dsh-team-control 0.1.6 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +55 -53
- package/index.js +1720 -167
- package/package.json +3 -3
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
|
|
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, {
|
|
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
|
|
681
|
-
// 模型偶尔会漏掉必填的 teamId
|
|
682
|
-
//
|
|
683
|
-
|
|
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
|
|
709
|
+
throw new Error('缺少 teamId:请把 team_create 返回的 result.team.id(形如 team_xxx)作为 teamId 参数传入后重试。');
|
|
686
710
|
}
|
|
687
711
|
const key = String(teamId);
|
|
688
|
-
|
|
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
|
-
|
|
693
|
-
return team
|
|
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
|
-
|
|
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
|
|
712
|
-
|
|
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,15 +1009,15 @@ 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
|
'执行要求:',
|
|
732
1015
|
'1) 直接在本会话里做这件事(用你自己的工具,不要委派给别的 agent)。',
|
|
733
1016
|
'2) 每开始或完成一步、以及验收通过后,调用 team_todo 更新该任务的计划清单(teamId/taskId 同上)。',
|
|
734
|
-
'3)
|
|
1017
|
+
'3) 收工前,如果这次任务产生了对后续任务可复用的结论(接口约定、坑、决策理由、未决问题),调用 team_memory_write 存一条简短 handoff(scope="member",kind="handoff",value 不超过 300 字);没有可复用结论就跳过,不要为了留记忆而写。只有 Lead 明确要求上传时才写 scope="team"。',
|
|
1018
|
+
'4) 完成或失败后必须调用 team_report_task,例如:',
|
|
735
1019
|
` team_report_task({ teamId: "${teamId}", taskId: "${task.id}", status: "done", summary: "一句话结果 + 关键产物路径" })`,
|
|
736
|
-
'
|
|
1020
|
+
'5) 需要 Lead 决策或补充信息时用 team_send(teamId 同上,to: "lead"),不要自己猜测。',
|
|
737
1021
|
].join('\n');
|
|
738
1022
|
}
|
|
739
1023
|
|
|
@@ -787,7 +1071,7 @@ async function dispatchLoop(s, ctx, teamId) {
|
|
|
787
1071
|
}
|
|
788
1072
|
const { task, member } = r;
|
|
789
1073
|
// 先记绑定再投递:成员第一轮 LLM 调用可能在 sendMessage 返回后就已开始
|
|
790
|
-
if (member.agentSessionId) rememberMember(member.agentSessionId, teamId, member.id);
|
|
1074
|
+
if (member.agentSessionId) rememberMember(member.agentSessionId, teamId, member.id, null, member.permissionPreset, member.name);
|
|
791
1075
|
// 任务已投递:先按「在跑」记账,agent/status 的 running 事件可能因为状态未变化而不发
|
|
792
1076
|
if (member.agentSessionId) agentStatusBySession.set(String(member.agentSessionId), 'running');
|
|
793
1077
|
try {
|
|
@@ -810,6 +1094,124 @@ async function dispatchLoop(s, ctx, teamId) {
|
|
|
810
1094
|
}
|
|
811
1095
|
}
|
|
812
1096
|
|
|
1097
|
+
// ---------- 权限审批转发:成员 preset 触发 approval/request → Lead 用 team_approve 决定 ----------
|
|
1098
|
+
const pendingApprovals = new Map();
|
|
1099
|
+
|
|
1100
|
+
function settleApproval(s, requestId, decision, reason, decidedBy) {
|
|
1101
|
+
const entry = pendingApprovals.get(requestId);
|
|
1102
|
+
if (!entry) return null;
|
|
1103
|
+
pendingApprovals.delete(requestId);
|
|
1104
|
+
clearTimeout(entry.timer);
|
|
1105
|
+
entry.signal?.removeEventListener?.('abort', entry.onAbort);
|
|
1106
|
+
const outcome = decision === 'allow' || decision === 'allowed-once'
|
|
1107
|
+
? 'allowed-once'
|
|
1108
|
+
: decision === 'cancelled' ? 'cancelled' : 'rejected';
|
|
1109
|
+
const recorded = outcome === 'allowed-once' ? 'allowed' : outcome;
|
|
1110
|
+
entry.resolve(outcome);
|
|
1111
|
+
void request(s, `/api/approvals/${encodeURIComponent(requestId)}/decide`, {
|
|
1112
|
+
method: 'POST',
|
|
1113
|
+
body: { decision: recorded, decidedBy: decidedBy || 'lead', ...(reason ? { reason } : {}) },
|
|
1114
|
+
}).catch(() => { /* 审计镜像失败不影响审批本身 */ });
|
|
1115
|
+
return entry;
|
|
1116
|
+
}
|
|
1117
|
+
|
|
1118
|
+
function cancelPendingApprovals() {
|
|
1119
|
+
for (const [requestId, entry] of [...pendingApprovals]) {
|
|
1120
|
+
pendingApprovals.delete(requestId);
|
|
1121
|
+
clearTimeout(entry.timer);
|
|
1122
|
+
entry.signal?.removeEventListener?.('abort', entry.onAbort);
|
|
1123
|
+
entry.resolve('cancelled');
|
|
1124
|
+
}
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
async function notifyLeadOfApproval(s, ctx, req, info) {
|
|
1128
|
+
const subs = subagentsOf(ctx);
|
|
1129
|
+
if (!subs || typeof subs.sendMessage !== 'function' || !req?.agent) return false;
|
|
1130
|
+
const team = await teamOf(s, info.teamId);
|
|
1131
|
+
const leadId = leadByTeam.get(info.teamId)?.id != null
|
|
1132
|
+
? String(leadByTeam.get(info.teamId).id)
|
|
1133
|
+
: (team.leadSessionId ? String(team.leadSessionId) : null);
|
|
1134
|
+
if (!leadId) return false;
|
|
1135
|
+
const minutes = Math.max(1, Math.round(s.approvalTimeoutMs / 60000));
|
|
1136
|
+
const text = [
|
|
1137
|
+
'【dsh-team 权限审批】',
|
|
1138
|
+
`teamId=${info.teamId}`,
|
|
1139
|
+
`memberId=${info.memberId}`,
|
|
1140
|
+
`memberName=${info.memberName || info.memberId}`,
|
|
1141
|
+
`toolName=${info.toolName || '(unknown)'}`,
|
|
1142
|
+
...(info.reason ? [`reason:${clip(info.reason, 500)}`] : []),
|
|
1143
|
+
`requestId=${info.requestId}`,
|
|
1144
|
+
'',
|
|
1145
|
+
`成员因 permissionPreset「${info.preset || 'unknown'}」的审批策略暂停,等待你决定。`,
|
|
1146
|
+
`批准本次操作:team_approve({ teamId: "${info.teamId}", requestId: "${info.requestId}", decision: "allow" })`,
|
|
1147
|
+
`拒绝:把 decision 改成 "deny"(可加 reason)。`,
|
|
1148
|
+
`超过 ${minutes} 分钟未决定将自动拒绝。`,
|
|
1149
|
+
].join('\n');
|
|
1150
|
+
await subs.sendMessage(req.agent, leadId, [{ type: 'text', text }], { signal: AbortSignal.timeout(s.requestTimeoutMs) });
|
|
1151
|
+
return true;
|
|
1152
|
+
}
|
|
1153
|
+
|
|
1154
|
+
async function onApprovalRequest(s, ctx, req, next) {
|
|
1155
|
+
const sessionId = req?.agent?.id != null ? String(req.agent.id) : null;
|
|
1156
|
+
const binding = sessionId ? sessionMember.get(sessionId) : null;
|
|
1157
|
+
// 不是本插件的成员:交回 DSH 原有审批链路(Lead 自己的审批仍走宿主 UI)。
|
|
1158
|
+
if (!binding) return next();
|
|
1159
|
+
|
|
1160
|
+
const requestId = String(req.id ?? req.requestId ?? `${sessionId}:${Date.now()}`);
|
|
1161
|
+
const info = {
|
|
1162
|
+
requestId,
|
|
1163
|
+
teamId: binding.teamId,
|
|
1164
|
+
memberId: binding.memberId,
|
|
1165
|
+
memberName: binding.name || null,
|
|
1166
|
+
sessionId,
|
|
1167
|
+
toolName: String(req.toolName || ''),
|
|
1168
|
+
reason: String(req.reason || ''),
|
|
1169
|
+
preset: binding.permissionPreset || null,
|
|
1170
|
+
};
|
|
1171
|
+
// 同一个请求重复进入(理论上不会)直接拒绝,避免两个 waiter 争同一个 id。
|
|
1172
|
+
if (pendingApprovals.has(requestId)) return 'rejected';
|
|
1173
|
+
|
|
1174
|
+
// 先镜像到 sidecar,面板/报告可见;失败不影响审批。
|
|
1175
|
+
void request(s, '/api/approvals', {
|
|
1176
|
+
method: 'POST',
|
|
1177
|
+
body: { id: requestId, teamId: info.teamId, memberId: info.memberId, sessionId, toolName: info.toolName, reason: info.reason },
|
|
1178
|
+
}).catch(() => { /* ignore */ });
|
|
1179
|
+
|
|
1180
|
+
const outcome = await new Promise((resolve) => {
|
|
1181
|
+
const timer = setTimeout(() => {
|
|
1182
|
+
if (!pendingApprovals.delete(requestId)) return;
|
|
1183
|
+
resolve('rejected');
|
|
1184
|
+
void request(s, `/api/approvals/${encodeURIComponent(requestId)}/decide`, {
|
|
1185
|
+
method: 'POST', body: { decision: 'expired', decidedBy: 'timeout', reason: 'approval timeout' },
|
|
1186
|
+
}).catch(() => {});
|
|
1187
|
+
}, s.approvalTimeoutMs);
|
|
1188
|
+
timer.unref?.();
|
|
1189
|
+
|
|
1190
|
+
const onAbort = () => {
|
|
1191
|
+
if (!pendingApprovals.delete(requestId)) return;
|
|
1192
|
+
clearTimeout(timer);
|
|
1193
|
+
resolve('cancelled');
|
|
1194
|
+
void request(s, `/api/approvals/${encodeURIComponent(requestId)}/decide`, {
|
|
1195
|
+
method: 'POST', body: { decision: 'cancelled', decidedBy: 'abort', reason: 'member turn aborted' },
|
|
1196
|
+
}).catch(() => {});
|
|
1197
|
+
};
|
|
1198
|
+
|
|
1199
|
+
pendingApprovals.set(requestId, { ...info, resolve, timer, signal: req.signal, onAbort });
|
|
1200
|
+
if (req.signal) req.signal.addEventListener?.('abort', onAbort, { once: true });
|
|
1201
|
+
|
|
1202
|
+
notifyLeadOfApproval(s, ctx, req, info).then((ok) => {
|
|
1203
|
+
if (ok) return;
|
|
1204
|
+
// 通知不到 Lead(服务缺失/没有 lead 会话):立刻拒绝,别让成员干等。
|
|
1205
|
+
const entry = pendingApprovals.get(requestId);
|
|
1206
|
+
if (entry) settleApproval(s, requestId, 'deny', '无法通知 Lead', 'system');
|
|
1207
|
+
}).catch(() => {
|
|
1208
|
+
const entry = pendingApprovals.get(requestId);
|
|
1209
|
+
if (entry) settleApproval(s, requestId, 'deny', '通知 Lead 失败', 'system');
|
|
1210
|
+
});
|
|
1211
|
+
});
|
|
1212
|
+
return outcome;
|
|
1213
|
+
}
|
|
1214
|
+
|
|
813
1215
|
/** agent/status 回写 sidecar:idle 时兜底收尾在途任务,running 时置 running。 */
|
|
814
1216
|
function reportAgentStatus(s, sessionId, status, detail) {
|
|
815
1217
|
if (!sessionId) return;
|
|
@@ -828,6 +1230,8 @@ const agentStatusBySession = new Map();
|
|
|
828
1230
|
const idleTimers = new Map();
|
|
829
1231
|
/** sessionId → 派发后「成员会话是否真的跑起来」的监视定时器。 */
|
|
830
1232
|
const startTimers = new Map();
|
|
1233
|
+
/** Lead 主动 interrupt 后冻结的会话:在 resume 前忽略其 idle / turn-error 回报。 */
|
|
1234
|
+
const heldSessions = new Set();
|
|
831
1235
|
|
|
832
1236
|
function cancelIdleReport(sessionId) {
|
|
833
1237
|
const timer = idleTimers.get(sessionId);
|
|
@@ -860,6 +1264,43 @@ function cancelStartWatchdog(sessionId) {
|
|
|
860
1264
|
if (timer) { clearTimeout(timer); startTimers.delete(sessionId); }
|
|
861
1265
|
}
|
|
862
1266
|
|
|
1267
|
+
/** 成员会话被替换/移除后,清掉插件侧所有指向旧 session 的绑定。 */
|
|
1268
|
+
function forgetSession(sessionId) {
|
|
1269
|
+
if (sessionId == null) return;
|
|
1270
|
+
const sid = String(sessionId);
|
|
1271
|
+
cancelIdleReport(sid);
|
|
1272
|
+
cancelStartWatchdog(sid);
|
|
1273
|
+
heldSessions.delete(sid);
|
|
1274
|
+
agentStatusBySession.delete(sid);
|
|
1275
|
+
sessionMember.delete(sid);
|
|
1276
|
+
}
|
|
1277
|
+
|
|
1278
|
+
/**
|
|
1279
|
+
* 释放成员子会话:优先 drainChildren(从父会话摘除并结束),
|
|
1280
|
+
* 旧版 subagents 没有该能力时退回 interrupt。
|
|
1281
|
+
*/
|
|
1282
|
+
async function releaseSession(subs, caller, sessionId) {
|
|
1283
|
+
if (!sessionId) return { ok: true, method: 'none' };
|
|
1284
|
+
const sid = String(sessionId);
|
|
1285
|
+
if (typeof subs?.drainChildren === 'function') {
|
|
1286
|
+
try {
|
|
1287
|
+
await subs.drainChildren(caller, [sid]);
|
|
1288
|
+
return { ok: true, method: 'drainChildren' };
|
|
1289
|
+
} catch (err) {
|
|
1290
|
+
if (typeof subs?.interrupt !== 'function') return { ok: false, error: String(err?.message || err) };
|
|
1291
|
+
}
|
|
1292
|
+
}
|
|
1293
|
+
if (typeof subs?.interrupt === 'function') {
|
|
1294
|
+
try {
|
|
1295
|
+
await subs.interrupt(sid, { kind: 'ancestor', agent: caller });
|
|
1296
|
+
return { ok: true, method: 'interrupt' };
|
|
1297
|
+
} catch (err) {
|
|
1298
|
+
return { ok: false, error: String(err?.message || err) };
|
|
1299
|
+
}
|
|
1300
|
+
}
|
|
1301
|
+
return { ok: false, error: 'subagents 服务不支持 drainChildren/interrupt' };
|
|
1302
|
+
}
|
|
1303
|
+
|
|
863
1304
|
/** 直接读 sidecar /status(不经 request:心跳/镜像不能顺手把 sidecar 拉起来)。 */
|
|
864
1305
|
async function readStatus(s) {
|
|
865
1306
|
try {
|
|
@@ -872,6 +1313,46 @@ async function readStatus(s) {
|
|
|
872
1313
|
} catch { return null; }
|
|
873
1314
|
}
|
|
874
1315
|
|
|
1316
|
+
/** sessionId → 最近一次从 sidecar 看到的成员状态;用于只强制中断一次。 */
|
|
1317
|
+
const forceStopSeen = new Map();
|
|
1318
|
+
|
|
1319
|
+
/**
|
|
1320
|
+
* 面板/看板停止只走 sidecar(不经过 Host 插件),sidecar 改不了 DSH 会话。
|
|
1321
|
+
* 这里轮询成员状态:一旦看到 running → interrupted,就用登记的直接父会话
|
|
1322
|
+
* 以 user 授权调用 subagents.interrupt,真正停掉成员当前回合,并冻结该会话,
|
|
1323
|
+
* 防止 DSH 中断后的 idle 又把成员改回 idle。
|
|
1324
|
+
*/
|
|
1325
|
+
async function forceStopPump(s, ctx) {
|
|
1326
|
+
const subs = subagentsOf(ctx);
|
|
1327
|
+
if (!subs || typeof subs.interrupt !== 'function') return;
|
|
1328
|
+
const status = await readStatus(s);
|
|
1329
|
+
if (!status || !Array.isArray(status.members)) return;
|
|
1330
|
+
const live = new Set();
|
|
1331
|
+
for (const m of status.members) {
|
|
1332
|
+
const sid = m?.agentSessionId != null ? String(m.agentSessionId) : null;
|
|
1333
|
+
if (!sid) continue;
|
|
1334
|
+
live.add(sid);
|
|
1335
|
+
const prev = forceStopSeen.get(sid);
|
|
1336
|
+
forceStopSeen.set(sid, m.status);
|
|
1337
|
+
if (m.status !== 'interrupted' || prev === 'interrupted') continue;
|
|
1338
|
+
if (heldSessions.has(sid)) continue;
|
|
1339
|
+
const parentSessionId = m.parentSessionId != null ? String(m.parentSessionId) : null;
|
|
1340
|
+
if (!parentSessionId) continue;
|
|
1341
|
+
heldSessions.add(sid);
|
|
1342
|
+
cancelIdleReport(sid);
|
|
1343
|
+
cancelStartWatchdog(sid);
|
|
1344
|
+
agentStatusBySession.set(sid, 'interrupted');
|
|
1345
|
+
try {
|
|
1346
|
+
await Promise.resolve(subs.interrupt(sid, { kind: 'user', parentSessionId }));
|
|
1347
|
+
} catch {
|
|
1348
|
+
// 会话可能已经结束;撤销冻结并清掉 seen,让下一跳还能重试。
|
|
1349
|
+
heldSessions.delete(sid);
|
|
1350
|
+
forceStopSeen.delete(sid);
|
|
1351
|
+
}
|
|
1352
|
+
}
|
|
1353
|
+
for (const sid of forceStopSeen.keys()) if (!live.has(sid)) forceStopSeen.delete(sid);
|
|
1354
|
+
}
|
|
1355
|
+
|
|
875
1356
|
/** DSH 内置 todo 的状态 → sidecar 计划步骤的状态。 */
|
|
876
1357
|
const TODO_TO_PLAN = { pending: 'open', in_progress: 'active', completed: 'done' };
|
|
877
1358
|
|
|
@@ -935,6 +1416,63 @@ async function markDelivered(s, messageId) {
|
|
|
935
1416
|
}).catch(() => { /* 回执补记失败不影响投递 */ });
|
|
936
1417
|
}
|
|
937
1418
|
|
|
1419
|
+
/**
|
|
1420
|
+
* 面板 steer 队列的投递泵。
|
|
1421
|
+
*
|
|
1422
|
+
* 面板(或任何外部调用)只把 `kind='steer'` 的消息写进 sidecar 信箱,sidecar 不会自己送进成员会话;
|
|
1423
|
+
* 这里定时取 queued 的 steer 消息,用 `subagents.sendMessage` 推进成员会话后补记送达。
|
|
1424
|
+
* - `payload.immediate=true`(面板 ⌘/Ctrl+↵ 或队列 chip 的「Now」)排到最前,只是优先投递,不打断当前回合;
|
|
1425
|
+
* - 每个成员每轮只投一条,避免一次性灌爆成员上下文;
|
|
1426
|
+
* - 投递失败保持 queued,下一轮重试;成员已无会话(worker / 已回收)就留在队列里等人工处理。
|
|
1427
|
+
*/
|
|
1428
|
+
const steerInFlight = new Set();
|
|
1429
|
+
|
|
1430
|
+
async function steerPump(s, ctx) {
|
|
1431
|
+
if (!sessionMember.size) return;
|
|
1432
|
+
const subs = subagentsOf(ctx);
|
|
1433
|
+
if (!subs || typeof subs.sendMessage !== 'function') return;
|
|
1434
|
+
const teams = new Set();
|
|
1435
|
+
for (const binding of sessionMember.values()) if (binding?.teamId) teams.add(binding.teamId);
|
|
1436
|
+
|
|
1437
|
+
for (const teamId of teams) {
|
|
1438
|
+
const caller = leadByTeam.get(teamId);
|
|
1439
|
+
if (!caller) continue;
|
|
1440
|
+
const res = await request(
|
|
1441
|
+
s,
|
|
1442
|
+
`/api/messages${qs({ team: teamId, status: 'queued', limit: 100 })}`,
|
|
1443
|
+
).catch(() => null);
|
|
1444
|
+
const rows = Array.isArray(res) ? res : (Array.isArray(res?.items) ? res.items : []);
|
|
1445
|
+
const items = rows.filter(
|
|
1446
|
+
(m) => m && m.kind === 'steer' && m.to && m.to !== 'lead' && m.status === 'queued' && !steerInFlight.has(m.id),
|
|
1447
|
+
);
|
|
1448
|
+
items.sort((a, b) => {
|
|
1449
|
+
const priority = Number(!!b.payload?.immediate) - Number(!!a.payload?.immediate);
|
|
1450
|
+
return priority || String(a.sentAt || '').localeCompare(String(b.sentAt || ''));
|
|
1451
|
+
});
|
|
1452
|
+
|
|
1453
|
+
const taken = new Set();
|
|
1454
|
+
for (const message of items) {
|
|
1455
|
+
const target = String(message.to);
|
|
1456
|
+
if (taken.has(target)) continue; // 每个成员每轮只投一条
|
|
1457
|
+
const binding = [...sessionMember.entries()].find(
|
|
1458
|
+
([, b]) => b && b.memberId === target && b.teamId === teamId,
|
|
1459
|
+
);
|
|
1460
|
+
if (!binding) continue; // 该成员没有 sub-agent 会话:留队列,等重新 spawn
|
|
1461
|
+
taken.add(target);
|
|
1462
|
+
const text = String(message.payload?.text || '').trim();
|
|
1463
|
+
if (!text) { await markDelivered(s, message.id); continue; }
|
|
1464
|
+
steerInFlight.add(message.id);
|
|
1465
|
+
try {
|
|
1466
|
+
await subs.sendMessage(caller, String(binding[0]), [{ type: 'text', text }], {
|
|
1467
|
+
signal: AbortSignal.timeout(s.requestTimeoutMs),
|
|
1468
|
+
});
|
|
1469
|
+
await markDelivered(s, message.id);
|
|
1470
|
+
} catch { /* 成员会话暂时不可写:保持 queued,下一轮重试 */ }
|
|
1471
|
+
finally { steerInFlight.delete(message.id); }
|
|
1472
|
+
}
|
|
1473
|
+
}
|
|
1474
|
+
}
|
|
1475
|
+
|
|
938
1476
|
/** 成员会话这一轮最后的助手正文:收工时落库成 member→lead 的回复消息。 */
|
|
939
1477
|
const lastReplyBySession = new Map();
|
|
940
1478
|
|
|
@@ -978,28 +1516,19 @@ async function flushMemberReply(s, sessionId) {
|
|
|
978
1516
|
const PLAN_STEP = {
|
|
979
1517
|
type: 'object',
|
|
980
1518
|
additionalProperties: true,
|
|
981
|
-
description: 'One
|
|
1519
|
+
description: 'One plan step / brief line handed to the member sub-agent. Purely descriptive: the member executes it with its own tools.',
|
|
982
1520
|
properties: {
|
|
983
1521
|
step: { type: 'string', description: 'Step label, e.g. S1.' },
|
|
984
1522
|
phase: {
|
|
985
1523
|
type: 'string',
|
|
986
|
-
description: '
|
|
1524
|
+
description: 'Optional phase used in the timeline: init|read|write|exec|net|env|msg|wait|verify|done|fail.',
|
|
987
1525
|
},
|
|
988
1526
|
action: { type: 'string', description: 'Verb shown in the timeline, e.g. write / read / exec.' },
|
|
989
1527
|
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' },
|
|
1528
|
+
op: { type: 'object', additionalProperties: true, description: 'Optional legacy detail (ignored by the sidecar).' },
|
|
1000
1529
|
fatal: { type: 'boolean' },
|
|
1001
1530
|
},
|
|
1002
|
-
required: ['step'
|
|
1531
|
+
required: ['step'],
|
|
1003
1532
|
};
|
|
1004
1533
|
|
|
1005
1534
|
const MEMBER_FIELDS = {
|
|
@@ -1022,35 +1551,442 @@ const textOutput = () => ({
|
|
|
1022
1551
|
render: (_args, value) => [{ type: 'text', text: String(value?.markdown ?? value) }],
|
|
1023
1552
|
});
|
|
1024
1553
|
|
|
1554
|
+
|
|
1555
|
+
// ---------------------------------------------------------------------------
|
|
1556
|
+
// 工作区看板:Host 侧调度
|
|
1557
|
+
//
|
|
1558
|
+
// sidecar 只负责状态/并发/claim;这里按 claim 结果创建根会话并投 prompt。
|
|
1559
|
+
// 规划默认只读,执行用 danger-full-access(无人值守会话不能停在审批 UI)。
|
|
1560
|
+
// ---------------------------------------------------------------------------
|
|
1561
|
+
const boardSessions = new Map(); // sessionId -> { taskId, phase, handle, sawRunning }
|
|
1562
|
+
const boardSessionIds = new Set();
|
|
1563
|
+
|
|
1564
|
+
function boardUserMessage(text) {
|
|
1565
|
+
return {
|
|
1566
|
+
id: randomUUID(),
|
|
1567
|
+
role: 'user',
|
|
1568
|
+
content: [{ type: 'text', text: String(text) }],
|
|
1569
|
+
source: { kind: 'user' },
|
|
1570
|
+
};
|
|
1571
|
+
}
|
|
1572
|
+
|
|
1573
|
+
function boardRoute(task, settings, kind) {
|
|
1574
|
+
const one = (provider, model, reasoningEffort) => (model
|
|
1575
|
+
? { ...(provider ? { provider } : {}), model, ...(reasoningEffort ? { reasoningEffort } : {}) }
|
|
1576
|
+
: null);
|
|
1577
|
+
const list = kind === 'planning'
|
|
1578
|
+
? [
|
|
1579
|
+
[task.planRoute?.provider, task.planRoute?.model, task.planRoute?.reasoningEffort],
|
|
1580
|
+
[settings.planProvider, settings.planModel, settings.planReasoningEffort],
|
|
1581
|
+
[task.leadRoute?.provider, task.leadRoute?.model, task.leadRoute?.reasoningEffort],
|
|
1582
|
+
[settings.leadProvider, settings.leadModel, settings.leadReasoningEffort],
|
|
1583
|
+
]
|
|
1584
|
+
: [
|
|
1585
|
+
[task.leadRoute?.provider, task.leadRoute?.model, task.leadRoute?.reasoningEffort],
|
|
1586
|
+
[settings.leadProvider, settings.leadModel, settings.leadReasoningEffort],
|
|
1587
|
+
];
|
|
1588
|
+
for (const [provider, model, effort] of list) {
|
|
1589
|
+
const route = one(provider, model, effort);
|
|
1590
|
+
if (route) return route;
|
|
1591
|
+
}
|
|
1592
|
+
return undefined;
|
|
1593
|
+
}
|
|
1594
|
+
|
|
1595
|
+
function boardRouteOrDefault(ctx, task, settings, kind) {
|
|
1596
|
+
const route = boardRoute(task, settings, kind);
|
|
1597
|
+
if (route) return route;
|
|
1598
|
+
try {
|
|
1599
|
+
const cur = ctx.get('agentDefaultModel')?.currentSelection?.();
|
|
1600
|
+
if (cur?.model) return { ...(cur.provider ? { provider: cur.provider } : {}), model: cur.model };
|
|
1601
|
+
} catch { /* ignore */ }
|
|
1602
|
+
return undefined;
|
|
1603
|
+
}
|
|
1604
|
+
|
|
1605
|
+
function boardSetPermission(ctx, agent, preset) {
|
|
1606
|
+
if (!preset) return { applied: false };
|
|
1607
|
+
const svc = permissionPresetsOf(ctx);
|
|
1608
|
+
if (!svc || typeof svc.set !== 'function') return { applied: false, reason: 'permissionPresets 不可用' };
|
|
1609
|
+
try {
|
|
1610
|
+
svc.set(agent.session, preset);
|
|
1611
|
+
return { applied: true, preset };
|
|
1612
|
+
} catch (err) {
|
|
1613
|
+
return { applied: false, preset, error: String(err?.message || err) };
|
|
1614
|
+
}
|
|
1615
|
+
}
|
|
1616
|
+
|
|
1617
|
+
function boardPromptModels(task) {
|
|
1618
|
+
return Array.isArray(task.teamModels) && task.teamModels.length
|
|
1619
|
+
? task.teamModels.map((m) => (typeof m === 'string' ? m : `${m.provider ? m.provider + '/' : ''}${m.model}`)).join('\n')
|
|
1620
|
+
: '不限制';
|
|
1621
|
+
}
|
|
1622
|
+
|
|
1623
|
+
function boardPlanningPrompt(task, settings) {
|
|
1624
|
+
const useTeam = task.useTeam !== false;
|
|
1625
|
+
const models = boardPromptModels(task);
|
|
1626
|
+
const head = [
|
|
1627
|
+
`你是「${task.title}」的规划 Agent。只做规划,不写代码、不修改文件、不创建团队。`,
|
|
1628
|
+
'规划完成后不要开始执行;调度器会在执行槽位空出后,在同一会话里让你继续。',
|
|
1629
|
+
'',
|
|
1630
|
+
`工作区:${task.workspacePath}`,
|
|
1631
|
+
'任务描述:',
|
|
1632
|
+
task.description || '(无)',
|
|
1633
|
+
'',
|
|
1634
|
+
];
|
|
1635
|
+
const body = useTeam
|
|
1636
|
+
? [
|
|
1637
|
+
'可用模型(成员分配只能从这里选):',
|
|
1638
|
+
models,
|
|
1639
|
+
'',
|
|
1640
|
+
'开始规划前,先加载 `dsh-agent-team` 技能(调用 skill 工具,参数 {"name":"dsh-agent-team"}),按技能里的团队编排流程与工具字段规划。',
|
|
1641
|
+
'',
|
|
1642
|
+
'请先阅读必要文件,然后输出一份可执行计划,必须包含:',
|
|
1643
|
+
'1. 目标与验收标准',
|
|
1644
|
+
'2. 实施步骤(到文件/模块级)',
|
|
1645
|
+
'3. 团队与成员建议(每个成员的角色、模型、依赖关系)',
|
|
1646
|
+
'4. 风险与回滚',
|
|
1647
|
+
]
|
|
1648
|
+
: [
|
|
1649
|
+
'本任务不开启团队:执行阶段由单个 Agent 独立完成,不需要规划成员或 DAG。',
|
|
1650
|
+
'',
|
|
1651
|
+
'请先阅读必要文件,然后输出一份可执行计划,必须包含:',
|
|
1652
|
+
'1. 目标与验收标准',
|
|
1653
|
+
'2. 实施步骤(到文件/模块级)',
|
|
1654
|
+
'3. 风险与回滚',
|
|
1655
|
+
];
|
|
1656
|
+
return [
|
|
1657
|
+
...head,
|
|
1658
|
+
...body,
|
|
1659
|
+
'',
|
|
1660
|
+
'最后必须调用 board_plan_submit({ plan: "<完整 markdown>", summary: "<一句话>" })。',
|
|
1661
|
+
'不要只把计划写在回复里。提交后停下,等待执行指令。',
|
|
1662
|
+
].join('\n');
|
|
1663
|
+
}
|
|
1664
|
+
|
|
1665
|
+
function boardLeadPrompt(task, sameSession) {
|
|
1666
|
+
const useTeam = task.useTeam !== false;
|
|
1667
|
+
const needPlan = task.needPlan !== false;
|
|
1668
|
+
const models = boardPromptModels(task);
|
|
1669
|
+
// 任务已有关联团队(重试、失败后继续、或完成后再次执行)时,在原团队上接着干,
|
|
1670
|
+
// 不要每轮都 team_create 出一个新团队。
|
|
1671
|
+
const teams = Array.isArray(task.teams) ? task.teams.filter(Boolean).map(String) : [];
|
|
1672
|
+
const teamRule = teams.length
|
|
1673
|
+
? `1. 本任务已关联团队:${teams.join('、')}。不要调用 team_create 新建团队:先 team_status 查看这些团队的现状,`
|
|
1674
|
+
+ '在原团队里用 team_task 追加剩余工作继续推进;已经完成的成员任务不要重复创建。'
|
|
1675
|
+
+ '只有原团队已被删除或全部不可用时,才允许 team_create 新团队(若既有团队需要继续保留、只是要并行新建,必须显式传 force: true)。'
|
|
1676
|
+
: '1. 先调用 team_create 创建团队;name 用任务标题,workspace 用上面的路径。需要多个团队就多次创建,所有团队都会自动绑定到本任务。';
|
|
1677
|
+
const teamRules = [
|
|
1678
|
+
'开始执行前,先加载 `dsh-agent-team` 技能(调用 skill 工具,参数 {"name":"dsh-agent-team"}),按技能里的团队编排流程、工具字段与常见错法执行,不要凭记忆猜参数。',
|
|
1679
|
+
'',
|
|
1680
|
+
'规则:',
|
|
1681
|
+
teamRule,
|
|
1682
|
+
'2. 调用 team_models 查看可用路由;只能使用以下模型:',
|
|
1683
|
+
models,
|
|
1684
|
+
'3. 用 team_task 拆解并派发;用 team_status / team_report 跟踪。不要自己写代码,不要重复成员的工作。',
|
|
1685
|
+
'4. 全部任务成功后,必须调用 board_task_status({ status: "done", summary: "<完成摘要>" })。',
|
|
1686
|
+
'5. 无法完成时调用 board_task_status({ status: "failed", summary: "<原因>" })。',
|
|
1687
|
+
'6. 之后如果用户再次发消息,先调用 board_task_status({ status: "inprogress" }),再继续处理。',
|
|
1688
|
+
];
|
|
1689
|
+
const soloRules = [
|
|
1690
|
+
'本任务不开启团队:由你自己直接完成所有工作,不要调用 team_create / team_spawn / team_task。',
|
|
1691
|
+
'',
|
|
1692
|
+
'规则:',
|
|
1693
|
+
'1. 按任务描述直接修改文件、运行命令并验证结果。',
|
|
1694
|
+
'2. 全部工作完成后,必须调用 board_task_status({ status: "done", summary: "<完成摘要>" })。',
|
|
1695
|
+
'3. 无法完成时调用 board_task_status({ status: "failed", summary: "<原因>" })。',
|
|
1696
|
+
'4. 之后如果用户再次发消息,先调用 board_task_status({ status: "inprogress" }),再继续处理。',
|
|
1697
|
+
];
|
|
1698
|
+
const rules = useTeam ? teamRules : soloRules;
|
|
1699
|
+
// 同会话执行:计划已经在同一会话的上文里,不再重复注入任务描述与 plan 全文。
|
|
1700
|
+
if (sameSession) {
|
|
1701
|
+
return [
|
|
1702
|
+
`现在开始执行「${task.title}」。计划就在同一会话的上文里,不要重复输出计划。`,
|
|
1703
|
+
'',
|
|
1704
|
+
...rules,
|
|
1705
|
+
].join('\n');
|
|
1706
|
+
}
|
|
1707
|
+
const lines = [
|
|
1708
|
+
`你是任务「${task.title}」的${useTeam ? ' Lead' : '执行 Agent'}。工作区:${task.workspacePath}`,
|
|
1709
|
+
needPlan ? '以下是规划会话产出的计划,现在开始执行。' : '本任务不需要规划,直接开始执行。',
|
|
1710
|
+
'',
|
|
1711
|
+
'任务描述:',
|
|
1712
|
+
task.description || '(无)',
|
|
1713
|
+
];
|
|
1714
|
+
if (needPlan) lines.push('', '已确认的计划:', task.planMd || '(无)');
|
|
1715
|
+
lines.push('', ...rules);
|
|
1716
|
+
return lines.join('\n');
|
|
1717
|
+
}
|
|
1718
|
+
|
|
1719
|
+
async function boardTaskOf(s, sessionId) {
|
|
1720
|
+
if (!sessionId) return null;
|
|
1721
|
+
try {
|
|
1722
|
+
const r = await request(s, `/api/board/by-session/${encodeURIComponent(sessionId)}`);
|
|
1723
|
+
return r && r.id ? r : null;
|
|
1724
|
+
} catch { return null; }
|
|
1725
|
+
}
|
|
1726
|
+
|
|
1727
|
+
async function bindBoardTeam(s, exec, teamId) {
|
|
1728
|
+
const sessionId = exec?.agent?.id != null ? String(exec.agent.id) : null;
|
|
1729
|
+
if (!sessionId || !teamId) return;
|
|
1730
|
+
try {
|
|
1731
|
+
const task = await boardTaskOf(s, sessionId);
|
|
1732
|
+
if (task) await request(s, `/api/board/tasks/${encodeURIComponent(task.id)}/teams`, { method: 'POST', body: { teamId } });
|
|
1733
|
+
} catch { /* 绑定失败不影响团队创建 */ }
|
|
1734
|
+
}
|
|
1735
|
+
|
|
1736
|
+
/**
|
|
1737
|
+
* 重试/续跑出来的 Lead 会话(spawn 时任务已有团队)默认禁止重复建队:
|
|
1738
|
+
* 提示词是软约束,这里做成硬约束,避免模型不听话又多出一个团队。
|
|
1739
|
+
* 只有 `force:true` 或原团队全部已被删除/归档时才放行。
|
|
1740
|
+
*/
|
|
1741
|
+
async function guardBoardTeamReuse(s, sessionId, force) {
|
|
1742
|
+
if (force || !sessionId) return;
|
|
1743
|
+
const rec = boardSessions.get(String(sessionId));
|
|
1744
|
+
if (!rec?.reusedRun) return;
|
|
1745
|
+
const task = await boardTaskOf(s, String(sessionId));
|
|
1746
|
+
const teamIds = Array.isArray(task?.teams) ? task.teams.filter(Boolean).map(String) : [];
|
|
1747
|
+
if (!teamIds.length) return;
|
|
1748
|
+
const alive = [];
|
|
1749
|
+
for (const id of teamIds) {
|
|
1750
|
+
try {
|
|
1751
|
+
const team = await request(s, `/api/teams/${encodeURIComponent(id)}`);
|
|
1752
|
+
if (team && !team.archivedAt) alive.push(`${team.id}(${team.name || '未命名'})`);
|
|
1753
|
+
} catch { /* 团队已不存在 */ }
|
|
1754
|
+
}
|
|
1755
|
+
if (!alive.length) return;
|
|
1756
|
+
throw new Error(
|
|
1757
|
+
`本任务已关联团队:${alive.join('、')}。重试/续跑请在原团队上继续:先用 team_status 查看现状,再用 team_task 追加剩余工作,不要重复 team_create。`
|
|
1758
|
+
+ '确实需要与之并行新建团队时,调用 team_create 并显式传 force: true。',
|
|
1759
|
+
);
|
|
1760
|
+
}
|
|
1761
|
+
|
|
1762
|
+
/**
|
|
1763
|
+
* 把看板会话挂进 DSH 工作区会话账本,让它在「工作区会话」列表里可见。
|
|
1764
|
+
* 受看板设置 showTaskSessions 控制(缺省开启);失败只告警,不影响任务推进。
|
|
1765
|
+
*/
|
|
1766
|
+
async function attachBoardSessionToWorkspace(ctx, task, sessionId) {
|
|
1767
|
+
try {
|
|
1768
|
+
const registry = ctx.get('workspaceRegistry');
|
|
1769
|
+
if (!registry || typeof registry.get !== 'function' || !task.workspaceId) return;
|
|
1770
|
+
const workspace = registry.get(task.workspaceId);
|
|
1771
|
+
if (!workspace || typeof workspace.attachSession !== 'function') return;
|
|
1772
|
+
await workspace.attachSession(String(sessionId));
|
|
1773
|
+
} catch (err) {
|
|
1774
|
+
console.warn(`[dsh-team] attach board session to workspace failed: ${String(err?.message || err)}`);
|
|
1775
|
+
}
|
|
1776
|
+
}
|
|
1777
|
+
|
|
1778
|
+
async function spawnBoardSession(s, ctx, item) {
|
|
1779
|
+
const { task, workspace, settings, fence } = item;
|
|
1780
|
+
const agents = (() => { try { return ctx.get('agents'); } catch { return undefined; } })();
|
|
1781
|
+
if (!agents || typeof agents.create !== 'function') throw new Error('agents 服务不可用:无法创建看板会话');
|
|
1782
|
+
|
|
1783
|
+
const kind = task.status === 'planning' ? 'planning' : 'inprogress';
|
|
1784
|
+
// spawn 时任务已有团队(重试、失败后续跑、或再次执行)→ 该会话属于续跑,
|
|
1785
|
+
// 允许复用既有团队但默认禁止再建新团队(见 guardBoardTeamReuse)。
|
|
1786
|
+
const hadTeams = Array.isArray(task.teams) && task.teams.filter(Boolean).length > 0;
|
|
1787
|
+
// 任何已有 Lead 会话的 inprogress 都复用该会话:same 模式的首轮、
|
|
1788
|
+
// 以及 new 模式完成后用户追问,都不能再新建会话。
|
|
1789
|
+
const sameSession = kind === 'inprogress' && !!task.leadSessionId;
|
|
1790
|
+
|
|
1791
|
+
// 同会话执行:复用规划会话,只切权限 + 投执行 prompt。
|
|
1792
|
+
if (sameSession) {
|
|
1793
|
+
const sessionId = String(task.leadSessionId);
|
|
1794
|
+
let agent = boardSessions.get(sessionId)?.handle?.agent;
|
|
1795
|
+
if (!agent && typeof agents.get === 'function') {
|
|
1796
|
+
try { agent = agents.get(sessionId); } catch { agent = undefined; }
|
|
1797
|
+
}
|
|
1798
|
+
if (!agent) {
|
|
1799
|
+
await request(s, `/api/board/tasks/${encodeURIComponent(task.id)}/release`, {
|
|
1800
|
+
method: 'POST', body: { kind: 'inprogress', error: 'session_not_live' },
|
|
1801
|
+
}).catch(() => {});
|
|
1802
|
+
return;
|
|
1803
|
+
}
|
|
1804
|
+
await request(s, `/api/board/tasks/${encodeURIComponent(task.id)}/attach`, {
|
|
1805
|
+
method: 'POST', body: { kind: 'inprogress', sessionId, fence },
|
|
1806
|
+
});
|
|
1807
|
+
boardSetPermission(ctx, agent, settings.leadPermissionPreset);
|
|
1808
|
+
if (settings.showTaskSessions !== false) await attachBoardSessionToWorkspace(ctx, task, sessionId);
|
|
1809
|
+
const rec = boardSessions.get(sessionId) || { taskId: task.id, handle: { agent }, sawRunning: false, reusedRun: hadTeams };
|
|
1810
|
+
rec.phase = 'execution';
|
|
1811
|
+
rec.sawRunning = false;
|
|
1812
|
+
boardSessions.set(sessionId, rec);
|
|
1813
|
+
boardSessionIds.add(sessionId);
|
|
1814
|
+
// 用户追问触发 done→inprogress 时,真实用户消息已经在会话里;
|
|
1815
|
+
// 这里只恢复状态与权限,不再注入重复的执行 prompt。
|
|
1816
|
+
if (!task.resumed) agent.followup(boardUserMessage(boardLeadPrompt(task, true)));
|
|
1817
|
+
return;
|
|
1818
|
+
}
|
|
1819
|
+
|
|
1820
|
+
// 新建会话:规划或「在新的会话执行」。
|
|
1821
|
+
const route = boardRouteOrDefault(ctx, task, settings, kind);
|
|
1822
|
+
const requestedPreset = kind === 'planning' ? settings.planAgentPreset : settings.leadAgentPreset;
|
|
1823
|
+
let presetId = null;
|
|
1824
|
+
try { presetId = await resolveAgentPreset(ctx, requestedPreset, null, s); } catch { presetId = null; }
|
|
1825
|
+
// 看板会话是根会话,没有父组合可继承;不显式挂 preset 就只剩宿主级工具
|
|
1826
|
+
// (没有 standard 的 shell/文件工具),成员再继承它也会一起缺。
|
|
1827
|
+
if (!presetId) presetId = await hostDefaultAgentPreset(ctx);
|
|
1828
|
+
const presetSvc = agentPresetsOf(ctx);
|
|
1829
|
+
let resolved = null;
|
|
1830
|
+
if (presetId && presetSvc && typeof presetSvc.resolve === 'function') {
|
|
1831
|
+
try { resolved = await presetSvc.resolve(presetId); } catch { resolved = null; }
|
|
1832
|
+
}
|
|
1833
|
+
const cwd = task.workspacePath || workspace.path;
|
|
1834
|
+
if (!cwd) throw new Error('工作区路径为空');
|
|
1835
|
+
fs.mkdirSync(cwd, { recursive: true });
|
|
1836
|
+
const sessionId = `session-${randomUUID()}`;
|
|
1837
|
+
let handle = null;
|
|
1838
|
+
let step = 'create';
|
|
1839
|
+
try {
|
|
1840
|
+
handle = await agents.create({
|
|
1841
|
+
sessionId,
|
|
1842
|
+
...(route ? { agentOptions: route } : {}),
|
|
1843
|
+
meta: { cwd, ...(resolved ? { agentPreset: resolved.id } : {}) },
|
|
1844
|
+
setup: async (agentCtx) => {
|
|
1845
|
+
if (!resolved || !presetSvc || typeof presetSvc.mount !== 'function') return;
|
|
1846
|
+
await presetSvc.mount(agentCtx, resolved.id);
|
|
1847
|
+
},
|
|
1848
|
+
});
|
|
1849
|
+
boardSetPermission(ctx, handle.agent, kind === 'planning' ? settings.planPermissionPreset : settings.leadPermissionPreset);
|
|
1850
|
+
step = 'attach';
|
|
1851
|
+
await request(s, `/api/board/tasks/${encodeURIComponent(task.id)}/attach`, {
|
|
1852
|
+
method: 'POST', body: { kind, sessionId, fence },
|
|
1853
|
+
});
|
|
1854
|
+
if (settings.showTaskSessions !== false) await attachBoardSessionToWorkspace(ctx, task, sessionId);
|
|
1855
|
+
boardSessions.set(sessionId, { taskId: task.id, phase: kind, handle, sawRunning: false, reusedRun: hadTeams });
|
|
1856
|
+
boardSessionIds.add(sessionId);
|
|
1857
|
+
handle.agent.followup(boardUserMessage(kind === 'planning'
|
|
1858
|
+
? boardPlanningPrompt(task, settings)
|
|
1859
|
+
: boardLeadPrompt(task, false)));
|
|
1860
|
+
} catch (err) {
|
|
1861
|
+
console.warn(`[dsh-team] board ${step} failed: ${String(err?.message || err)} cause=${String(err?.cause?.code || err?.cause || '')}`);
|
|
1862
|
+
try { await handle?.dispose?.(); } catch { /* ignore */ }
|
|
1863
|
+
await request(s, `/api/board/tasks/${encodeURIComponent(task.id)}/release`, {
|
|
1864
|
+
method: 'POST', body: { kind, error: String(err?.message || err) },
|
|
1865
|
+
}).catch(() => {});
|
|
1866
|
+
throw err;
|
|
1867
|
+
}
|
|
1868
|
+
}
|
|
1869
|
+
|
|
1870
|
+
async function boardPump(s, ctx) {
|
|
1871
|
+
if (!s.boardEnabled) return;
|
|
1872
|
+
const agents = (() => { try { return ctx.get('agents'); } catch { return undefined; } })();
|
|
1873
|
+
if (!agents || typeof agents.create !== 'function') return;
|
|
1874
|
+
// 规划超时:插件崩溃/会话卡死时,避免任务永久占着 planning 槽位。
|
|
1875
|
+
try {
|
|
1876
|
+
const live = await request(s, '/api/board/live');
|
|
1877
|
+
for (const task of live?.tasks || []) {
|
|
1878
|
+
// 插件重启后 boardSessions 是空的:能找回 live agent 就接管,找不回就把
|
|
1879
|
+
// 永远不可能再推进的任务置 failed,避免占着槽位。
|
|
1880
|
+
if (task.status === 'done' || task.status === 'failed') {
|
|
1881
|
+
// 规划被 stop/failed 后,规划会话已无用途,直接释放。
|
|
1882
|
+
const planSid = task.planningSessionId;
|
|
1883
|
+
const planRec = planSid ? boardSessions.get(String(planSid)) : null;
|
|
1884
|
+
if (planRec && planRec.phase === 'planning') {
|
|
1885
|
+
try { void planRec.handle?.dispose?.(); } catch { /* ignore */ }
|
|
1886
|
+
boardSessions.delete(String(planSid));
|
|
1887
|
+
boardSessionIds.delete(String(planSid));
|
|
1888
|
+
}
|
|
1889
|
+
// 终态任务的 Lead 会话仍可能收到用户追问;重启后把它重新纳入监听。
|
|
1890
|
+
const sid = task.leadSessionId;
|
|
1891
|
+
if (sid && !boardSessionIds.has(String(sid))) {
|
|
1892
|
+
let agent = null;
|
|
1893
|
+
try { agent = agents.get(String(sid)); } catch { agent = null; }
|
|
1894
|
+
if (agent) {
|
|
1895
|
+
boardSessions.set(String(sid), {
|
|
1896
|
+
taskId: task.id, phase: 'execution', handle: { agent }, sawRunning: false,
|
|
1897
|
+
});
|
|
1898
|
+
boardSessionIds.add(String(sid));
|
|
1899
|
+
}
|
|
1900
|
+
}
|
|
1901
|
+
continue;
|
|
1902
|
+
}
|
|
1903
|
+
if (task.status === 'planning' || task.status === 'inprogress') {
|
|
1904
|
+
const sid = task.status === 'planning' ? task.planningSessionId : task.leadSessionId;
|
|
1905
|
+
if (sid && !boardSessions.has(String(sid))) {
|
|
1906
|
+
let agent = null;
|
|
1907
|
+
try { agent = agents.get(String(sid)); } catch { agent = null; }
|
|
1908
|
+
if (agent) {
|
|
1909
|
+
boardSessions.set(String(sid), {
|
|
1910
|
+
taskId: task.id, phase: task.status === 'planning' ? 'planning' : 'execution',
|
|
1911
|
+
handle: { agent }, sawRunning: true,
|
|
1912
|
+
});
|
|
1913
|
+
boardSessionIds.add(String(sid));
|
|
1914
|
+
} else {
|
|
1915
|
+
await request(s, '/api/board/agents/status', {
|
|
1916
|
+
method: 'POST',
|
|
1917
|
+
body: { sessionId: sid, status: 'failed', summary: '会话已失效(插件重启或会话被关闭)' },
|
|
1918
|
+
}).catch(() => {});
|
|
1919
|
+
}
|
|
1920
|
+
}
|
|
1921
|
+
}
|
|
1922
|
+
if (task.status !== 'planning') continue;
|
|
1923
|
+
const at = Date.parse(task.updatedAt || task.claimedAt || '');
|
|
1924
|
+
if (!Number.isFinite(at) || Date.now() - at < s.boardPlanningTimeoutMs) continue;
|
|
1925
|
+
if (!task.planningSessionId) {
|
|
1926
|
+
await request(s, `/api/board/tasks/${encodeURIComponent(task.id)}/stop`, {
|
|
1927
|
+
method: 'POST', body: { reason: '规划超时(未 attach 会话)' },
|
|
1928
|
+
}).catch(() => {});
|
|
1929
|
+
continue;
|
|
1930
|
+
}
|
|
1931
|
+
await request(s, '/api/board/agents/status', {
|
|
1932
|
+
method: 'POST', body: { sessionId: task.planningSessionId, status: 'failed', summary: '规划超时' },
|
|
1933
|
+
}).catch(() => {});
|
|
1934
|
+
const rec = boardSessions.get(String(task.planningSessionId));
|
|
1935
|
+
if (rec) {
|
|
1936
|
+
try { void rec.handle?.dispose?.(); } catch { /* ignore */ }
|
|
1937
|
+
boardSessions.delete(String(task.planningSessionId));
|
|
1938
|
+
boardSessionIds.delete(String(task.planningSessionId));
|
|
1939
|
+
}
|
|
1940
|
+
}
|
|
1941
|
+
} catch { /* 查询失败不阻塞 claim */ }
|
|
1942
|
+
for (const kind of ['planning', 'inprogress']) {
|
|
1943
|
+
for (let i = 0; i < 4; i++) {
|
|
1944
|
+
let claimed;
|
|
1945
|
+
try {
|
|
1946
|
+
claimed = await request(s, '/api/board/claim', { method: 'POST', body: { kind } });
|
|
1947
|
+
} catch { return; }
|
|
1948
|
+
if (!claimed?.item) break;
|
|
1949
|
+
try { await spawnBoardSession(s, ctx, claimed.item); }
|
|
1950
|
+
catch (err) { console.warn(`[dsh-team] board spawn failed: ${String(err?.message || err)}`); }
|
|
1951
|
+
}
|
|
1952
|
+
}
|
|
1953
|
+
}
|
|
1954
|
+
|
|
1025
1955
|
/** 构造全部工具(普通 ToolDefinition,不依赖 defineTool;参数即 JSON Schema)。 */
|
|
1026
1956
|
function buildTools(s, ctx) {
|
|
1027
1957
|
const tools = [];
|
|
1028
1958
|
|
|
1029
1959
|
tools.push({
|
|
1030
1960
|
name: 'team_create',
|
|
1031
|
-
description: 'START HERE to build a working team of agents. Order: team_create({name, workspace,
|
|
1961
|
+
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
1962
|
parameters: {
|
|
1033
1963
|
type: 'object',
|
|
1034
1964
|
additionalProperties: false,
|
|
1035
1965
|
properties: {
|
|
1036
1966
|
name: { type: 'string', description: 'Team name.' },
|
|
1037
|
-
workspace: { type: 'string', description: 'Absolute directory shared by
|
|
1038
|
-
|
|
1967
|
+
workspace: { type: 'string', description: 'Absolute directory shared by members; created if missing.' },
|
|
1968
|
+
permissionPreset: { type: 'string', description: 'Default DSH permission preset for members (sandbox + approval policy). Default workspace-write. team_spawn can override it per member.' },
|
|
1969
|
+
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
1970
|
maxMembers: { type: 'integer', description: 'Member cap, 0 means unlimited. Default 64. Extra members are queued, never errors.' },
|
|
1040
1971
|
maxConcurrency: { type: 'integer', description: 'Max simultaneously running tasks. Default 8.' },
|
|
1041
1972
|
failurePolicy: { type: 'string', enum: ['continue', 'abort'], description: 'Team-level default failure policy.' },
|
|
1042
1973
|
maxAttempts: { type: 'integer', description: 'Per-task retry cap. Default 3.' },
|
|
1974
|
+
force: { type: 'boolean', description: '仅看板任务相关:该任务已关联团队时默认禁止重复建队(重试应继续用原团队);确认需要与之并行新建团队时传 true。' },
|
|
1043
1975
|
},
|
|
1044
1976
|
required: ['name', 'workspace'],
|
|
1045
1977
|
},
|
|
1046
1978
|
output: jsonOutput('{ team, panel }'),
|
|
1047
1979
|
async execute(args, exec) {
|
|
1980
|
+
await guardBoardTeamReuse(s, exec?.agent?.id, args.force);
|
|
1981
|
+
const permissionPreset = resolvePermissionPreset(ctx, args.permissionPreset, 'workspace-write');
|
|
1982
|
+
const agentPreset = await resolveAgentPreset(ctx, args.agentPreset, null, s);
|
|
1048
1983
|
const team = await request(s, '/api/teams', {
|
|
1049
1984
|
method: 'POST',
|
|
1050
1985
|
body: {
|
|
1051
1986
|
name: args.name,
|
|
1052
1987
|
workspace: args.workspace,
|
|
1053
|
-
|
|
1988
|
+
permissionPreset,
|
|
1989
|
+
...(agentPreset ? { agentPreset } : {}),
|
|
1054
1990
|
...(args.maxMembers !== undefined ? { maxMembers: args.maxMembers } : {}),
|
|
1055
1991
|
...(args.maxConcurrency !== undefined ? { maxConcurrency: args.maxConcurrency } : {}),
|
|
1056
1992
|
...(args.failurePolicy !== undefined ? { failurePolicy: args.failurePolicy } : {}),
|
|
@@ -1058,73 +1994,98 @@ function buildTools(s, ctx) {
|
|
|
1058
1994
|
...(exec?.agent && exec.agent.id != null ? { leadSessionId: String(exec.agent.id) } : {}),
|
|
1059
1995
|
},
|
|
1060
1996
|
});
|
|
1061
|
-
|
|
1997
|
+
teamCache.set(team.id, team);
|
|
1062
1998
|
if (exec?.agent) leadByTeam.set(team.id, exec.agent);
|
|
1999
|
+
// 会话级粘性绑定:即使后续 team_spawn 漏传 teamId,也能解析到本会话刚建的团队。
|
|
2000
|
+
if (exec?.agent?.id != null) teamBySession.set(String(exec.agent.id), String(team.id));
|
|
2001
|
+
await bindBoardTeam(s, exec, team.id);
|
|
1063
2002
|
return { team, panel: panelUrl(s) };
|
|
1064
2003
|
},
|
|
1065
2004
|
});
|
|
1066
2005
|
|
|
1067
2006
|
tools.push({
|
|
1068
2007
|
name: 'team_spawn',
|
|
1069
|
-
description: "Add one member to a team; returns the member `id` you use as team_task's `assignee`.
|
|
2008
|
+
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
2009
|
parameters: {
|
|
1071
2010
|
type: 'object',
|
|
1072
2011
|
additionalProperties: false,
|
|
1073
2012
|
properties: {
|
|
1074
|
-
teamId: { type: 'string', description: '
|
|
2013
|
+
teamId: { type: 'string', description: 'team_create 返回的 result.team.id(形如 team_xxx)。漏传时自动使用当前会话刚创建的团队。' },
|
|
1075
2014
|
name: { type: 'string', description: 'Unique member name inside the team; this is the addressable target.' },
|
|
1076
|
-
role: { type: 'string', description: 'Role label
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
2015
|
+
role: { type: 'string', description: 'Role label shown on the panel.' },
|
|
2016
|
+
permissionPreset: { type: 'string', description: "DSH permission preset for this member (sandbox + approval policy). Defaults to the team's permissionPreset." },
|
|
2017
|
+
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)." },
|
|
2018
|
+
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.' },
|
|
2019
|
+
model: { type: 'string', description: 'LLM model id, as returned by team_models. Changing the route clears inherited reasoning effort unless reasoningEffort is set explicitly.' },
|
|
2020
|
+
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.' },
|
|
2021
|
+
contextMode: { type: 'string', enum: ['isolated', 'fresh', 'fork'], description: 'Context isolation: `fresh` starts with no Lead history, `fork` inherits completed Lead turns. Default isolated/fresh.' },
|
|
2022
|
+
prompt: { type: 'string', description: 'The member’s first instruction. Tell it its role, workspace, and that it must call team_report_task when done.' },
|
|
2023
|
+
description: { type: 'string', description: 'One-line description of what this member is responsible for.' },
|
|
1083
2024
|
},
|
|
1084
|
-
required: ['teamId', 'name'],
|
|
2025
|
+
required: ['teamId', 'name', 'prompt'],
|
|
1085
2026
|
},
|
|
1086
|
-
output: jsonOutput('{ member, agent
|
|
2027
|
+
output: jsonOutput('{ member, agent, panel, permissionPreset, agentPreset, agentPresetWarning?, permissionPresetApplied?, permissionPresetWarning? }'),
|
|
1087
2028
|
async execute(args, exec) {
|
|
1088
|
-
const
|
|
1089
|
-
|
|
1090
|
-
|
|
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
|
-
}
|
|
2029
|
+
const team = await teamOf(s, args.teamId, { sessionId: exec?.agent?.id });
|
|
2030
|
+
const permissionPreset = resolvePermissionPreset(ctx, args.permissionPreset, team.permissionPreset);
|
|
2031
|
+
let requestedAgentPreset = await resolveAgentPreset(ctx, args.agentPreset, team.agentPreset, s);
|
|
1101
2032
|
|
|
1102
|
-
// ----
|
|
2033
|
+
// ---- 用 subagents 服务起一个 continuable 真子会话 ----
|
|
1103
2034
|
const subs = subagentsOf(ctx);
|
|
1104
2035
|
if (!subs || typeof subs.startActivation !== 'function') {
|
|
1105
|
-
throw new Error('subagents
|
|
2036
|
+
throw new Error('subagents 服务不可用:无法创建 sub-agent 成员(需要宿主启用 dsh-subagent)。');
|
|
1106
2037
|
}
|
|
1107
2038
|
const caller = exec?.agent;
|
|
1108
|
-
if (!caller) throw new Error('team_spawn
|
|
1109
|
-
if (!args.prompt) throw new Error('
|
|
2039
|
+
if (!caller) throw new Error('team_spawn 需要 Lead 会话上下文(exec.agent 缺失:不能在非 agent 调用里起成员)。');
|
|
2040
|
+
if (!args.prompt) throw new Error('team_spawn 需要 prompt(成员的初始指令)。');
|
|
1110
2041
|
|
|
1111
2042
|
const context = args.contextMode === 'fork' ? 'fork' : 'fresh';
|
|
2043
|
+
// 省略 preset 时 DSH 继承 Lead 的实时组合,不会套宿主默认;
|
|
2044
|
+
// fresh 成员必须显式拿宿主默认,否则 Lead 是看板裸会话时成员就没有 shell/文件工具。
|
|
2045
|
+
if (context !== 'fork' && !requestedAgentPreset) {
|
|
2046
|
+
requestedAgentPreset = await hostDefaultAgentPreset(ctx);
|
|
2047
|
+
}
|
|
2048
|
+
// fork provider 继承父方组装,DSH 会拒绝独立 agentPreset;这里显式降级为警告而不是静默传。
|
|
2049
|
+
const agentPreset = context === 'fork' ? null : requestedAgentPreset;
|
|
2050
|
+
const agentPresetWarning = context === 'fork' && requestedAgentPreset
|
|
2051
|
+
? `contextMode=fork 继承 Lead 的组装,agentPreset「${requestedAgentPreset}」未生效`
|
|
2052
|
+
: undefined;
|
|
1112
2053
|
const provider = providerFor(ctx, s, context);
|
|
1113
2054
|
// 实际 route:显式参数覆盖 Lead;effort 只在 route 未变时继承(与 DSH 子会话合并规则一致)
|
|
1114
2055
|
const leadRoute = leadRouteOf(caller);
|
|
1115
2056
|
const route = { provider: args.agentProvider || leadRoute.provider, model: args.model || leadRoute.model };
|
|
2057
|
+
// 看板任务如果指定了团队模型白名单,成员 route 必须落在名单内;不指定时取第一条。
|
|
2058
|
+
let pickedByBoard = false;
|
|
2059
|
+
const callerId = caller?.id != null ? String(caller.id) : null;
|
|
2060
|
+
const boardTask = callerId && boardSessionIds.has(callerId) ? await boardTaskOf(s, callerId) : null;
|
|
2061
|
+
const allowedModels = Array.isArray(boardTask?.teamModels)
|
|
2062
|
+
? boardTask.teamModels.map((m) => (typeof m === 'string'
|
|
2063
|
+
? { provider: null, model: m, reasoningEffort: null }
|
|
2064
|
+
: { provider: m?.provider || null, model: m?.model || null, reasoningEffort: m?.reasoningEffort || null })).filter((m) => m.model)
|
|
2065
|
+
: [];
|
|
2066
|
+
if (allowedModels.length) {
|
|
2067
|
+
if (!args.model) {
|
|
2068
|
+
const first = allowedModels[0];
|
|
2069
|
+
route.provider = first.provider || route.provider;
|
|
2070
|
+
route.model = first.model;
|
|
2071
|
+
pickedByBoard = true;
|
|
2072
|
+
}
|
|
2073
|
+
const hit = allowedModels.find((m) => m.model === route.model && (!m.provider || m.provider === route.provider));
|
|
2074
|
+
if (!hit) throw new Error(`模型 ${route.provider || '?'}/${route.model || '?'} 不在看板任务的白名单内:${allowedModels.map((m) => m.model).join(', ')}`);
|
|
2075
|
+
}
|
|
1116
2076
|
const routeChanged = route.provider !== leadRoute.provider || route.model !== leadRoute.model;
|
|
1117
2077
|
route.reasoningEffort = args.reasoningEffort || (routeChanged ? null : leadRoute.reasoningEffort);
|
|
1118
2078
|
// 继承 Lead 的 route 也要过启用闸门:停用项不该被成员继续使用;effort 同理。
|
|
1119
2079
|
await assertRouteEnabled(s, ctx, route.provider, route.model, route.reasoningEffort);
|
|
1120
2080
|
const agentOptions = {};
|
|
1121
|
-
if (args.agentProvider
|
|
1122
|
-
|
|
1123
|
-
|
|
2081
|
+
if (args.agentProvider || args.model || pickedByBoard) {
|
|
2082
|
+
if (route.provider) agentOptions.provider = String(route.provider);
|
|
2083
|
+
if (route.model) agentOptions.model = String(route.model);
|
|
2084
|
+
if (route.reasoningEffort && (args.reasoningEffort || pickedByBoard)) agentOptions.reasoningEffort = String(route.reasoningEffort);
|
|
2085
|
+
}
|
|
1124
2086
|
const memberName = String(args.name).trim();
|
|
1125
2087
|
const description = String(args.description || args.role || memberName).slice(0, 200);
|
|
1126
2088
|
const sessionId = randomUUID();
|
|
1127
|
-
const team = await request(s, `/api/teams/${encodeURIComponent(args.teamId)}`).catch(() => null);
|
|
1128
2089
|
const started = await subs.startActivation({
|
|
1129
2090
|
delivery: 'parent',
|
|
1130
2091
|
childId: sessionId,
|
|
@@ -1135,41 +2096,54 @@ function buildTools(s, ctx) {
|
|
|
1135
2096
|
parent: caller,
|
|
1136
2097
|
...(team && team.workspace ? { cwd: team.workspace } : {}),
|
|
1137
2098
|
...(Object.keys(agentOptions).length ? { agentOptions } : {}),
|
|
2099
|
+
...(agentPreset ? { agentPreset } : {}),
|
|
1138
2100
|
},
|
|
1139
2101
|
signal: exec.signal || AbortSignal.timeout(s.requestTimeoutMs),
|
|
1140
2102
|
});
|
|
1141
2103
|
// 成员跑的是一整轮 agent loop,结果由 team_report_task 汇报;这里只防止未处理的 rejection。
|
|
1142
2104
|
if (started && started.result && typeof started.result.catch === 'function') started.result.catch(() => {});
|
|
1143
|
-
|
|
2105
|
+
// 子会话发布后立刻把 preset 落到会话(会覆盖 subagent 继承来的 approval=never)。
|
|
2106
|
+
const presetResult = applyPermissionPreset(ctx, sessionId, permissionPreset);
|
|
1144
2107
|
|
|
1145
2108
|
const registered = await request(s, '/api/agents/register', {
|
|
1146
2109
|
method: 'POST',
|
|
1147
2110
|
body: {
|
|
1148
|
-
|
|
2111
|
+
// 用解析后的 team.id,而不是原始 args.teamId:teamId 可省略并回退到会话绑定的团队,
|
|
2112
|
+
// 原始值此时是 undefined,直接透传会让 sidecar 报 `teamId required`。
|
|
2113
|
+
teamId: team.id,
|
|
1149
2114
|
name: memberName,
|
|
1150
2115
|
sessionId,
|
|
2116
|
+
parentSessionId: caller.id != null ? String(caller.id) : null,
|
|
1151
2117
|
role: args.role || 'teammate',
|
|
1152
|
-
model: args.model ||
|
|
2118
|
+
model: args.model || route.model || null,
|
|
1153
2119
|
contextMode: context,
|
|
2120
|
+
agentProvider: route.provider || null,
|
|
2121
|
+
permissionPreset,
|
|
2122
|
+
...(agentPreset ? { agentPreset } : {}),
|
|
1154
2123
|
// 实际生效的思考强度(含从 Lead 继承的值):面板成员卡片据此展示,之后不可变
|
|
1155
2124
|
reasoningEffort: route.reasoningEffort || null,
|
|
1156
2125
|
},
|
|
1157
2126
|
});
|
|
1158
|
-
rememberMember(sessionId,
|
|
1159
|
-
leadByTeam.set(
|
|
2127
|
+
rememberMember(sessionId, team.id, registered.member.id, team.workspace, registered.member.permissionPreset || permissionPreset, memberName);
|
|
2128
|
+
leadByTeam.set(team.id, caller);
|
|
1160
2129
|
return {
|
|
1161
2130
|
member: registered.member,
|
|
1162
2131
|
agent: {
|
|
1163
2132
|
sessionId,
|
|
1164
|
-
name:
|
|
1165
|
-
status:
|
|
1166
|
-
role:
|
|
2133
|
+
name: memberName,
|
|
2134
|
+
status: 'running',
|
|
2135
|
+
role: args.role || 'teammate',
|
|
1167
2136
|
provider,
|
|
1168
2137
|
context,
|
|
1169
2138
|
model: route.model || null,
|
|
1170
2139
|
route,
|
|
1171
|
-
diagnostics: spawned.member.diagnostics || [],
|
|
1172
2140
|
},
|
|
2141
|
+
permissionPreset: registered.member?.permissionPreset || permissionPreset,
|
|
2142
|
+
agentPreset: registered.member?.agentPreset || agentPreset || null,
|
|
2143
|
+
...(agentPresetWarning ? { agentPresetWarning } : {}),
|
|
2144
|
+
permissionPresetApplied: presetResult.applied,
|
|
2145
|
+
...(presetResult.reason ? { permissionPresetWarning: presetResult.reason } : {}),
|
|
2146
|
+
...(presetResult.error ? { permissionPresetWarning: presetResult.error } : {}),
|
|
1173
2147
|
panel: panelUrl(s),
|
|
1174
2148
|
};
|
|
1175
2149
|
},
|
|
@@ -1215,9 +2189,63 @@ function buildTools(s, ctx) {
|
|
|
1215
2189
|
},
|
|
1216
2190
|
});
|
|
1217
2191
|
|
|
2192
|
+
tools.push({
|
|
2193
|
+
name: 'team_preset',
|
|
2194
|
+
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.',
|
|
2195
|
+
parameters: {
|
|
2196
|
+
type: 'object',
|
|
2197
|
+
additionalProperties: false,
|
|
2198
|
+
required: ['action'],
|
|
2199
|
+
properties: {
|
|
2200
|
+
action: { type: 'string', enum: ['list', 'save', 'show', 'delete'], description: 'list:列出可用预设;save:写入固定目录并立刻注册;show:读回已保存的文档;delete:删除团队自建预设并反注册。' },
|
|
2201
|
+
id: { type: 'string', description: '预设 id(save/show 必填),`^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$`。' },
|
|
2202
|
+
name: { type: 'string', description: '展示名(save 可选)。' },
|
|
2203
|
+
description: { type: 'string', description: '用途说明(save 可选)。' },
|
|
2204
|
+
order: { type: 'number', description: '排序权重(save 可选,越小越靠前)。' },
|
|
2205
|
+
confirm: { type: 'boolean', description: 'save 覆盖同名团队自建预设时必须显式 true;内置预设任何时候都不能覆盖。' },
|
|
2206
|
+
plugins: {
|
|
2207
|
+
type: 'array',
|
|
2208
|
+
description: 'save 必填:Cordis 插件条目列表,每项 { name, config?, id?, disabled? }。',
|
|
2209
|
+
items: {
|
|
2210
|
+
type: 'object',
|
|
2211
|
+
additionalProperties: true,
|
|
2212
|
+
required: ['name'],
|
|
2213
|
+
properties: { name: { type: 'string', description: '插件包名,如 @deepseek-ai/dsh-tool-fs。' } },
|
|
2214
|
+
},
|
|
2215
|
+
},
|
|
2216
|
+
},
|
|
2217
|
+
},
|
|
2218
|
+
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 }'),
|
|
2219
|
+
isConcurrencySafe: () => true,
|
|
2220
|
+
async execute(args = {}) {
|
|
2221
|
+
const action = String(args.action || '');
|
|
2222
|
+
if (action === 'list') return listTeamPresets(s, ctx);
|
|
2223
|
+
if (action === 'show') {
|
|
2224
|
+
const id = String(args.id || '').trim();
|
|
2225
|
+
if (!PRESET_ID_RE.test(id)) throw new Error(`agentPreset 名称非法:「${id}」`);
|
|
2226
|
+
const file = path.join(s.presetDir, `${id}.json`);
|
|
2227
|
+
if (!fs.existsSync(file)) {
|
|
2228
|
+
const svc = ctx.get('agentPresets');
|
|
2229
|
+
let row = null;
|
|
2230
|
+
try { row = (await svc?.list?.() || []).find((r) => r && r.id === id) || null; } catch { row = null; }
|
|
2231
|
+
if (!row) throw new Error(`没有找到 preset「${id}」:既不在 ${s.presetDir},也不是宿主内置预设`);
|
|
2232
|
+
return { id, source: 'host', preset: row, hint: '宿主内置预设的文档在 DSH bundle 里,不能编辑;需要定制就新建一个 id。' };
|
|
2233
|
+
}
|
|
2234
|
+
return { id, source: 'team', file, doc: JSON.parse(fs.readFileSync(file, 'utf8')) };
|
|
2235
|
+
}
|
|
2236
|
+
if (action === 'save') {
|
|
2237
|
+
const saved = await saveTeamPreset(s, ctx, args);
|
|
2238
|
+
await syncPresetCatalog(s, ctx);
|
|
2239
|
+
return saved;
|
|
2240
|
+
}
|
|
2241
|
+
if (action === 'delete') return deleteTeamPreset(s, ctx, args.id);
|
|
2242
|
+
throw new Error(`未知 action「${action}」:只支持 list / save / show / delete`);
|
|
2243
|
+
},
|
|
2244
|
+
});
|
|
2245
|
+
|
|
1218
2246
|
tools.push({
|
|
1219
2247
|
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/
|
|
2248
|
+
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
2249
|
parameters: {
|
|
1222
2250
|
type: 'object',
|
|
1223
2251
|
additionalProperties: false,
|
|
@@ -1239,10 +2267,11 @@ function buildTools(s, ctx) {
|
|
|
1239
2267
|
asOf: st.asOf,
|
|
1240
2268
|
version: st.version,
|
|
1241
2269
|
panel: panelUrl(s),
|
|
1242
|
-
runtime: st.runtime || runtimeByTeam.get(args.teamId) || 'worker',
|
|
1243
2270
|
members: (st.members || []).map((m) => ({
|
|
1244
2271
|
name: m.name,
|
|
1245
2272
|
model: m.model || null,
|
|
2273
|
+
permissionPreset: m.permissionPreset || null,
|
|
2274
|
+
agentPreset: m.agentPreset || null,
|
|
1246
2275
|
reasoningEffort: m.reasoningEffort || null,
|
|
1247
2276
|
status: m.status,
|
|
1248
2277
|
step: m.step,
|
|
@@ -1251,7 +2280,6 @@ function buildTools(s, ctx) {
|
|
|
1251
2280
|
next: m.next,
|
|
1252
2281
|
last: m.last,
|
|
1253
2282
|
currentTaskId: m.currentTaskId,
|
|
1254
|
-
leaseUntil: m.leaseUntil,
|
|
1255
2283
|
blockers: m.blockers,
|
|
1256
2284
|
stale: m.stale,
|
|
1257
2285
|
agentSessionId: m.agentSessionId || null,
|
|
@@ -1265,7 +2293,7 @@ function buildTools(s, ctx) {
|
|
|
1265
2293
|
|
|
1266
2294
|
tools.push({
|
|
1267
2295
|
name: 'team_task',
|
|
1268
|
-
description: 'Declare one task (DAG node) and hand it to a member.
|
|
2296
|
+
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
2297
|
parameters: {
|
|
1270
2298
|
type: 'object',
|
|
1271
2299
|
additionalProperties: false,
|
|
@@ -1273,7 +2301,7 @@ function buildTools(s, ctx) {
|
|
|
1273
2301
|
teamId: { type: 'string' },
|
|
1274
2302
|
subject: { type: 'string', description: 'Concise task title.' },
|
|
1275
2303
|
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
|
|
2304
|
+
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
2305
|
deps: {
|
|
1278
2306
|
type: 'array',
|
|
1279
2307
|
description: 'Upstream dependencies declared atomically with the task: [{from, condition?, artifactPath?}].',
|
|
@@ -1288,12 +2316,11 @@ function buildTools(s, ctx) {
|
|
|
1288
2316
|
required: ['from'],
|
|
1289
2317
|
},
|
|
1290
2318
|
},
|
|
1291
|
-
writeScopes: { type: 'array', items: { type: 'string' }, description: 'Advisory write scope prefixes (sidecar policies are the enforced ones).' },
|
|
1292
2319
|
acceptance: { type: 'string' },
|
|
1293
2320
|
priority: { type: 'integer', description: 'Smaller runs first. Default 0.' },
|
|
1294
2321
|
failurePolicy: { type: 'string', enum: ['continue', 'skip', 'abort_team', 'retry'] },
|
|
1295
2322
|
maxAttempts: { type: 'integer' },
|
|
1296
|
-
dispatch: { type: 'boolean', description: '
|
|
2323
|
+
dispatch: { type: 'boolean', description: 'Dispatch immediately after creating (default true). Pass false to build the DAG first and dispatch later with team_dispatch.' },
|
|
1297
2324
|
},
|
|
1298
2325
|
required: ['teamId', 'subject', 'plan'],
|
|
1299
2326
|
},
|
|
@@ -1308,14 +2335,13 @@ function buildTools(s, ctx) {
|
|
|
1308
2335
|
...(args.assignee !== undefined ? { assignee: args.assignee } : {}),
|
|
1309
2336
|
plan: args.plan || [],
|
|
1310
2337
|
...(args.deps !== undefined ? { deps: args.deps } : {}),
|
|
1311
|
-
...(args.writeScopes !== undefined ? { writeScopes: args.writeScopes } : {}),
|
|
1312
2338
|
...(args.acceptance !== undefined ? { acceptance: args.acceptance } : {}),
|
|
1313
2339
|
...(args.priority !== undefined ? { priority: args.priority } : {}),
|
|
1314
2340
|
...(args.failurePolicy !== undefined ? { failurePolicy: args.failurePolicy } : {}),
|
|
1315
2341
|
...(args.maxAttempts !== undefined ? { maxAttempts: args.maxAttempts } : {}),
|
|
1316
2342
|
},
|
|
1317
2343
|
});
|
|
1318
|
-
if (args.dispatch === false
|
|
2344
|
+
if (args.dispatch === false) return { task };
|
|
1319
2345
|
await sleep(s.agentSettleMs);
|
|
1320
2346
|
const dispatched = await dispatchLoop(s, ctx, args.teamId);
|
|
1321
2347
|
return { task, dispatched };
|
|
@@ -1324,7 +2350,7 @@ function buildTools(s, ctx) {
|
|
|
1324
2350
|
|
|
1325
2351
|
tools.push({
|
|
1326
2352
|
name: 'team_send',
|
|
1327
|
-
description: "Send a message that a member will actually read
|
|
2353
|
+
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
2354
|
parameters: {
|
|
1329
2355
|
type: 'object',
|
|
1330
2356
|
additionalProperties: false,
|
|
@@ -1345,9 +2371,8 @@ function buildTools(s, ctx) {
|
|
|
1345
2371
|
if (exec?.agent && !callerMember) leadByTeam.set(args.teamId, exec.agent);
|
|
1346
2372
|
const from = callerMember ? callerMember.memberId : 'lead';
|
|
1347
2373
|
const toLead = String(args.to).trim().toLowerCase() === 'lead';
|
|
1348
|
-
const runtime = await runtimeOfTeam(s, args.teamId);
|
|
1349
2374
|
// sidecar 的收件人只能是成员 id、'*' 或虚拟收件人 'lead',所以先把 name / id 统一解析成成员行。
|
|
1350
|
-
const st =
|
|
2375
|
+
const st = await request(s, `/api/status${qs({ team: args.teamId })}`);
|
|
1351
2376
|
const members = st?.members || [];
|
|
1352
2377
|
const resolve = (v) => members.find((m) => m.name === v || m.id === v) || null;
|
|
1353
2378
|
if (!toLead && args.to !== '*' && (members.length ? !resolve(args.to) : false)) {
|
|
@@ -1363,8 +2388,8 @@ function buildTools(s, ctx) {
|
|
|
1363
2388
|
...(args.correlationId !== undefined ? { correlationId: args.correlationId } : {}),
|
|
1364
2389
|
},
|
|
1365
2390
|
});
|
|
1366
|
-
// 成员→Lead 只落信箱(面板可见),不打扰 Lead
|
|
1367
|
-
if (
|
|
2391
|
+
// 成员→Lead 只落信箱(面板可见),不打扰 Lead 会话。
|
|
2392
|
+
if (toLead) return recorded;
|
|
1368
2393
|
|
|
1369
2394
|
const subs = subagentsOf(ctx);
|
|
1370
2395
|
// 成员之间互通必须借 Lead 的 agent 句柄:成员会话都挂在 Lead 下,成员直发会「belongs to another parent session」。
|
|
@@ -1467,6 +2492,159 @@ function buildTools(s, ctx) {
|
|
|
1467
2492
|
},
|
|
1468
2493
|
});
|
|
1469
2494
|
|
|
2495
|
+
// ---------- 显式记忆(文件持久化;成员收工时保存 handoff,Lead 可要求上传团队空间) ----------
|
|
2496
|
+
const memorySession = (exec) => (exec?.agent?.sessionId ?? exec?.agent?.id ?? null) == null
|
|
2497
|
+
? null : String(exec.agent.sessionId ?? exec.agent.id);
|
|
2498
|
+
const memoryQuery = (params, sessionId) => {
|
|
2499
|
+
const q = new URLSearchParams();
|
|
2500
|
+
for (const [k, v] of Object.entries(params)) if (v != null && v !== '') q.set(k, String(v));
|
|
2501
|
+
if (sessionId) q.set('session', sessionId);
|
|
2502
|
+
const s = q.toString();
|
|
2503
|
+
return s ? `?${s}` : '';
|
|
2504
|
+
};
|
|
2505
|
+
|
|
2506
|
+
tools.push({
|
|
2507
|
+
name: 'team_memory_write',
|
|
2508
|
+
description: 'Save ONE memory into the file-backed memory space (one JSON file per memory, never SQLite). scope=member writes the caller member\'s own space; scope=team writes the shared team space (use it when the Lead asks you to upload). Same (scope, team, owner, key) upserts and bumps version; pass expectedVersion for compare-and-set. Keep handoffs short (<=300 chars) and only save what is actually reusable — do NOT force a memory when the task produced nothing worth carrying.',
|
|
2509
|
+
parameters: {
|
|
2510
|
+
type: 'object',
|
|
2511
|
+
additionalProperties: false,
|
|
2512
|
+
properties: {
|
|
2513
|
+
teamId: { type: 'string' },
|
|
2514
|
+
scope: { type: 'string', enum: ['member', 'team'], description: 'member = caller\'s own space (default); team = shared space.' },
|
|
2515
|
+
key: { type: 'string', description: 'Stable slot key inside the space, e.g. "handoff/api-contract" or "decision/db". Max 128 chars.' },
|
|
2516
|
+
value: { description: 'Memory body: string, or JSON value (objects are stored as a JSON string). Max 64KB.' },
|
|
2517
|
+
kind: { type: 'string', enum: ['handoff', 'fact', 'decision', 'open-question'], description: 'Default fact; use handoff when finishing a task.' },
|
|
2518
|
+
title: { type: 'string', description: 'Optional short title; defaults to the first line of value.' },
|
|
2519
|
+
tags: { type: 'array', items: { type: 'string' }, description: 'Optional tags (max 20).' },
|
|
2520
|
+
visibility: { type: 'string', enum: ['private', 'team', 'shared'], description: 'private = owner + team Lead; team = this team\'s members; shared = any team by id. Default: private for member scope, team for team scope.' },
|
|
2521
|
+
taskId: { type: 'string', description: 'Optional task provenance id.' },
|
|
2522
|
+
expectedVersion: { type: 'integer', description: 'Optimistic concurrency: 0 = must be new; N = must currently be version N.' },
|
|
2523
|
+
},
|
|
2524
|
+
required: ['teamId', 'key', 'value'],
|
|
2525
|
+
},
|
|
2526
|
+
output: jsonOutput('{ memory, created }'),
|
|
2527
|
+
async execute(args, exec) {
|
|
2528
|
+
await teamOf(s, args.teamId, { sessionId: memorySession(exec) });
|
|
2529
|
+
return await request(s, '/api/memory', {
|
|
2530
|
+
method: 'POST',
|
|
2531
|
+
body: {
|
|
2532
|
+
teamId: args.teamId,
|
|
2533
|
+
scope: args.scope ?? 'member',
|
|
2534
|
+
key: args.key,
|
|
2535
|
+
value: args.value,
|
|
2536
|
+
kind: args.kind,
|
|
2537
|
+
title: args.title,
|
|
2538
|
+
tags: args.tags,
|
|
2539
|
+
visibility: args.visibility,
|
|
2540
|
+
expectedVersion: args.expectedVersion,
|
|
2541
|
+
source: args.taskId ? { taskId: args.taskId } : undefined,
|
|
2542
|
+
sessionId: memorySession(exec),
|
|
2543
|
+
},
|
|
2544
|
+
});
|
|
2545
|
+
},
|
|
2546
|
+
});
|
|
2547
|
+
|
|
2548
|
+
tools.push({
|
|
2549
|
+
name: 'team_memory_read',
|
|
2550
|
+
description: 'Read ONE memory by id, or find the first matching memory by scope+key (and optional memberId). Memory ids are portable: a shared memory id can be passed to a member of another team. Returns the full value and version.',
|
|
2551
|
+
parameters: {
|
|
2552
|
+
type: 'object',
|
|
2553
|
+
additionalProperties: false,
|
|
2554
|
+
properties: {
|
|
2555
|
+
teamId: { type: 'string' },
|
|
2556
|
+
memoryId: { type: 'string', description: 'mem_xxx id; takes precedence over scope/key.' },
|
|
2557
|
+
scope: { type: 'string', enum: ['member', 'team'] },
|
|
2558
|
+
key: { type: 'string', description: 'Slot key to look up when memoryId is absent.' },
|
|
2559
|
+
memberId: { type: 'string', description: 'Owner member for member scope; defaults to the caller member.' },
|
|
2560
|
+
},
|
|
2561
|
+
required: ['teamId'],
|
|
2562
|
+
},
|
|
2563
|
+
output: jsonOutput('{ memory?, items? }'),
|
|
2564
|
+
async execute(args, exec) {
|
|
2565
|
+
const sessionId = memorySession(exec);
|
|
2566
|
+
const binding = sessionId ? sessionMember.get(sessionId) : null;
|
|
2567
|
+
if (args.memoryId) {
|
|
2568
|
+
return await request(s, `/api/memory/${encodeURIComponent(args.memoryId)}${memoryQuery({ team: args.teamId }, sessionId)}`);
|
|
2569
|
+
}
|
|
2570
|
+
if (!args.key) throw new Error('需要 memoryId 或 key');
|
|
2571
|
+
const memberId = args.scope === 'member' ? (args.memberId || binding?.memberId) : args.memberId;
|
|
2572
|
+
const res = await request(s, `/api/memory${memoryQuery({ team: args.teamId, scope: args.scope ?? (memberId ? 'member' : undefined), member: memberId, slot: args.key, limit: 20 }, sessionId)}`);
|
|
2573
|
+
const hit = (res.items || [])[0];
|
|
2574
|
+
if (!hit) return { items: [] };
|
|
2575
|
+
return await request(s, `/api/memory/${encodeURIComponent(hit.id)}${memoryQuery({ team: args.teamId }, sessionId)}`);
|
|
2576
|
+
},
|
|
2577
|
+
});
|
|
2578
|
+
|
|
2579
|
+
tools.push({
|
|
2580
|
+
name: 'team_memory_list',
|
|
2581
|
+
description: 'List memory metadata (slot/title/kind/source/updatedAt, no value body) for a team. Members see their own private memories + team-scope memories; the Lead sees all memories of the team; shared memories are visible across teams. Use q to search slot/title/tags/value text.',
|
|
2582
|
+
parameters: {
|
|
2583
|
+
type: 'object',
|
|
2584
|
+
additionalProperties: false,
|
|
2585
|
+
properties: {
|
|
2586
|
+
teamId: { type: 'string' },
|
|
2587
|
+
scope: { type: 'string', enum: ['member', 'team'] },
|
|
2588
|
+
memberId: { type: 'string' },
|
|
2589
|
+
kind: { type: 'string', enum: ['handoff', 'fact', 'decision', 'open-question'] },
|
|
2590
|
+
tag: { type: 'string' },
|
|
2591
|
+
q: { type: 'string' },
|
|
2592
|
+
limit: { type: 'integer', description: 'Default 200, max 1000.' },
|
|
2593
|
+
},
|
|
2594
|
+
required: ['teamId'],
|
|
2595
|
+
},
|
|
2596
|
+
output: jsonOutput('{ asOf, total, items: [{ id, scope, slot, kind, title, summary, tags, visibility, source, updatedAt, version }] }'),
|
|
2597
|
+
async execute(args, exec) {
|
|
2598
|
+
const sessionId = memorySession(exec);
|
|
2599
|
+
const binding = sessionId ? sessionMember.get(sessionId) : null;
|
|
2600
|
+
const memberId = args.memberId || (args.scope === 'member' ? binding?.memberId : undefined);
|
|
2601
|
+
return await request(s, `/api/memory${memoryQuery({
|
|
2602
|
+
team: args.teamId, scope: args.scope, member: memberId, kind: args.kind, tag: args.tag, q: args.q, limit: args.limit,
|
|
2603
|
+
}, sessionId)}`);
|
|
2604
|
+
},
|
|
2605
|
+
});
|
|
2606
|
+
|
|
2607
|
+
tools.push({
|
|
2608
|
+
name: 'team_memory_share',
|
|
2609
|
+
description: 'Change a memory\'s visibility: private (owner + team Lead), team (this team\'s members), shared (any team by id). The Lead uses this to hand a member\'s memory to other members; a member can share its own memory.',
|
|
2610
|
+
parameters: {
|
|
2611
|
+
type: 'object',
|
|
2612
|
+
additionalProperties: false,
|
|
2613
|
+
properties: {
|
|
2614
|
+
teamId: { type: 'string' },
|
|
2615
|
+
memoryId: { type: 'string' },
|
|
2616
|
+
visibility: { type: 'string', enum: ['private', 'team', 'shared'] },
|
|
2617
|
+
},
|
|
2618
|
+
required: ['teamId', 'memoryId', 'visibility'],
|
|
2619
|
+
},
|
|
2620
|
+
output: jsonOutput('{ memory }'),
|
|
2621
|
+
async execute(args, exec) {
|
|
2622
|
+
await teamOf(s, args.teamId, { sessionId: memorySession(exec) });
|
|
2623
|
+
return await request(s, `/api/memory/${encodeURIComponent(args.memoryId)}/share${memoryQuery({ team: args.teamId }, memorySession(exec))}`, {
|
|
2624
|
+
method: 'POST',
|
|
2625
|
+
body: { visibility: args.visibility, sessionId: memorySession(exec) },
|
|
2626
|
+
});
|
|
2627
|
+
},
|
|
2628
|
+
});
|
|
2629
|
+
|
|
2630
|
+
tools.push({
|
|
2631
|
+
name: 'team_memory_delete',
|
|
2632
|
+
description: 'Delete ONE memory file permanently. The owner member or the team Lead may delete; team deletion does NOT cascade to memory files. Shared memory ids keep working across teams until deleted.',
|
|
2633
|
+
parameters: {
|
|
2634
|
+
type: 'object',
|
|
2635
|
+
additionalProperties: false,
|
|
2636
|
+
properties: {
|
|
2637
|
+
teamId: { type: 'string' },
|
|
2638
|
+
memoryId: { type: 'string' },
|
|
2639
|
+
},
|
|
2640
|
+
required: ['teamId', 'memoryId'],
|
|
2641
|
+
},
|
|
2642
|
+
output: jsonOutput('{ id, removed }'),
|
|
2643
|
+
async execute(args, exec) {
|
|
2644
|
+
return await request(s, `/api/memory/${encodeURIComponent(args.memoryId)}${memoryQuery({ team: args.teamId }, memorySession(exec))}`, { method: 'DELETE' });
|
|
2645
|
+
},
|
|
2646
|
+
});
|
|
2647
|
+
|
|
1470
2648
|
tools.push({
|
|
1471
2649
|
name: 'team_dispatch',
|
|
1472
2650
|
description: 'Pump the agent-team dispatcher once: claim ready tasks for idle members and send each member its brief. Normally unnecessary — team_task dispatches automatically and team_report_task dispatches the next wave — but useful after team_control/resume, after approving a scope request, or when a member went idle without reporting. Safe to call repeatedly; it returns when no idle member or no ready task is left.',
|
|
@@ -1484,110 +2662,102 @@ function buildTools(s, ctx) {
|
|
|
1484
2662
|
});
|
|
1485
2663
|
|
|
1486
2664
|
tools.push({
|
|
1487
|
-
name: '
|
|
1488
|
-
description: '
|
|
2665
|
+
name: 'team_approve',
|
|
2666
|
+
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
2667
|
parameters: {
|
|
1490
2668
|
type: 'object',
|
|
1491
2669
|
additionalProperties: false,
|
|
1492
2670
|
properties: {
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
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.' },
|
|
2671
|
+
teamId: { type: 'string', description: 'Team id from the forwarded approval message.' },
|
|
2672
|
+
requestId: { type: 'string', description: 'Approval request id from the forwarded message.' },
|
|
2673
|
+
decision: { type: 'string', enum: ['allow', 'deny'], description: 'allow = authorize this single operation; deny = reject it.' },
|
|
2674
|
+
reason: { type: 'string', description: 'Optional reason shown in the audit trail and to the member.' },
|
|
1509
2675
|
},
|
|
1510
|
-
required: ['
|
|
2676
|
+
required: ['teamId', 'requestId', 'decision'],
|
|
1511
2677
|
},
|
|
1512
|
-
output: jsonOutput('{
|
|
1513
|
-
async execute(args) {
|
|
1514
|
-
const
|
|
1515
|
-
if (
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
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
|
-
});
|
|
2678
|
+
output: jsonOutput('{ requestId, decision, memberId, toolName, reason }'),
|
|
2679
|
+
async execute(args, exec) {
|
|
2680
|
+
const requestId = String(args.requestId || '').trim();
|
|
2681
|
+
if (!requestId) throw new Error('team_approve requires requestId');
|
|
2682
|
+
const entry = pendingApprovals.get(requestId);
|
|
2683
|
+
if (!entry) throw new Error('审批请求不存在或已处理(可能已超时)。请以成员收到的审批消息里的 requestId 为准。');
|
|
2684
|
+
if (String(entry.teamId) !== String(args.teamId)) throw new Error('teamId 与审批请求不匹配');
|
|
2685
|
+
const callerId = exec?.agent?.id != null ? String(exec.agent.id) : null;
|
|
2686
|
+
const team = await teamOf(s, entry.teamId).catch(() => null);
|
|
2687
|
+
const leadId = team?.leadSessionId ? String(team.leadSessionId) : (leadByTeam.get(entry.teamId)?.id != null ? String(leadByTeam.get(entry.teamId).id) : null);
|
|
2688
|
+
if (leadId && callerId && leadId !== callerId) {
|
|
2689
|
+
throw new Error('只有该团队的 Lead 可以审批这个请求');
|
|
1551
2690
|
}
|
|
1552
|
-
|
|
2691
|
+
settleApproval(s, requestId, args.decision, args.reason || '', callerId || 'lead');
|
|
2692
|
+
return { requestId, decision: args.decision, memberId: entry.memberId, toolName: entry.toolName, reason: args.reason || null };
|
|
1553
2693
|
},
|
|
1554
2694
|
});
|
|
1555
2695
|
|
|
1556
2696
|
tools.push({
|
|
1557
2697
|
name: 'team_control',
|
|
1558
|
-
description: 'Control one member.
|
|
2698
|
+
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
2699
|
parameters: {
|
|
1560
2700
|
type: 'object',
|
|
1561
2701
|
additionalProperties: false,
|
|
1562
2702
|
properties: {
|
|
1563
|
-
action: { type: 'string', enum: ['interrupt', 'resume', 'assign'] },
|
|
2703
|
+
action: { type: 'string', enum: ['interrupt', 'resume', 'assign', 'abort'] },
|
|
1564
2704
|
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.' },
|
|
2705
|
+
memberId: { type: 'string', description: 'Required for interrupt/resume/assign.' },
|
|
2706
|
+
taskId: { type: 'string', description: 'Required for assign and abort.' },
|
|
2707
|
+
reason: { type: 'string', description: 'For interrupt/abort.' },
|
|
1568
2708
|
},
|
|
1569
|
-
required: ['action'
|
|
2709
|
+
required: ['action'],
|
|
1570
2710
|
},
|
|
1571
2711
|
output: jsonOutput('{ member, ... }'),
|
|
1572
2712
|
async execute(args, exec) {
|
|
2713
|
+
if (args.action === 'abort') {
|
|
2714
|
+
if (!args.taskId) throw new Error('team_control abort requires taskId');
|
|
2715
|
+
const res = await request(s, `/api/tasks/${encodeURIComponent(args.taskId)}/abort`, { method: 'POST', body: { reason: args.reason || 'lead abort' } });
|
|
2716
|
+
if (!res?.wasRunning || !res?.member?.agentSessionId) return res;
|
|
2717
|
+
const sid = String(res.member.agentSessionId);
|
|
2718
|
+
const subs = subagentsOf(ctx);
|
|
2719
|
+
const caller = exec?.agent;
|
|
2720
|
+
if (!subs || !caller || typeof subs.interrupt !== 'function') return res;
|
|
2721
|
+
cancelIdleReport(sid);
|
|
2722
|
+
cancelStartWatchdog(sid);
|
|
2723
|
+
agentStatusBySession.set(sid, 'interrupted');
|
|
2724
|
+
const interrupted = await Promise.resolve()
|
|
2725
|
+
.then(() => subs.interrupt(sid, { kind: 'ancestor', agent: caller }))
|
|
2726
|
+
.then(() => ({ ok: true, previousStatus: res.member.agentStatus ?? null }),
|
|
2727
|
+
(err) => ({ ok: false, error: String(err?.message || err) }));
|
|
2728
|
+
return { ...res, agent: interrupted };
|
|
2729
|
+
}
|
|
2730
|
+
if (!args.memberId) throw new Error(`team_control ${args.action} requires memberId`);
|
|
1573
2731
|
const id = encodeURIComponent(args.memberId);
|
|
1574
2732
|
if (args.action === 'interrupt') {
|
|
1575
2733
|
const res = await request(s, `/api/members/${id}/interrupt`, { method: 'POST', body: { reason: args.reason || 'lead interrupt' } });
|
|
1576
|
-
|
|
1577
|
-
|
|
2734
|
+
if (res?.member?.agentSessionId) {
|
|
2735
|
+
const sid = String(res.member.agentSessionId);
|
|
1578
2736
|
const subs = subagentsOf(ctx);
|
|
1579
2737
|
const caller = exec?.agent;
|
|
1580
2738
|
if (subs && caller && typeof subs.interrupt === 'function') {
|
|
2739
|
+
// 冻结会话:直到 Lead resume 前,忽略该会话的 idle / turn-error 回报,
|
|
2740
|
+
// 否则 DSH 中断后的 idle 会把 sidecar 的 interrupted 覆盖成 idle,派发泵又能唤醒它。
|
|
2741
|
+
heldSessions.add(sid);
|
|
2742
|
+
cancelIdleReport(sid);
|
|
2743
|
+
cancelStartWatchdog(sid);
|
|
2744
|
+
agentStatusBySession.set(sid, 'interrupted');
|
|
1581
2745
|
const interrupted = await Promise.resolve()
|
|
1582
|
-
.then(() => subs.interrupt(
|
|
2746
|
+
.then(() => subs.interrupt(sid, { kind: 'ancestor', agent: caller }))
|
|
1583
2747
|
.then(() => ({ ok: true, previousStatus: res.member.agentStatus ?? null }),
|
|
1584
2748
|
(err) => ({ ok: false, error: String(err?.message || err) }));
|
|
2749
|
+
if (!interrupted.ok) heldSessions.delete(sid);
|
|
1585
2750
|
return { ...res, agent: interrupted };
|
|
1586
2751
|
}
|
|
1587
2752
|
}
|
|
1588
2753
|
return res;
|
|
1589
2754
|
}
|
|
1590
|
-
if (args.action === 'resume')
|
|
2755
|
+
if (args.action === 'resume') {
|
|
2756
|
+
const res = await request(s, `/api/members/${id}/resume`, { method: 'POST', body: {} });
|
|
2757
|
+
const sid = res?.member?.agentSessionId ? String(res.member.agentSessionId) : null;
|
|
2758
|
+
if (sid) heldSessions.delete(sid);
|
|
2759
|
+
return res;
|
|
2760
|
+
}
|
|
1591
2761
|
if (args.action === 'assign') {
|
|
1592
2762
|
if (!args.taskId) throw new Error('team_control assign requires taskId');
|
|
1593
2763
|
return await request(s, `/api/members/${id}/assign`, { method: 'POST', body: { taskId: args.taskId } });
|
|
@@ -1596,9 +2766,191 @@ function buildTools(s, ctx) {
|
|
|
1596
2766
|
},
|
|
1597
2767
|
});
|
|
1598
2768
|
|
|
2769
|
+
tools.push({
|
|
2770
|
+
name: 'team_member',
|
|
2771
|
+
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.",
|
|
2772
|
+
parameters: {
|
|
2773
|
+
type: 'object',
|
|
2774
|
+
additionalProperties: false,
|
|
2775
|
+
properties: {
|
|
2776
|
+
action: { type: 'string', enum: ['update', 'retire', 'remove'] },
|
|
2777
|
+
teamId: { type: 'string', description: 'Team id; omit to resolve from the current Lead session.' },
|
|
2778
|
+
memberId: { type: 'string', description: 'Member id returned by team_spawn / team_status.' },
|
|
2779
|
+
role: { type: 'string', description: 'update: new role label.' },
|
|
2780
|
+
model: { type: 'string', description: 'update: new LLM model id (empty to inherit). Rebuilds the session.' },
|
|
2781
|
+
agentProvider: { type: 'string', description: 'update: new LLM provider route id. Rebuilds the session.' },
|
|
2782
|
+
contextMode: { type: 'string', enum: ['isolated', 'fresh', 'fork'], description: 'update: new context isolation. Rebuilds the session; old context is lost.' },
|
|
2783
|
+
reasoningEffort: { type: 'string', description: 'update: new reasoning effort id. Rebuilds the session.' },
|
|
2784
|
+
permissionPreset: { type: 'string', description: 'update: DSH permission preset (sandbox + approvals). Applies to the live session without rebuild.' },
|
|
2785
|
+
agentPreset: { type: 'string', description: 'update: DSH agent preset (composition). Rebuilds the session; not supported with contextMode fork.' },
|
|
2786
|
+
confirm: { type: 'boolean', description: 'Required true for action=remove.' },
|
|
2787
|
+
},
|
|
2788
|
+
required: ['action', 'memberId'],
|
|
2789
|
+
},
|
|
2790
|
+
output: jsonOutput('{ member, restarted?, agent?, removed?, panel }'),
|
|
2791
|
+
async execute(args, exec) {
|
|
2792
|
+
const id = encodeURIComponent(args.memberId);
|
|
2793
|
+
const current = await request(s, `/api/members/${id}`);
|
|
2794
|
+
if (!current) throw new Error(`member not found: ${args.memberId}`);
|
|
2795
|
+
const team = await teamOf(s, args.teamId || current.teamId, { sessionId: exec?.agent?.id });
|
|
2796
|
+
if (current.teamId !== team.id) throw new Error('member 不属于指定团队');
|
|
2797
|
+
|
|
2798
|
+
if (args.action === 'retire' || args.action === 'remove') {
|
|
2799
|
+
if (args.action === 'remove' && args.confirm !== true) throw new Error('team_member remove requires confirm:true');
|
|
2800
|
+
const mode = args.action === 'remove' ? 'remove' : 'retire';
|
|
2801
|
+
const res = await request(s, `/api/members/${id}?mode=${mode}${mode === 'remove' ? '&confirm=1' : ''}`, { method: 'DELETE' });
|
|
2802
|
+
let agent = null;
|
|
2803
|
+
if (current.agentSessionId) {
|
|
2804
|
+
const released = await releaseSession(subagentsOf(ctx), exec?.agent, current.agentSessionId);
|
|
2805
|
+
forgetSession(current.agentSessionId);
|
|
2806
|
+
agent = {
|
|
2807
|
+
sessionId: String(current.agentSessionId),
|
|
2808
|
+
released: released.ok,
|
|
2809
|
+
method: released.method || null,
|
|
2810
|
+
...(released.error ? { error: released.error } : {}),
|
|
2811
|
+
};
|
|
2812
|
+
}
|
|
2813
|
+
return { ...res, agent, panel: panelUrl(s) };
|
|
2814
|
+
}
|
|
2815
|
+
|
|
2816
|
+
if (args.action !== 'update') throw new Error(`team_member unknown action: ${args.action}`);
|
|
2817
|
+
if (current.status === 'retired') throw new Error('member is retired; create a new member instead');
|
|
2818
|
+
if (['running', 'provisioning', 'blocked'].includes(current.status)) {
|
|
2819
|
+
throw new Error(`member is ${current.status}; interrupt it before updating configuration`);
|
|
2820
|
+
}
|
|
2821
|
+
|
|
2822
|
+
const has = (key) => Object.prototype.hasOwnProperty.call(args, key);
|
|
2823
|
+
const metadata = {};
|
|
2824
|
+
for (const key of ['role', 'model', 'agentProvider', 'contextMode', 'reasoningEffort', 'permissionPreset', 'agentPreset']) {
|
|
2825
|
+
if (has(key)) metadata[key] = args[key];
|
|
2826
|
+
}
|
|
2827
|
+
const restart = ['model', 'agentProvider', 'contextMode', 'agentPreset', 'reasoningEffort'].some(has);
|
|
2828
|
+
|
|
2829
|
+
if (!restart) {
|
|
2830
|
+
const updated = await request(s, `/api/members/${id}`, { method: 'PATCH', body: metadata });
|
|
2831
|
+
let presetApplied = null;
|
|
2832
|
+
if (has('permissionPreset') && updated.agentSessionId) {
|
|
2833
|
+
presetApplied = applyPermissionPreset(ctx, String(updated.agentSessionId), updated.permissionPreset);
|
|
2834
|
+
}
|
|
2835
|
+
return {
|
|
2836
|
+
member: updated,
|
|
2837
|
+
restarted: false,
|
|
2838
|
+
agent: { sessionId: updated.agentSessionId || null, permissionPresetApplied: presetApplied },
|
|
2839
|
+
panel: panelUrl(s),
|
|
2840
|
+
};
|
|
2841
|
+
}
|
|
2842
|
+
|
|
2843
|
+
const subs = subagentsOf(ctx);
|
|
2844
|
+
const caller = exec?.agent;
|
|
2845
|
+
if (!subs || typeof subs.startActivation !== 'function') throw new Error('subagents 服务不可用:无法重建成员会话');
|
|
2846
|
+
if (!caller) throw new Error('team_member update 需要 Lead 会话上下文(exec.agent 缺失)');
|
|
2847
|
+
|
|
2848
|
+
const leadRoute = leadRouteOf(caller);
|
|
2849
|
+
const oldRoute = {
|
|
2850
|
+
provider: current.agentProvider ?? leadRoute.provider ?? null,
|
|
2851
|
+
model: current.model ?? leadRoute.model ?? null,
|
|
2852
|
+
reasoningEffort: current.reasoningEffort ?? null,
|
|
2853
|
+
};
|
|
2854
|
+
const route = {
|
|
2855
|
+
provider: has('agentProvider') ? (args.agentProvider || null) : oldRoute.provider,
|
|
2856
|
+
model: has('model') ? (args.model || null) : oldRoute.model,
|
|
2857
|
+
reasoningEffort: has('reasoningEffort') ? (args.reasoningEffort || null) : oldRoute.reasoningEffort,
|
|
2858
|
+
};
|
|
2859
|
+
const routeChanged = route.provider !== oldRoute.provider || route.model !== oldRoute.model;
|
|
2860
|
+
if (routeChanged && !has('reasoningEffort')) route.reasoningEffort = null;
|
|
2861
|
+
await assertRouteEnabled(s, ctx, route.provider, route.model, route.reasoningEffort);
|
|
2862
|
+
|
|
2863
|
+
const context = has('contextMode')
|
|
2864
|
+
? (args.contextMode === 'fork' ? 'fork' : 'fresh')
|
|
2865
|
+
: (current.contextMode === 'fork' ? 'fork' : 'fresh');
|
|
2866
|
+
let requestedAgentPreset = has('agentPreset')
|
|
2867
|
+
? await resolveAgentPreset(ctx, args.agentPreset, team.agentPreset, s)
|
|
2868
|
+
: (current.agentPreset || team.agentPreset || null);
|
|
2869
|
+
if (context !== 'fork' && !requestedAgentPreset) {
|
|
2870
|
+
requestedAgentPreset = await hostDefaultAgentPreset(ctx);
|
|
2871
|
+
}
|
|
2872
|
+
const agentPreset = context === 'fork' ? null : requestedAgentPreset;
|
|
2873
|
+
const agentPresetWarning = context === 'fork' && requestedAgentPreset
|
|
2874
|
+
? `contextMode=fork 继承 Lead 的组装,agentPreset「${requestedAgentPreset}」未生效`
|
|
2875
|
+
: undefined;
|
|
2876
|
+
const permissionPreset = has('permissionPreset')
|
|
2877
|
+
? resolvePermissionPreset(ctx, args.permissionPreset, team.permissionPreset)
|
|
2878
|
+
: (current.permissionPreset || team.permissionPreset);
|
|
2879
|
+
const role = has('role') ? args.role : current.role;
|
|
2880
|
+
|
|
2881
|
+
const provider = providerFor(ctx, s, context);
|
|
2882
|
+
const agentOptions = {};
|
|
2883
|
+
if (route.provider) agentOptions.provider = String(route.provider);
|
|
2884
|
+
if (route.model) agentOptions.model = String(route.model);
|
|
2885
|
+
if (route.reasoningEffort) agentOptions.reasoningEffort = String(route.reasoningEffort);
|
|
2886
|
+
|
|
2887
|
+
const sessionId = randomUUID();
|
|
2888
|
+
const started = await subs.startActivation({
|
|
2889
|
+
delivery: 'parent',
|
|
2890
|
+
childId: sessionId,
|
|
2891
|
+
provider,
|
|
2892
|
+
label: memberLabel(current.name, String(role || current.name)),
|
|
2893
|
+
request: {
|
|
2894
|
+
prompt: [{ type: 'text', text: `你是团队成员 ${current.name}(${role || 'teammate'})。配置刚刚更新,这是新的会话;当前没有任务,等待 Lead 派发。收到任务后按简报执行,完成时调用 team_report_task。` }],
|
|
2895
|
+
parent: caller,
|
|
2896
|
+
...(team.workspace ? { cwd: team.workspace } : {}),
|
|
2897
|
+
...(Object.keys(agentOptions).length ? { agentOptions } : {}),
|
|
2898
|
+
...(agentPreset ? { agentPreset } : {}),
|
|
2899
|
+
},
|
|
2900
|
+
signal: exec.signal || AbortSignal.timeout(s.requestTimeoutMs),
|
|
2901
|
+
});
|
|
2902
|
+
if (started && started.result && typeof started.result.catch === 'function') started.result.catch(() => {});
|
|
2903
|
+
const presetResult = applyPermissionPreset(ctx, sessionId, permissionPreset);
|
|
2904
|
+
|
|
2905
|
+
await request(s, '/api/agents/register', {
|
|
2906
|
+
method: 'POST',
|
|
2907
|
+
body: {
|
|
2908
|
+
teamId: team.id,
|
|
2909
|
+
name: current.name,
|
|
2910
|
+
sessionId,
|
|
2911
|
+
parentSessionId: caller.id != null ? String(caller.id) : null,
|
|
2912
|
+
role,
|
|
2913
|
+
model: route.model,
|
|
2914
|
+
contextMode: context,
|
|
2915
|
+
agentProvider: route.provider,
|
|
2916
|
+
permissionPreset,
|
|
2917
|
+
agentPreset, // explicit null = clear old override
|
|
2918
|
+
reasoningEffort: route.reasoningEffort,
|
|
2919
|
+
},
|
|
2920
|
+
});
|
|
2921
|
+
// 只把调用方显式改的字段写回元数据并记 member.update;不要用解析后的
|
|
2922
|
+
// 继承值覆盖成员覆盖项,否则团队预设以后变更时该成员不会再跟随。
|
|
2923
|
+
const updated = await request(s, `/api/members/${id}`, { method: 'PATCH', body: metadata });
|
|
2924
|
+
const release = await releaseSession(subs, caller, current.agentSessionId);
|
|
2925
|
+
forgetSession(current.agentSessionId);
|
|
2926
|
+
rememberMember(sessionId, team.id, updated.id, team.workspace, updated.permissionPreset || permissionPreset, current.name);
|
|
2927
|
+
leadByTeam.set(team.id, caller);
|
|
2928
|
+
return {
|
|
2929
|
+
member: updated,
|
|
2930
|
+
restarted: true,
|
|
2931
|
+
agent: {
|
|
2932
|
+
sessionId,
|
|
2933
|
+
previousSessionId: current.agentSessionId ? String(current.agentSessionId) : null,
|
|
2934
|
+
provider,
|
|
2935
|
+
context,
|
|
2936
|
+
model: route.model,
|
|
2937
|
+
route,
|
|
2938
|
+
release,
|
|
2939
|
+
},
|
|
2940
|
+
permissionPreset: updated.permissionPreset || permissionPreset,
|
|
2941
|
+
agentPreset: updated.agentPreset || agentPreset || null,
|
|
2942
|
+
...(agentPresetWarning ? { agentPresetWarning } : {}),
|
|
2943
|
+
permissionPresetApplied: presetResult.applied,
|
|
2944
|
+
...(presetResult.reason ? { permissionPresetWarning: presetResult.reason } : {}),
|
|
2945
|
+
...(presetResult.error ? { permissionPresetWarning: presetResult.error } : {}),
|
|
2946
|
+
panel: panelUrl(s),
|
|
2947
|
+
};
|
|
2948
|
+
},
|
|
2949
|
+
});
|
|
2950
|
+
|
|
1599
2951
|
tools.push({
|
|
1600
2952
|
name: 'team_report',
|
|
1601
|
-
description: 'Export a Markdown run report: members, tasks/DAG,
|
|
2953
|
+
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
2954
|
parameters: {
|
|
1603
2955
|
type: 'object',
|
|
1604
2956
|
additionalProperties: false,
|
|
@@ -1613,6 +2965,65 @@ function buildTools(s, ctx) {
|
|
|
1613
2965
|
},
|
|
1614
2966
|
});
|
|
1615
2967
|
|
|
2968
|
+
|
|
2969
|
+
tools.push({
|
|
2970
|
+
name: 'board_plan_submit',
|
|
2971
|
+
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.',
|
|
2972
|
+
parameters: {
|
|
2973
|
+
type: 'object',
|
|
2974
|
+
additionalProperties: false,
|
|
2975
|
+
properties: {
|
|
2976
|
+
plan: { type: 'string', description: 'Complete plan in markdown.' },
|
|
2977
|
+
summary: { type: 'string', description: 'One-line summary.' },
|
|
2978
|
+
},
|
|
2979
|
+
required: ['plan'],
|
|
2980
|
+
},
|
|
2981
|
+
output: jsonOutput('{ board task }'),
|
|
2982
|
+
async execute(args, exec) {
|
|
2983
|
+
const sessionId = exec?.agent?.id != null ? String(exec.agent.id) : null;
|
|
2984
|
+
if (!sessionId) throw new Error('board_plan_submit 只能在规划会话里调用');
|
|
2985
|
+
const task = await request(s, '/api/board/agents/plan', {
|
|
2986
|
+
method: 'POST',
|
|
2987
|
+
body: { sessionId, plan: args.plan, summary: args.summary || null },
|
|
2988
|
+
});
|
|
2989
|
+
const rec = boardSessions.get(sessionId);
|
|
2990
|
+
if (rec) rec.phase = 'planned';
|
|
2991
|
+
if (task?.executionMode === 'new' && rec) {
|
|
2992
|
+
const timer = setTimeout(() => {
|
|
2993
|
+
if (rec.phase !== 'planned') return;
|
|
2994
|
+
try { void rec.handle?.dispose?.(); } catch { /* ignore */ }
|
|
2995
|
+
boardSessions.delete(sessionId);
|
|
2996
|
+
boardSessionIds.delete(sessionId);
|
|
2997
|
+
}, 5000);
|
|
2998
|
+
timer.unref?.();
|
|
2999
|
+
}
|
|
3000
|
+
return task;
|
|
3001
|
+
},
|
|
3002
|
+
});
|
|
3003
|
+
|
|
3004
|
+
tools.push({
|
|
3005
|
+
name: 'board_task_status',
|
|
3006
|
+
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.',
|
|
3007
|
+
parameters: {
|
|
3008
|
+
type: 'object',
|
|
3009
|
+
additionalProperties: false,
|
|
3010
|
+
properties: {
|
|
3011
|
+
status: { type: 'string', enum: ['done', 'failed', 'inprogress'] },
|
|
3012
|
+
summary: { type: 'string', description: 'Short result or failure reason.' },
|
|
3013
|
+
},
|
|
3014
|
+
required: ['status'],
|
|
3015
|
+
},
|
|
3016
|
+
output: jsonOutput('{ board task }'),
|
|
3017
|
+
async execute(args, exec) {
|
|
3018
|
+
const sessionId = exec?.agent?.id != null ? String(exec.agent.id) : null;
|
|
3019
|
+
if (!sessionId) throw new Error('board_task_status 只能在看板 Lead 会话里调用');
|
|
3020
|
+
return await request(s, '/api/board/agents/status', {
|
|
3021
|
+
method: 'POST',
|
|
3022
|
+
body: { sessionId, status: args.status, summary: args.summary || null },
|
|
3023
|
+
});
|
|
3024
|
+
},
|
|
3025
|
+
});
|
|
3026
|
+
|
|
1616
3027
|
return tools;
|
|
1617
3028
|
}
|
|
1618
3029
|
|
|
@@ -1920,7 +3331,7 @@ export function apply(ctx, config) {
|
|
|
1920
3331
|
const disposers = buildTools(s, ctx).map((tool) => ctx.tools.register(tool));
|
|
1921
3332
|
return () => {
|
|
1922
3333
|
for (const dispose of disposers.reverse()) { try { dispose(); } catch { /* ignore */ } }
|
|
1923
|
-
leadByTeam.clear();
|
|
3334
|
+
leadByTeam.clear(); teamCache.clear(); sessionMember.clear(); dispatching.clear(); teamBySession.clear(); contextReportAt.clear();
|
|
1924
3335
|
for (const timer of idleTimers.values()) clearTimeout(timer);
|
|
1925
3336
|
for (const timer of startTimers.values()) clearTimeout(timer);
|
|
1926
3337
|
idleTimers.clear(); startTimers.clear(); agentStatusBySession.clear(); lastReplyBySession.clear();
|
|
@@ -1931,6 +3342,29 @@ export function apply(ctx, config) {
|
|
|
1931
3342
|
};
|
|
1932
3343
|
}, 'dsh-team.tools()');
|
|
1933
3344
|
|
|
3345
|
+
// Leader 自建 agentPreset:启动时把固定目录里的 JSON 文档注册进宿主,卸载时反注册。
|
|
3346
|
+
// 注册失败不阻断插件:工具仍可 list/show/save,错误从返回值里看。
|
|
3347
|
+
ctx.effect(() => {
|
|
3348
|
+
teamPresetsReady = null;
|
|
3349
|
+
teamPresetLoading = null;
|
|
3350
|
+
void ensureTeamPresets(s, ctx).then(() => syncPresetCatalog(s, ctx)).catch(() => null);
|
|
3351
|
+
let presetTicks = 0;
|
|
3352
|
+
const presetTimer = setInterval(() => {
|
|
3353
|
+
void processPresetDeletes(s, ctx).catch(() => null);
|
|
3354
|
+
// sidecar 可能比插件晚就绪:每 30s 补一次目录同步,面板不会一直空着。
|
|
3355
|
+
if (++presetTicks % 6 === 0) void syncPresetCatalog(s, ctx).catch(() => null);
|
|
3356
|
+
}, 5000);
|
|
3357
|
+
presetTimer.unref?.();
|
|
3358
|
+
return () => {
|
|
3359
|
+
clearInterval(presetTimer);
|
|
3360
|
+
const pending = [...teamPresetDisposers.values()];
|
|
3361
|
+
teamPresetDisposers.clear();
|
|
3362
|
+
teamPresetsReady = null;
|
|
3363
|
+
teamPresetLoading = null;
|
|
3364
|
+
for (const dispose of pending) { try { void dispose(); } catch { /* ignore */ } }
|
|
3365
|
+
};
|
|
3366
|
+
}, 'dsh-team.presets()');
|
|
3367
|
+
|
|
1934
3368
|
// 技能:skills 服务在场时把包内 `skills/` 注册成 provider,装上插件就带 `dsh-agent-team` 技能;
|
|
1935
3369
|
// 服务缺失(老版本/测试假 ctx)时静默跳过,不影响工具面。
|
|
1936
3370
|
if (typeof ctx.inject === 'function') {
|
|
@@ -1943,6 +3377,16 @@ export function apply(ctx, config) {
|
|
|
1943
3377
|
});
|
|
1944
3378
|
}
|
|
1945
3379
|
|
|
3380
|
+
// 成员权限审批:preset 的 approval=ask 触发时,把请求转给 Lead,由 team_approve 决定。
|
|
3381
|
+
// 放在最前面(prepend),确保本插件的成员请求不会再弹出宿主审批 UI。
|
|
3382
|
+
ctx.effect(() => {
|
|
3383
|
+
const off = ctx.on('approval/request', (req, next) => onApprovalRequest(s, ctx, req, next), { prepend: true });
|
|
3384
|
+
return () => {
|
|
3385
|
+
try { off?.(); } catch { /* ignore */ }
|
|
3386
|
+
cancelPendingApprovals();
|
|
3387
|
+
};
|
|
3388
|
+
}, 'dsh-team.approval()');
|
|
3389
|
+
|
|
1946
3390
|
if (s.reportToolCalls) {
|
|
1947
3391
|
ctx.on('tools/execute', (exec, next) => traceToolCall(s, ctx, exec, next));
|
|
1948
3392
|
}
|
|
@@ -1993,6 +3437,13 @@ export function apply(ctx, config) {
|
|
|
1993
3437
|
agentStatusBySession.set(sessionId, 'running');
|
|
1994
3438
|
return;
|
|
1995
3439
|
}
|
|
3440
|
+
// Lead interrupt 后会话处于冻结态:DSH 中断引发的 idle 不能把成员改回 idle,
|
|
3441
|
+
// 否则 sidecar 认为成员可派发,下一次派发泵又会把它唤醒。
|
|
3442
|
+
if (status === 'idle' && heldSessions.has(sessionId)) {
|
|
3443
|
+
cancelIdleReport(sessionId);
|
|
3444
|
+
agentStatusBySession.set(sessionId, 'interrupted');
|
|
3445
|
+
return;
|
|
3446
|
+
}
|
|
1996
3447
|
if (status !== 'idle') {
|
|
1997
3448
|
cancelIdleReport(sessionId);
|
|
1998
3449
|
agentStatusBySession.set(sessionId, status);
|
|
@@ -2006,6 +3457,7 @@ export function apply(ctx, config) {
|
|
|
2006
3457
|
const settle = Math.max(0, Number(s.agentIdleSettleMs) || 0);
|
|
2007
3458
|
const finish = () => {
|
|
2008
3459
|
idleTimers.delete(sessionId);
|
|
3460
|
+
if (heldSessions.has(sessionId)) { agentStatusBySession.set(sessionId, 'interrupted'); return; }
|
|
2009
3461
|
if (agentStatusBySession.get(sessionId) !== 'idle') return; // 窗口内又跑起来了
|
|
2010
3462
|
// 把这一轮最后的正文带给 sidecar:漏调 team_report_task 时,兜底收尾的 task.done 也有摘要可看
|
|
2011
3463
|
const reply = lastReplyBySession.get(sessionId);
|
|
@@ -2033,6 +3485,8 @@ export function apply(ctx, config) {
|
|
|
2033
3485
|
if (event && event.type === 'turn/end') {
|
|
2034
3486
|
const reason = event.data?.reason;
|
|
2035
3487
|
if (reason && reason.kind === 'error') {
|
|
3488
|
+
// 冻结中的会话:中断本身可能让回合以 error 结束,不要覆盖 sidecar 的 interrupted。
|
|
3489
|
+
if (heldSessions.has(sessionId)) return;
|
|
2036
3490
|
const err = reason.error || {};
|
|
2037
3491
|
const msg = String(err.message || err.code || 'unknown error').slice(0, 500);
|
|
2038
3492
|
cancelIdleReport(sessionId);
|
|
@@ -2056,6 +3510,15 @@ export function apply(ctx, config) {
|
|
|
2056
3510
|
return () => clearInterval(timer);
|
|
2057
3511
|
}, 'dsh-team.agent-heartbeat()');
|
|
2058
3512
|
|
|
3513
|
+
// 面板/看板停止的强制收尾:sidecar 只把成员置 interrupted,真正中断 DSH 会话在这里做。
|
|
3514
|
+
ctx.effect(() => {
|
|
3515
|
+
const timer = setInterval(() => {
|
|
3516
|
+
void forceStopPump(s, ctx).catch(() => { /* ignore */ });
|
|
3517
|
+
}, Math.max(250, s.forceStopPollMs));
|
|
3518
|
+
timer.unref?.();
|
|
3519
|
+
return () => clearInterval(timer);
|
|
3520
|
+
}, 'dsh-team.force-stop-pump()');
|
|
3521
|
+
|
|
2059
3522
|
// 成员上下文快照:面板「上下文分析」页的数据来源。周期泵覆盖进行中的回合,
|
|
2060
3523
|
// agent/status 变化时补报一次(回合结束/中断后上下文占用才定型)。
|
|
2061
3524
|
if (s.reportContext) {
|
|
@@ -2111,6 +3574,87 @@ export function apply(ctx, config) {
|
|
|
2111
3574
|
}, 'dsh-team.llm-catalog-pump()');
|
|
2112
3575
|
}
|
|
2113
3576
|
|
|
3577
|
+
// 看板会话审批:规划阶段只读,任何审批直接拒绝,避免无人值守卡住。
|
|
3578
|
+
// 执行阶段用 danger-full-access(never),正常情况下不会走到这里。
|
|
3579
|
+
if (s.boardEnabled) {
|
|
3580
|
+
ctx.effect(() => {
|
|
3581
|
+
const off = ctx.on('approval/request', (req, next) => {
|
|
3582
|
+
const sessionId = req?.agent?.id != null ? String(req.agent.id) : null;
|
|
3583
|
+
const rec = sessionId ? boardSessions.get(sessionId) : null;
|
|
3584
|
+
if (rec && rec.phase === 'planning') return 'rejected';
|
|
3585
|
+
return next();
|
|
3586
|
+
}, { prepend: true });
|
|
3587
|
+
return () => { try { off?.(); } catch { /* ignore */ } };
|
|
3588
|
+
}, 'dsh-team.board-approval()');
|
|
3589
|
+
}
|
|
3590
|
+
|
|
3591
|
+
// 看板会话的后续用户消息:done/failed 被追问时翻回 inprogress(sidecar 只对这些状态生效)。
|
|
3592
|
+
// 自己注入的首条 prompt 也会触发,但此时状态是 planning/inprogress,sidecar 会拒绝,不会误翻。
|
|
3593
|
+
ctx.on('session/event', (session, event) => {
|
|
3594
|
+
const sessionId = session?.id != null ? String(session.id) : null;
|
|
3595
|
+
if (!sessionId || !boardSessionIds.has(sessionId)) return;
|
|
3596
|
+
if (!event || event.type !== 'user/message') return;
|
|
3597
|
+
void request(s, '/api/board/agents/status', {
|
|
3598
|
+
method: 'POST', body: { sessionId, status: 'inprogress' },
|
|
3599
|
+
}).catch(() => { /* 非终态时 sidecar 会拒绝,忽略 */ });
|
|
3600
|
+
});
|
|
3601
|
+
|
|
3602
|
+
// 规划会话 idle 却没有提交计划:给工具收尾留一个宽限窗口,仍停在 planning 就判失败。
|
|
3603
|
+
ctx.on('agent/status', ({ agent, status } = {}) => {
|
|
3604
|
+
const sessionId = agent?.id != null ? String(agent.id) : null;
|
|
3605
|
+
const rec = sessionId ? boardSessions.get(sessionId) : null;
|
|
3606
|
+
if (!rec) return;
|
|
3607
|
+
if (status === 'running') { rec.sawRunning = true; return; }
|
|
3608
|
+
if (status !== 'idle' || rec.phase !== 'planning' || !rec.sawRunning) return;
|
|
3609
|
+
const timer = setTimeout(() => {
|
|
3610
|
+
void (async () => {
|
|
3611
|
+
if (rec.phase !== 'planning') return;
|
|
3612
|
+
try {
|
|
3613
|
+
const task = await request(s, `/api/board/tasks/${encodeURIComponent(rec.taskId)}`);
|
|
3614
|
+
if (task?.status !== 'planning') return;
|
|
3615
|
+
await request(s, '/api/board/agents/status', {
|
|
3616
|
+
method: 'POST', body: { sessionId, status: 'failed', summary: '规划会话空闲但未提交计划' },
|
|
3617
|
+
});
|
|
3618
|
+
} catch { /* ignore */ }
|
|
3619
|
+
})();
|
|
3620
|
+
}, Math.max(0, s.boardIdleGraceMs));
|
|
3621
|
+
timer.unref?.();
|
|
3622
|
+
});
|
|
3623
|
+
|
|
3624
|
+
// 把 DSH Web 的浏览器地址报给 sidecar:独立面板据此 window.open 到 `#dsh-session=<id>`
|
|
3625
|
+
// 深链,由 dsh-plugin-ui 的客户端半边接管并打开对应会话。
|
|
3626
|
+
ctx.effect(() => {
|
|
3627
|
+
const report = () => {
|
|
3628
|
+
try {
|
|
3629
|
+
const ws = typeof ctx.get === 'function' ? ctx.get('webServer') : undefined;
|
|
3630
|
+
if (!ws || !ws.port) return;
|
|
3631
|
+
const host = String(ws.host || '127.0.0.1');
|
|
3632
|
+
const authority = host.includes(':') ? `[${host}]` : host;
|
|
3633
|
+
const proto = ws.config?.tls ? 'https' : 'http';
|
|
3634
|
+
void request(s, '/api/host/web', { method: 'POST', body: { url: `${proto}://${authority}:${ws.port}` } })
|
|
3635
|
+
.catch(() => { /* sidecar 未就绪时下一轮再报 */ });
|
|
3636
|
+
} catch { /* 宿主没有 webServer 服务时跳过 */ }
|
|
3637
|
+
};
|
|
3638
|
+
report();
|
|
3639
|
+
const timer = setInterval(report, 60000);
|
|
3640
|
+
timer.unref?.();
|
|
3641
|
+
return () => clearInterval(timer);
|
|
3642
|
+
}, 'dsh-team.host-web()');
|
|
3643
|
+
|
|
3644
|
+
// 看板调度泵:每个 tick 向 sidecar claim 规划/执行槽位,claim 到就建会话并投 prompt。
|
|
3645
|
+
if (s.boardEnabled) {
|
|
3646
|
+
ctx.effect(() => {
|
|
3647
|
+
const timer = setInterval(() => { void boardPump(s, ctx).catch(() => { /* ignore */ }); }, Math.max(500, s.boardDispatchMs));
|
|
3648
|
+
timer.unref?.();
|
|
3649
|
+
return () => {
|
|
3650
|
+
clearInterval(timer);
|
|
3651
|
+
for (const rec of boardSessions.values()) { try { void rec.handle?.dispose?.(); } catch { /* ignore */ } }
|
|
3652
|
+
boardSessions.clear();
|
|
3653
|
+
boardSessionIds.clear();
|
|
3654
|
+
};
|
|
3655
|
+
}, 'dsh-team.board-pump()');
|
|
3656
|
+
}
|
|
3657
|
+
|
|
2114
3658
|
// 保底泵:负责 lead 不在工具调用栈里时(例如成员直接回报)把 ready 任务继续发出去。
|
|
2115
3659
|
if (s.agentAutoDispatch) {
|
|
2116
3660
|
ctx.effect(() => {
|
|
@@ -2123,4 +3667,13 @@ export function apply(ctx, config) {
|
|
|
2123
3667
|
return () => clearInterval(timer);
|
|
2124
3668
|
}, 'dsh-team.agent-pump()');
|
|
2125
3669
|
}
|
|
3670
|
+
|
|
3671
|
+
// steer 泵:把面板排进 sidecar 的队列消息(kind='steer')推进成员会话。
|
|
3672
|
+
ctx.effect(() => {
|
|
3673
|
+
const timer = setInterval(() => {
|
|
3674
|
+
void steerPump(s, ctx).catch(() => { /* ignore */ });
|
|
3675
|
+
}, Math.max(500, s.steerPollMs));
|
|
3676
|
+
timer.unref?.();
|
|
3677
|
+
return () => clearInterval(timer);
|
|
3678
|
+
}, 'dsh-team.steer-pump()');
|
|
2126
3679
|
}
|