@suifei/dsh-ai-team 0.4.154 → 0.4.155

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/CHANGELOG.md CHANGED
@@ -1,5 +1,10 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.155 - 2026-12-03
4
+
5
+ - DSH 会话可用 `/ai-team 建队` 预览当前工作目录和团队预设,确认后创建项目。取消草稿和重复确认均有回归,创建后 PMO 自动初始关闭。感谢 @buger-gif 提供会话建队场景(#121)。
6
+ - 编制巡检和补位建议按各项目的根代理树跟踪并发上限。并发排队在本树释放槽位后补投,保留定时重试。感谢 @buger-gif 的容量与编制案例(#116)。
7
+
3
8
  ## 0.4.154 - 2026-12-03
4
9
 
5
10
  - 新建和编辑项目可用宿主的浏览式目录列表。选定后回填路径,提交表单时才保存或创建项目。感谢 @ljyzww 提供 Windows 复现与宿主契约(#100)。
package/README.md CHANGED
@@ -37,6 +37,7 @@
37
37
 
38
38
  ## 最近更新
39
39
 
40
+ - **从会话建队与分树容量**(0.4.155)。在 DSH 会话输入目标即可预览目录和岗位,确认后由现有流程创建项目。编制巡检和排队补投按项目代理树处理并发。感谢 [@buger-gif](https://github.com/buger-gif),[#121](https://github.com/suifei/dsh-ai-team/issues/121)、[#116](https://github.com/suifei/dsh-ai-team/issues/116)。
40
41
  - **目录浏览和验收补位**(0.4.154)。新建或编辑项目时可使用宿主的原生对话框或浏览式选择器。桌面安装说明补齐首次初始化和退出步骤。编制巡检标明缺少合格验收人的任务、观察到的成员回合和容量来源。感谢 [@ljyzww](https://github.com/ljyzww),[#100](https://github.com/suifei/dsh-ai-team/issues/100)。感谢 [@Arnoldnuo](https://github.com/Arnoldnuo),[#102](https://github.com/suifei/dsh-ai-team/issues/102)。感谢 [@buger-gif](https://github.com/buger-gif),[#116](https://github.com/suifei/dsh-ai-team/issues/116)。
41
42
  - **看板受阻、离队交接和只读巡检**(0.4.153)。看板按当前状态显示受阻,历史依赖仍可查。离队与认领按同一顺序处理,待交接的原卡能交给继任者。普通项目可以开启只读编制巡检。感谢 [@idontlikefruit](https://github.com/idontlikefruit),[#115](https://github.com/suifei/dsh-ai-team/issues/115)。感谢 [@buger-gif](https://github.com/buger-gif),[#116](https://github.com/suifei/dsh-ai-team/issues/116)、[#117](https://github.com/suifei/dsh-ai-team/issues/117)。
42
43
  - **派发预检和 DSH 0.2.3 兼容**(0.4.153)。PMO 在唤醒前核对依赖、在手任务和写入范围。工作台兼容新版宿主的会话鉴权。感谢 [@buger-gif](https://github.com/buger-gif),[#120](https://github.com/suifei/dsh-ai-team/issues/120)。感谢 [@Estelle00](https://github.com/Estelle00),[#122](https://github.com/suifei/dsh-ai-team/issues/122)。
@@ -128,6 +129,18 @@ const svg = HashAvatar.svg('墨渊', { gender: 'male', age: 'middle', race: 'asi
128
129
  - **在线人才库同步**:人才市场顶部「同步在线库」从官方在线人才库 [`@suifei/dsh-ai-team-catalog`](https://www.npmjs.com/package/@suifei/dsh-ai-team-catalog)(npmmirror → jsDelivr → npmjs;registry 下整包核对 integrity)取最新的人才与团队,按 `index.json` 逐文件核对 sha256 后整体替换,落到 `~/.dsh/ai-team/catalog/official/<版本>/`;失败不动现有的。优先级:自建 > 在线 > 内置(插件升级后内置版本更高的人才用内置)。「退回内置」删掉本机在线库。内网可设环境变量 `DSH_AI_TEAM_CATALOG_MIRROR` 指向 npmmirror 同形的私有源。在线人才同样只读,可「复制为可编辑」。
129
130
  - 成员在账本里记下来源人才与版本、职责;人才文件之后再改,不会悄悄改动已招成员的性格与职责。已有项目不受新团队影响。文件写坏时跳过它并在诊断日志记 `catalog.load.fail` / `catalog.team.fail`。
130
131
 
132
+ ### 从 DSH 会话建队
133
+
134
+ 在已有工作目录的 DSH 会话中输入以下命令。
135
+
136
+ ```text
137
+ /ai-team 建队 --team docs 整理接口文档
138
+ ```
139
+
140
+ 会话会显示工作目录、目标、团队预设与岗位。输入草稿末尾的 `/ai-team 确认 草稿ID` 创建项目,或用对应的取消命令丢弃草稿。省略 `--team` 时使用设置中的默认团队预设。草稿跟随当前会话,宿主重启后可以重新生成。
141
+
142
+ 新项目会出现在文渊阁,PMO 自动初始关闭。团队准备好后,可以在项目页开启 PMO 自动。
143
+
131
144
  ### 按蓝图试跑
132
145
 
133
146
  在「新建项目 → 按蓝图试跑」填写业务、月目标、你保留的工作、每周可投入时间和手工耗时。插件比较候选的已知手工负担,把首发收窄到一个真实样本和一份待审草稿。预览里可以查看岗位提示词、验收清单和七天上线步骤。
@@ -142,7 +155,7 @@ const svg = HashAvatar.svg('墨渊', { gender: 'male', age: 'middle', race: 'asi
142
155
 
143
156
  在当前 DSH profile 的 `ai-team` 配置中设 `staffingReviewMinutes: 180` 和 `diagLevel: full` 后,启用 PMO 自动的运行中普通项目会随现有巡检周期采样,每个时间窗口记录一次。`staffingReviewMinutes: 0`(默认)关闭采样。诊断日志中的 `pmo.staffing.review` 包含岗位已分配队列、可认领与待验收队列、最长及平均等待,以及采样窗口内每位成员的提交、验收和退回。返工率按退回的本窗口提交除以本窗口提交数计算,零样本为空。
144
157
 
145
- 巡检还会记录没有合格验收人的任务 ID、插件观察到的在队成员运行回合数和容量来源。容量来源为 `default` 时使用默认估计,为 `host` 时来自宿主报告。PMO 会把长期无人可验收的任务带进现有补位建议。
158
+ 巡检还会记录没有合格验收人的任务 ID、插件观察到的在队成员运行回合数和容量来源。并发上限按当前项目的根代理树记录,来源为 `default` 时使用默认估计,为 `host` 时来自这棵树的宿主容量回执。宿主释放槽位后,插件优先补投本树排队最久的成员。PMO 会把长期无人可验收的任务带进现有补位建议。
146
159
 
147
160
  巡检复用现有派员建议和冷却规则,记录被暂缓的建议。人员动作仍由已有授权流程处理。试跑样本和调整建议可回到 [#116](https://github.com/suifei/dsh-ai-team/issues/116)。
148
161
 
@@ -391,7 +404,7 @@ round-19 DeepSeek + Zhipu 双 provider
391
404
  | 贡献者 | 贡献 | 带来的进展 |
392
405
  |---|---|---|
393
406
  | [@idontlikefruit](https://github.com/idontlikefruit) | 受阻状态的三组复现输入 [#115](https://github.com/suifei/dsh-ai-team/issues/115) | 统一看板徽标、读屏和分组统计的受阻判定,保留历史依赖 |
394
- | [@buger-gif](https://github.com/buger-gif) | 编制巡检、离队交接案例 [#116](https://github.com/suifei/dsh-ai-team/issues/116)、[#117](https://github.com/suifei/dsh-ai-team/issues/117),派发空转记录 [#120](https://github.com/suifei/dsh-ai-team/issues/120) | 统一认领与离队的执行顺序,在唤醒前检查认领条件,巡检识别缺少合格验收人的任务并记录运行回合和容量来源 |
407
+ | [@buger-gif](https://github.com/buger-gif) | 编制巡检、离队交接案例 [#116](https://github.com/suifei/dsh-ai-team/issues/116)、[#117](https://github.com/suifei/dsh-ai-team/issues/117),派发空转记录 [#120](https://github.com/suifei/dsh-ai-team/issues/120),会话建队场景 [#121](https://github.com/suifei/dsh-ai-team/issues/121) | 统一认领与离队顺序,减少派发空转,记录验收缺口与项目代理树容量,并在 DSH 会话里预览和确认建队 |
395
408
  | [@Estelle00](https://github.com/Estelle00) | DSH 0.2.3 启动 503 的复现和桌面验证 [#122](https://github.com/suifei/dsh-ai-team/issues/122) | 接入新版会话鉴权接口,恢复工作台初始化 |
396
409
  | [@phm101299-ui](https://github.com/phm101299-ui) | PMO 冷恢复的复现、根因和桌面验证 [#112](https://github.com/suifei/dsh-ai-team/issues/112) | 让原 PMO 在宿主重启后带着模型路由继续工作,保留成员关系和任务 |
397
410
  | [@godfay-g](https://github.com/godfay-g) | 技能目录和 ZIP 的导入建议 [#109](https://github.com/suifei/dsh-ai-team/issues/109) | 成员与自定义人才可在文渊阁选择已安装的技能或导入完整技能包。0.4.151 统一新建人才的导入入口,并由文渊阁直接安装整包 |
package/index.js CHANGED
@@ -14,15 +14,17 @@ import { homedir, tmpdir } from 'node:os';
14
14
  import { randomUUID } from 'node:crypto';
15
15
  import { isAbsolute, join, relative, sep } from 'node:path';
16
16
  import { fileURLToPath } from 'node:url';
17
- import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
17
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
18
18
  import { realpath, stat } from 'node:fs/promises';
19
19
  import z from '@deepseek-ai/schemastery';
20
20
  import { ProjectRuntime } from './lib/host/project-runtime.js';
21
21
  import { ProjectRegistry } from './lib/host/project-registry.js';
22
22
  import { resolveDefaultWorkspace } from './lib/host/default-workspace.js';
23
- import { hostPlatform, workspaceExample } from './lib/host/workspace-path.js';
23
+ import { hostPlatform, requireWorkspaceDirectory, workspaceExample } from './lib/host/workspace-path.js';
24
+ import { sessionTeamCommand } from './lib/host/session-team-command.js';
24
25
  import { migrateLegacyNamespace, resolveProfile } from './lib/ledger/namespace.js';
25
26
  import { ids } from './lib/domain/ids.js';
27
+ import { ERRORS, fail } from './lib/domain/errors.js';
26
28
  import { MemberRuntime, validatePermissionProfile } from './lib/runtime/member-runtime.js';
27
29
  import { ensureHostAgent } from './lib/runtime/host-agent.js';
28
30
  import { activationSpec } from './lib/runtime/activation-spec.js';
@@ -61,7 +63,7 @@ import { buildModelCatalog, buildModelEfforts } from './lib/host/model-catalog.j
61
63
  import { createTeamTool } from './lib/host/member-tools.js';
62
64
  import { canDeliverWake, describeTaskContext, describeWake, planWakes } from './lib/host/waker.js';
63
65
  import { describeCauseChain } from './lib/runtime/error-chain.js';
64
- import { capacityLimit, classifyWakeFailure, deferredWakeKind, isCapacityError, isMalformedTurnError } from './lib/runtime/wake-failure.js';
66
+ import { classifyWakeFailure, deferredWakeKind, isCapacityError, isMalformedTurnError, observeTreeCapacity } from './lib/runtime/wake-failure.js';
65
67
  import { createDeferredWakes } from './lib/runtime/deferred-wakes.js';
66
68
  import { registerShellGuard } from './lib/runtime/shell-guard.js';
67
69
  import { registerOneShotToolGuard, registerStopGuard } from './lib/runtime/stop-guard.js';
@@ -180,11 +182,27 @@ async function memberHostSkillReferences(names, ownedRoots, summaries) {
180
182
 
181
183
  /** 新项目用哪个团队:新建时选的优先,其次插件设置 `teamPreset`,最后内置默认团队。 */
182
184
  function teamPresetFor(config, diag, chosen = '') {
183
- const preset = resolveTeam(talentCatalog(diag), chosen || config?.teamPreset || DEFAULT_TEAM, { diag });
185
+ const catalog = talentCatalog(diag);
186
+ if (chosen !== '') {
187
+ const entry = listTeams(catalog).find((team) => team.id === chosen);
188
+ if (entry === undefined) fail(ERRORS.INVALID_ARGUMENT, `团队不存在:${chosen}`, { status: 400 });
189
+ if (entry.broken) fail(ERRORS.INVALID_ARGUMENT, `团队「${entry.name}」引用了不存在的人才,先修好再用`, { status: 400 });
190
+ }
191
+ const preset = resolveTeam(catalog, chosen || config?.teamPreset || DEFAULT_TEAM, { diag });
184
192
  diag?.append?.({ ev: 'catalog.team', name: preset.id, source: preset.source, dir: preset.dir, members: preset.team.members.length });
185
193
  return preset;
186
194
  }
187
195
 
196
+ function projectInput(payload) {
197
+ const name = typeof payload?.name === 'string' ? payload.name.trim() : '';
198
+ const goal = typeof payload?.goal === 'string' ? payload.goal.trim() : '';
199
+ const workspacePath = typeof payload?.workspacePath === 'string' ? payload.workspacePath.trim() : '';
200
+ if (name === '') fail(ERRORS.INVALID_ARGUMENT, 'project name is required', { status: 400 });
201
+ if (workspacePath === '') fail(ERRORS.INVALID_ARGUMENT, '工作目录是必填项:请选择一个已存在的目录', { status: 400 });
202
+ requireWorkspaceDirectory(workspacePath, 400);
203
+ return { name, goal, workspacePath };
204
+ }
205
+
188
206
  /**
189
207
  * 惰性 shell 服务代理:插件注入时机可能早于 shell 服务就绪,注册与 tick 都
190
208
  * 必须在调用时现取,避免「boot 时未就绪 → 整条技能链静默跳过」。
@@ -947,6 +965,16 @@ export function apply(ctx, config = {}) {
947
965
  await deliverWakePlans(runtime, [plan], { retry: true });
948
966
  },
949
967
  });
968
+ const offSubagentEnd = typeof ctx.on === 'function'
969
+ ? ctx.on('subagent/end', (info) => {
970
+ if (typeof info?.parentSessionId !== 'string') return;
971
+ try {
972
+ const parent = serviceOf(ctx, 'agents')?.get?.(info.parentSessionId);
973
+ const subagents = serviceOf(ctx, 'subagents');
974
+ if (parent) deferredWakes.capacityReleased(subagents?.rootOf?.(parent));
975
+ } catch { /* the durable creator may have exited; the queued retry retains its timer */ }
976
+ })
977
+ : () => {};
950
978
  // provider 探测状态去重:能力缺失/确认无 provider 只各记一次,避免每轮刷日志。
951
979
  let lastProviderState = '';
952
980
  // PMO tick 是 fire-and-forget:慢 tick(模型/IO)会被下一分钟的定时器再入,
@@ -978,12 +1006,8 @@ export function apply(ctx, config = {}) {
978
1006
  // 空闲必派的节流状态(按项目):上次叫的时间、局面签名、同一局面重复次数(planIdleStaffing)。
979
1007
  const pmoLastStaffing = new Map();
980
1008
  const pmoStaffingReviewWindows = new Map();
981
- // 宿主同时在跑的子智能体上限:默认 8,见到容量报错就以报错里的数字为准(加人建议的排队提示用)。
982
- let observedHostCapacity = null;
983
- const noteHostCapacity = (error) => {
984
- const limit = capacityLimit(error);
985
- if (limit !== null) observedHostCapacity = limit;
986
- };
1009
+ // DSH 的 ActivationPool 按根 Agent 分配,已观察的上限随当前项目树而变。
1010
+ const treeCapacity = observeTreeCapacity();
987
1011
  const pmoLastEscalate = new Map();
988
1012
  const pmoLastReview = new Map();
989
1013
  let pmoTimer = null;
@@ -1216,9 +1240,9 @@ export function apply(ctx, config = {}) {
1216
1240
  // - 超过宿主并发上限(默认 8):宿主不排队直接拒绝,团队多出来的人由插件排队。
1217
1241
  const deferMember = projectRuntime.service.state.members?.[plan.memberId];
1218
1242
  const deferKind = deferredWakeKind(error);
1219
- noteHostCapacity(error);
1243
+ treeCapacity.record(parentInfo.agent, error);
1220
1244
  if (deferKind !== null && (deferKind !== 'stale-tree' || typeof deferMember?.sessionId === 'string')
1221
- && deferredWakes.defer({ kind: deferKind, sessionId: deferMember?.sessionId ?? null, projectId: projectRuntime.id, memberId: plan.memberId, plan, retry })) {
1245
+ && deferredWakes.defer({ kind: deferKind, sessionId: deferMember?.sessionId ?? null, root: parentInfo.agent, projectId: projectRuntime.id, memberId: plan.memberId, plan, retry })) {
1222
1246
  continue;
1223
1247
  }
1224
1248
  const causeChain = describeCauseChain(error);
@@ -1486,6 +1510,7 @@ export function apply(ctx, config = {}) {
1486
1510
  const reviewDue = reviewWindow !== null && pmoStaffingReviewWindows.get(projectRuntime.id) !== reviewWindow;
1487
1511
  const suppressed = [];
1488
1512
  const inTurn = (id) => turnsInFlight.has(id);
1513
+ const observedHostCapacity = treeCapacity.get(hosts.get(projectRuntime.id)?.agent);
1489
1514
  const capacity = observedHostCapacity ?? HOST_SUBAGENT_LIMIT;
1490
1515
  const adviceList = planStaffingAdvice(staffingState, {
1491
1516
  now, inTurn, capacity,
@@ -2294,6 +2319,7 @@ export function apply(ctx, config = {}) {
2294
2319
  diag?.append({ ev: 'activate.reject', projectId: projectRuntime.id, memberId: member.id, code: 'E_RUNTIME_UNAVAILABLE', detail: 'no provider' });
2295
2320
  return { error: { code: 'E_RUNTIME_UNAVAILABLE', message: 'no subagent provider is registered' }, status: 503 };
2296
2321
  }
2322
+ let capacityRoot;
2297
2323
  try {
2298
2324
  const selection = serviceOf(ctx, 'agentDefaultModel')?.currentSelection?.();
2299
2325
  const activationMember = member.config?.provider && member.config?.model
@@ -2310,6 +2336,7 @@ export function apply(ctx, config = {}) {
2310
2336
  return { error: { code: 'E_RUNTIME_UNAVAILABLE', message: 'no member or default provider/model is configured' }, status: 503 };
2311
2337
  }
2312
2338
  const parentInfo = await ensureParent(projectRuntime);
2339
+ capacityRoot = parentInfo.agent;
2313
2340
  const runtime = new MemberRuntime({
2314
2341
  subagents,
2315
2342
  sessions,
@@ -2387,7 +2414,7 @@ export function apply(ctx, config = {}) {
2387
2414
  // 超过宿主并发上限:不是成员失败——记 failed 会让 waker 再也不叫它(团队超过 8 人时第 9 位
2388
2415
  // 首次激活就会被永久搁置)。保持原状态,唤醒路径会把它排进 deferredWakes 的 capacity 队列。
2389
2416
  if (isCapacityError(error)) {
2390
- noteHostCapacity(error);
2417
+ treeCapacity.record(capacityRoot, error);
2391
2418
  diag.append({ ev: 'member.activate.capacity', memberId: member.id, projectId: projectRuntime.id, message: error?.message ?? String(error) });
2392
2419
  } else if (currentStatus !== 'retired') {
2393
2420
  try {
@@ -2503,31 +2530,41 @@ export function apply(ctx, config = {}) {
2503
2530
  };
2504
2531
 
2505
2532
  const blueprintCreations = new Map();
2506
- async function activateProject(nextProjectId, projectName, projectGoal, workspacePath = '', team = '', blueprint = null) {
2533
+ const projectActivations = new Set();
2534
+ function activateProject(projectId, input) {
2535
+ const activation = activateProjectRuntime(projectId, input);
2536
+ const settled = () => projectActivations.delete(activation);
2537
+ projectActivations.add(activation);
2538
+ activation.then(settled, settled);
2539
+ return activation;
2540
+ }
2541
+ async function activateProjectRuntime(nextProjectId, { name, goal, workspacePath = '', teamPreset = null, blueprint = null, pmoAuto = true }) {
2507
2542
  await ready;
2508
- if (booted === null) throw new Error('team ledger is unavailable');
2543
+ if (disposed || booted === null) throw new Error('team ledger is unavailable');
2509
2544
  let next = projectRuntime(nextProjectId);
2510
2545
  if (next === null) {
2511
2546
  next = await ProjectRuntime.open({
2512
2547
  rootDir: booted.dataDir,
2513
2548
  projectId: nextProjectId,
2514
- projectName,
2515
- projectGoal,
2549
+ projectName: name,
2550
+ projectGoal: goal,
2516
2551
  workspacePath,
2517
2552
  diag,
2518
2553
  pmoMaxRounds: config.pmoMaxRounds,
2519
- teamPreset: blueprint ? null : teamPresetFor(config, diag, team),
2554
+ teamPreset: blueprint ? null : teamPreset ?? teamPresetFor(config, diag),
2520
2555
  blueprint,
2556
+ pmoAuto,
2521
2557
  });
2522
2558
  // 账本和两个岗位先落地,重启时才不会把半写的蓝图项目播种成预设团队。
2523
2559
  try {
2524
- booted.registry.add({ id: nextProjectId, name: projectName, goal: projectGoal, workspacePath });
2560
+ booted.registry.add({ id: nextProjectId, name, goal, workspacePath });
2525
2561
  } catch (error) {
2526
- next.close();
2562
+ await next.close();
2527
2563
  throw error;
2528
2564
  }
2529
2565
  booted.runtimes.set(nextProjectId, next);
2530
- attachRuntime(next);
2566
+ if (!disposed) attachRuntime(next);
2567
+ diag.append({ ev: 'project.create', id: nextProjectId, team: teamPreset?.id ?? null });
2531
2568
  }
2532
2569
  booted.registry.setActive(nextProjectId);
2533
2570
  booted = {
@@ -2537,9 +2574,25 @@ export function apply(ctx, config = {}) {
2537
2574
  ledger: next.ledger,
2538
2575
  service: next.service,
2539
2576
  };
2540
- broadcast(undefined, next);
2577
+ if (!disposed) broadcast(undefined, next);
2541
2578
  return next;
2542
2579
  }
2580
+ const nativeTeamCommand = sessionTeamCommand({
2581
+ prepare: (input) => ({ ...projectInput(input), teamPreset: teamPresetFor(config, diag, input.team) }),
2582
+ create: async (id, input) => (await activateProject(id, { ...input, pmoAuto: false })).service.state.projects[id],
2583
+ diag,
2584
+ });
2585
+ const registerSessionCommand = (scoped) => {
2586
+ const registry = serviceOf(scoped, 'commands');
2587
+ if (typeof registry?.register !== 'function') return () => {};
2588
+ const unregister = registry.register(nativeTeamCommand);
2589
+ diag.append({ ev: 'session.team.command.registered' });
2590
+ return unregister;
2591
+ };
2592
+ const commandScope = typeof ctx.inject === 'function'
2593
+ ? ctx.inject(['commands'], (scoped) => scoped.effect(() => registerSessionCommand(scoped), 'ai-team: session command'))
2594
+ : null;
2595
+ const disposeSessionCommand = commandScope === null ? registerSessionCommand(ctx) : () => commandScope.dispose();
2543
2596
 
2544
2597
  const dispose = webServer.register({
2545
2598
  kind: 'prefix',
@@ -3352,28 +3405,9 @@ export function apply(ctx, config = {}) {
3352
3405
  return send(res, distilled);
3353
3406
  }
3354
3407
  if (body.type === 'project.create' || body.type === 'project.blueprint.preview') {
3355
- const name = typeof body.payload?.name === 'string' ? body.payload.name.trim() : '';
3356
- const goal = typeof body.payload?.goal === 'string' ? body.payload.goal.trim() : '';
3357
- const workspacePath = typeof body.payload?.workspacePath === 'string' ? body.payload.workspacePath.trim() : '';
3408
+ const input = projectInput(body.payload);
3409
+ const { name, goal, workspacePath } = input;
3358
3410
  const preview = body.type === 'project.blueprint.preview';
3359
- if (name === '') return send(res, { error: { code: 'E_INVALID_ARGUMENT', message: 'project name is required' } }, 400);
3360
- // 每个项目都必须指定工作目录:先在这里挡,别把一行没有目录的
3361
- // registry 记录写进去(service 也会再校验一次)。
3362
- if (workspacePath === '') {
3363
- return send(res, { error: { code: 'E_INVALID_ARGUMENT', message: '工作目录是必填项:请选择一个已存在的目录' } }, 400);
3364
- }
3365
- // 工作目录可空(稍后设置):讨论与建卡不受限;成员激活在
3366
- // activateMember 处 fail-closed,绝不落到宿主默认目录执行。
3367
- // 但给了就必须真实存在:非法路径若先写进 registry,boot 会在
3368
- // 该项上抛出,导致整个插件起不来(所有路由 503),只能手工改
3369
- // projects.json 才能恢复。
3370
- if (workspacePath !== '') {
3371
- let stat = null;
3372
- try { stat = statSync(workspacePath); } catch { stat = null; }
3373
- if (stat === null || (typeof stat.isDirectory === 'function' && stat.isDirectory() !== true)) {
3374
- return send(res, { error: { code: 'E_INVALID_ARGUMENT', message: `工作目录不存在或不是目录:${workspacePath}` } }, 400);
3375
- }
3376
- }
3377
3411
  const blueprint = preview || body.payload?.blueprint !== undefined ? buildTeamBlueprint({ ...body.payload?.blueprint, goal }) : null;
3378
3412
  if (blueprint) {
3379
3413
  const id = preview ? ids.project() : body.payload?.blueprintId;
@@ -3397,23 +3431,16 @@ export function apply(ctx, config = {}) {
3397
3431
  let pending = blueprintCreations.get(id);
3398
3432
  if (pending && pending.fingerprint !== fingerprint) return send(res, { error: { code: 'E_CONFLICT', message: '这个蓝图正在创建' } }, 409);
3399
3433
  if (!pending) {
3400
- const runtimePromise = activateProject(id, name, goal, workspacePath, '', blueprint).finally(() => blueprintCreations.delete(id));
3434
+ const runtimePromise = activateProject(id, { ...input, blueprint }).finally(() => blueprintCreations.delete(id));
3401
3435
  pending = { fingerprint, runtimePromise };
3402
3436
  blueprintCreations.set(id, pending);
3403
3437
  }
3404
3438
  const next = await pending.runtimePromise;
3405
3439
  return send(res, { ok: true, project: next.service.state.projects[id] });
3406
3440
  }
3407
- // 新建时选的团队:必须在目录里且引用的人才都在(否则种成员会悄悄退回默认团队)。
3408
3441
  const team = typeof body.payload?.team === 'string' ? body.payload.team.trim() : '';
3409
- if (team !== '') {
3410
- const chosen = listTeams(talentCatalog(diag)).find((entry) => entry.id === team);
3411
- if (chosen === undefined) return send(res, { error: { code: 'E_INVALID_ARGUMENT', message: `团队不存在:${team}` } }, 400);
3412
- if (chosen.broken) return send(res, { error: { code: 'E_INVALID_ARGUMENT', message: `团队「${chosen.name}」引用了不存在的人才,先修好再用` } }, 400);
3413
- }
3414
3442
  const id = ids.project();
3415
- const next = await activateProject(id, name, goal, workspacePath, team);
3416
- diag?.append({ ev: 'project.create', id, team: team || null });
3443
+ const next = await activateProject(id, { ...input, teamPreset: teamPresetFor(config, diag, team) });
3417
3444
  return send(res, { ok: true, project: next.service.state.projects[id] ?? { id, name } });
3418
3445
  }
3419
3446
  if (body.type === 'project.blueprint.start' && runtime.service.state.projects?.[runtime.id]?.blueprint && !blueprintGuardReady) {
@@ -3427,7 +3454,7 @@ export function apply(ctx, config = {}) {
3427
3454
  const record = booted.registry.list().find((project) => project.id === target);
3428
3455
  // 透传 workspacePath:否则账本里的 project/created 会把工作目录写成空,
3429
3456
  // 之后该项目的成员激活永远 E_WORKSPACE_REQUIRED。
3430
- const next = await activateProject(target, record?.name, record?.goal, record?.workspacePath);
3457
+ const next = await activateProject(target, record);
3431
3458
  return send(res, { ok: true, project: next.service.state.projects[target] ?? record });
3432
3459
  }
3433
3460
  if (body.type === 'member.activate') {
@@ -3575,7 +3602,7 @@ export function apply(ctx, config = {}) {
3575
3602
  const fallback = booted.registry.list().find((project) => project.id === fallbackId);
3576
3603
  if (fallback !== undefined && fallback.id !== runtime.id) {
3577
3604
  try {
3578
- await activateProject(fallback.id, fallback.name, fallback.goal, fallback.workspacePath);
3605
+ await activateProject(fallback.id, fallback);
3579
3606
  diag.append({ ev: 'project.archive.reactivated', from: runtime.id, to: fallback.id });
3580
3607
  } catch (error) {
3581
3608
  diag.append({ ev: 'project.archive.reactivate.fail', from: runtime.id, to: fallback.id, message: error?.message ?? String(error) });
@@ -3628,9 +3655,10 @@ export function apply(ctx, config = {}) {
3628
3655
  try { teamDiscipline.dispose(); } catch { /* already disposed */ }
3629
3656
  try { deferredWakes.dispose(); } catch { /* already disposed */ }
3630
3657
  hostSessionGate.dispose();
3631
- // 在途的 boot 也算本组合的资源:等它落定(落定时见 disposed 会自行关账本),
3632
- // 否则下一组合抢在关锁之前打开同一账本。
3633
- const cleanup = [ready.then(() => undefined, () => undefined)];
3658
+ // 先收完已确认的项目创建,再关闭它们可能刚打开的账本。
3659
+ const closeRuntimes = Promise.allSettled([ready, ...projectActivations]).then(() =>
3660
+ Promise.allSettled([...(booted?.runtimes?.values() ?? [])].map(async (runtime) => runtime.close())));
3661
+ const cleanup = [closeRuntimes, Promise.resolve().then(disposeSessionCommand)];
3634
3662
  for (const client of sseClients) {
3635
3663
  try { client.res.end(); } catch { /* socket already gone */ }
3636
3664
  }
@@ -3659,13 +3687,9 @@ export function apply(ctx, config = {}) {
3659
3687
  offRequestError();
3660
3688
  offSessionEvent();
3661
3689
  offAgentCreated();
3690
+ offSubagentEnd();
3662
3691
  disposeTool();
3663
3692
  dispose();
3664
- for (const runtime of booted?.runtimes?.values() ?? []) {
3665
- cleanup.push(Promise.resolve().then(async () => {
3666
- try { await runtime.close(); } catch { /* ledger already closed */ }
3667
- }));
3668
- }
3669
3693
  return Promise.allSettled(cleanup).then(() => undefined);
3670
3694
  };
3671
3695
  }, 'ai-team: workbench routes');
package/lib/host/pmo.js CHANGED
@@ -299,7 +299,7 @@ export function staffingReview(state, events, { now, intervalMs, capacity, capac
299
299
  if (task.status === 'in_progress') group.inProgress += 1;
300
300
  }
301
301
  return {
302
- since, now, capacity, capacitySource, activeMemberTurns,
302
+ since, now, capacity, capacitySource, capacityScope: 'agent-tree', activeMemberTurns,
303
303
  claimable: waitingSummary(claimableTasks(state, open), now),
304
304
  pendingAcceptance: waitingSummary(waitingReview, now),
305
305
  pendingAcceptanceWithoutReviewer: { ...waitingSummary(missingReviewers, now), taskIds: missingReviewers.map(({ id }) => id) },
@@ -369,7 +369,7 @@ export function planStaffingAdvice(state, { now, inTurn, capacity = HOST_SUBAGEN
369
369
  const reasons = [...entry.reasons];
370
370
  const who = entry.role === 'developer' ? '开发' : '验收';
371
371
  if (entry.action === 'recover') return { ...entry, reasons, title: `建议恢复停摆的${who}:${reasons.join(';')}` };
372
- if (headcount + entry.count > capacity) reasons.push(`团队现有 ${headcount} 名 AI 成员,宿主同时在跑上限 ${capacity},加人后超出的部分会排队,提速有限`);
372
+ if (headcount + entry.count > capacity) reasons.push(`团队现有 ${headcount} 名 AI 成员,按这棵代理树的 ${capacity} 个并发位估算,同时跑满时会排队`);
373
373
  return { ...entry, reasons, title: `建议加 ${entry.count} 名${who}:${reasons.join(';')}` };
374
374
  });
375
375
  }
@@ -26,7 +26,7 @@ export class ProjectRuntime {
26
26
  this.service = service;
27
27
  }
28
28
 
29
- static async open({ rootDir, projectId = DEFAULT_PROJECT_ID, now = undefined, seed = true, projectName = '我的项目', projectGoal = '把事交给团队', workspacePath = '', diag = null, pmoMaxRounds = undefined, teamPreset = null, blueprint = null }) {
29
+ static async open({ rootDir, projectId = DEFAULT_PROJECT_ID, now = undefined, seed = true, projectName = '我的项目', projectGoal = '把事交给团队', workspacePath = '', diag = null, pmoMaxRounds = undefined, teamPreset = null, blueprint = null, pmoAuto = true }) {
30
30
  const dir = join(rootDir, 'projects', projectId);
31
31
  mkdirSync(dir, { recursive: true });
32
32
  const ledger = openLedger({
@@ -71,27 +71,32 @@ export class ProjectRuntime {
71
71
  });
72
72
 
73
73
  if (seed) {
74
- const state = service.state;
75
- if (state.members?.[HUMAN_ID] === undefined) {
76
- await service.dispatch({
77
- type: 'member.add',
78
- actor: { kind: 'human', memberId: HUMAN_ID },
79
- projectId,
80
- payload: { id: HUMAN_ID, name: '你', kind: 'human', role: 'Human' },
81
- });
74
+ try {
75
+ const state = service.state;
76
+ if (state.members?.[HUMAN_ID] === undefined) {
77
+ await service.dispatch({
78
+ type: 'member.add',
79
+ actor: { kind: 'human', memberId: HUMAN_ID },
80
+ projectId,
81
+ payload: { id: HUMAN_ID, name: '你', kind: 'human', role: 'Human' },
82
+ });
83
+ }
84
+ if (state.projects?.[projectId] === undefined) {
85
+ await service.dispatch({
86
+ type: 'project.create',
87
+ actor: { kind: 'human', memberId: HUMAN_ID },
88
+ projectId,
89
+ // 播种是内部路径:允许先建一个「待设定目录」的默认项目,用户在首次使用
90
+ // 引导里选定目录后再 project.workspace.update。
91
+ payload: { id: projectId, name: projectName, goal: projectGoal, workspacePath, seed: true, blueprint, pmoAuto },
92
+ });
93
+ }
94
+ await seedDefaultRoster(service, projectId, { humanId: HUMAN_ID, ...(teamPreset ? { preset: teamPreset } : {}) });
95
+ await service.backfillHumanMentions(state.projects?.[projectId]?.workspacePath ?? '');
96
+ } catch (error) {
97
+ runtime.close();
98
+ throw error;
82
99
  }
83
- if (state.projects?.[projectId] === undefined) {
84
- await service.dispatch({
85
- type: 'project.create',
86
- actor: { kind: 'human', memberId: HUMAN_ID },
87
- projectId,
88
- // 播种是内部路径:允许先建一个「待设定目录」的默认项目,用户在首次使用
89
- // 引导里选定目录后再 project.workspace.update。
90
- payload: { id: projectId, name: projectName, goal: projectGoal, workspacePath, seed: true, blueprint },
91
- });
92
- }
93
- await seedDefaultRoster(service, projectId, { humanId: HUMAN_ID, ...(teamPreset ? { preset: teamPreset } : {}) });
94
- await service.backfillHumanMentions(state.projects?.[projectId]?.workspacePath ?? '');
95
100
  }
96
101
  return runtime;
97
102
  }
@@ -1,4 +1,4 @@
1
- import { checkWorkspacePath } from './workspace-path.js';
1
+ import { requireWorkspaceDirectory } from './workspace-path.js';
2
2
  import { existsSync, mkdirSync, readFileSync, realpathSync, statSync, writeFileSync } from 'node:fs';
3
3
  import pathDefault from 'node:path';
4
4
  import { ERRORS, fail } from '../domain/errors.js';
@@ -674,21 +674,10 @@ export class TeamService {
674
674
  // 例外只有内部播种(payload.seed):它先建出「待设定目录」的默认项目,
675
675
  // 由首次使用引导补上目录,否则 boot 自己就会被这条校验挡住。
676
676
  const rawWorkspace = typeof payload.workspacePath === 'string' ? payload.workspacePath.trim() : '';
677
- if (rawWorkspace !== '') {
678
- const shape = checkWorkspacePath(rawWorkspace);
679
- if (shape.ok !== true) fail(ERRORS.INVALID_ARGUMENT, shape.message, { suggestion: shape.suggestion ?? null });
680
- }
681
677
  if (rawWorkspace === '' && payload.seed !== true) {
682
678
  fail(ERRORS.INVALID_ARGUMENT, '工作目录是必填项:请选择一个已存在的目录作为项目工作区');
683
679
  }
684
- if (rawWorkspace !== '') {
685
- let stat = null;
686
- try { stat = statSync(rawWorkspace); } catch { stat = null; }
687
- if (stat === null) fail(ERRORS.INVALID_ARGUMENT, `工作目录不存在:${rawWorkspace};请先创建该目录,或选择已存在的目录`);
688
- if (typeof stat.isDirectory === 'function' && stat.isDirectory() !== true) {
689
- fail(ERRORS.INVALID_ARGUMENT, `工作目录不是目录:${rawWorkspace}`);
690
- }
691
- }
680
+ if (rawWorkspace !== '') requireWorkspaceDirectory(rawWorkspace);
692
681
  const ownerMemberId = payload.ownerId ?? command.actor.memberId ?? this.humanId();
693
682
  const project = {
694
683
  id,
@@ -743,22 +732,7 @@ export class TeamService {
743
732
  if (typeof payload.workspacePath !== 'string' || payload.workspacePath.trim() === '') {
744
733
  fail(ERRORS.INVALID_ARGUMENT, 'workspacePath is required');
745
734
  }
746
- const workspacePath = payload.workspacePath.trim();
747
- // 平台形态先判:WSL/Linux 宿主上 `D:\works\x` 只是带反斜杠的相对文件名,
748
- // 直接做 statSync 只会得到「不存在」,完全指不出该怎么改。
749
- const shape = checkWorkspacePath(workspacePath);
750
- if (shape.ok !== true) fail(ERRORS.INVALID_ARGUMENT, shape.message, { suggestion: shape.suggestion ?? null });
751
- // P5b:目录必须真实存在且是目录——配置不存在的目录会让成员会话 cwd
752
- // 无效、回合直接失败(用户实证:working-directory: directory does not exist)。
753
- let stat = null;
754
- try {
755
- stat = statSync(workspacePath);
756
- } catch {
757
- fail(ERRORS.INVALID_ARGUMENT, `工作目录不存在:${workspacePath};请先创建该目录,或选择已存在的目录`);
758
- }
759
- if (stat !== null && typeof stat.isDirectory === 'function' && stat.isDirectory() !== true) {
760
- fail(ERRORS.INVALID_ARGUMENT, `工作目录不是目录:${workspacePath}`);
761
- }
735
+ const workspacePath = requireWorkspaceDirectory(payload.workspacePath.trim());
762
736
  await this.append(command, 'project/workspace-changed', {
763
737
  projectId,
764
738
  workspacePath,
@@ -0,0 +1,85 @@
1
+ import { realpathSync } from 'node:fs';
2
+ import { isAbsolute } from 'node:path';
3
+ import { DomainError, ERRORS, fail } from '../domain/errors.js';
4
+ import { ids } from '../domain/ids.js';
5
+ import { requireWorkspaceDirectory } from './workspace-path.js';
6
+
7
+ const HELP = '用 /ai-team 建队 目标 生成草稿。可在目标前加 --team 预设ID。按草稿中的命令确认或取消。';
8
+
9
+ function sessionWorkspace(session) {
10
+ const path = session?.header?.cwd;
11
+ if (typeof session?.id !== 'string' || typeof path !== 'string' || !isAbsolute(path)) {
12
+ fail(ERRORS.INVALID_ARGUMENT, '请先在项目所在工作区打开一个会话,再运行建队命令。');
13
+ }
14
+ return realpathSync(requireWorkspaceDirectory(path));
15
+ }
16
+
17
+ const presetSignature = (preset) => JSON.stringify([preset.id, preset.source, preset.dir, preset.team]);
18
+
19
+ /** 只注册用户显式调用的会话命令。草稿跟随当前 Session 实例,试跑和派发仍由项目自行启动。 */
20
+ export function sessionTeamCommand({ prepare, create, diag }) {
21
+ const drafts = new WeakMap();
22
+ return {
23
+ name: 'ai-team',
24
+ description: '在会话里预览、确认或取消文渊阁建队草稿',
25
+ input: { hint: '建队 [--team 预设ID] 目标 / 确认 草稿ID / 取消 草稿ID' },
26
+ async handler({ agent, rawInput, signal }) {
27
+ const session = agent?.session;
28
+ const [, action, argument = ''] = /^(\S+)(?:\s+([\s\S]*))?$/.exec(rawInput.trim()) ?? [];
29
+ if (signal?.aborted) return { kind: 'error', text: '这次命令已取消。' };
30
+ try {
31
+ if (action === undefined || action === '帮助') return { kind: 'success', text: HELP };
32
+ if (action !== '建队' && action !== '确认' && action !== '取消') return { kind: 'error', text: HELP };
33
+ const workspacePath = sessionWorkspace(session);
34
+ const existing = drafts.get(session);
35
+ if (action === '建队') {
36
+ if (existing?.pending) return { kind: 'error', text: '上一份草稿正在创建项目,请等它完成。' };
37
+ const selected = /^--team\s+(\S+)\s+([\s\S]+)$/.exec(argument);
38
+ const goal = (selected?.[2] ?? argument).trim();
39
+ if (goal === '' || (!selected && argument.startsWith('--team'))) return { kind: 'error', text: HELP };
40
+ const input = { name: goal.split(/\r?\n/, 1)[0], goal, workspacePath, team: selected?.[1] ?? '' };
41
+ const proposed = prepare(input);
42
+ const id = ids.project();
43
+ drafts.set(session, { id, input, signature: presetSignature(proposed.teamPreset), pending: null, result: null });
44
+ diag.append({ ev: 'session.team.previewed', projectId: id, preset: proposed.teamPreset.id, members: proposed.teamPreset.team.members.length });
45
+ return { kind: 'success', text: [
46
+ `建队草稿 ${input.name}`,
47
+ `目标 ${goal}`,
48
+ `工作目录 ${workspacePath}`,
49
+ `预设 ${proposed.teamPreset.team.name}(${proposed.teamPreset.id})`,
50
+ ...proposed.teamPreset.team.members.map((member) => `- ${member.name} · ${member.role}`),
51
+ '确认后创建项目,PMO 自动为关闭状态。',
52
+ `确认用 /ai-team 确认 ${id}`,
53
+ `取消用 /ai-team 取消 ${id}`,
54
+ ].join('\n') };
55
+ }
56
+ if (!existing || argument.trim() !== existing.id || workspacePath !== existing.input.workspacePath) {
57
+ return { kind: 'error', text: '当前会话和工作区没有这份草稿。请在这里重新生成。' };
58
+ }
59
+ if (action === '取消') {
60
+ if (existing.pending || existing.result) return { kind: 'error', text: '这份草稿已经确认。' };
61
+ drafts.delete(session);
62
+ diag.append({ ev: 'session.team.cancelled', projectId: existing.id });
63
+ return { kind: 'success', text: '已取消建队草稿。' };
64
+ }
65
+ if (existing.result) return existing.result;
66
+ if (existing.pending) return await existing.pending;
67
+ const approved = prepare(existing.input);
68
+ if (presetSignature(approved.teamPreset) !== existing.signature) {
69
+ drafts.delete(session);
70
+ return { kind: 'error', text: '团队预设已更新,请重新生成草稿后再确认。' };
71
+ }
72
+ existing.pending = create(existing.id, approved).then((project) => {
73
+ const result = { kind: 'success', text: `已创建「${project.name}」(${project.id})。可在文渊阁查看团队,准备好后开启 PMO 自动。` };
74
+ existing.result = result;
75
+ diag.append({ ev: 'session.team.confirmed', projectId: project.id });
76
+ return result;
77
+ }).finally(() => { existing.pending = null; });
78
+ return await existing.pending;
79
+ } catch (error) {
80
+ diag.append({ ev: 'session.team.fail', code: error?.code ?? 'E_RUNTIME', message: error?.message ?? String(error) });
81
+ return { kind: 'error', text: error instanceof DomainError ? error.message : '文渊阁暂未能完成建队。可在相同会话中重试。' };
82
+ }
83
+ },
84
+ };
85
+ }
@@ -5,10 +5,11 @@
5
5
  * ——Windows 形态。POSIX 上这只是一串**带反斜杠的文件名**(相对路径),既不是那个盘,
6
6
  * 也不会给出有用的报错;成员会话随后在错误目录里干活。
7
7
  *
8
- * 这里只判断「路径形态与宿主平台是否匹配」,存在性仍由调用方的 statSync 负责。
8
+ * 路径形态和存在性分别检查,以便在对话或表单里保留准确错误。
9
9
  */
10
10
 
11
- import { readFileSync } from 'node:fs';
11
+ import { readFileSync, statSync } from 'node:fs';
12
+ import { ERRORS, fail } from '../domain/errors.js';
12
13
 
13
14
  const WINDOWS_DRIVE = /^[A-Za-z]:[\\/]/;
14
15
  const WINDOWS_DRIVE_BARE = /^[A-Za-z]:$/;
@@ -85,6 +86,20 @@ export function checkWorkspacePath(raw, options = {}) {
85
86
  return { ok: true };
86
87
  }
87
88
 
89
+ /** 校验项目或会话已选定的目录,不补默认目录也不创建目录。 */
90
+ export function requireWorkspaceDirectory(workspacePath, status = 409) {
91
+ const shape = checkWorkspacePath(workspacePath);
92
+ if (!shape.ok) fail(ERRORS.INVALID_ARGUMENT, shape.message, { status, details: { suggestion: shape.suggestion ?? null } });
93
+ let stat;
94
+ try {
95
+ stat = statSync(workspacePath);
96
+ } catch {
97
+ fail(ERRORS.INVALID_ARGUMENT, `工作目录不存在:${workspacePath};请先创建该目录,或选择已存在的目录`, { status });
98
+ }
99
+ if (!stat.isDirectory()) fail(ERRORS.INVALID_ARGUMENT, `工作目录不是目录:${workspacePath}`, { status });
100
+ return workspacePath;
101
+ }
102
+
88
103
  /** 目录输入框的示例路径(与宿主平台一致)。 */
89
104
  export function workspaceExample(platform = process.platform, options = {}) {
90
105
  const host = hostPlatform(platform, options.wsl);
@@ -8,10 +8,8 @@
8
8
  * 那棵树下;宿主在**该成员**回合结束、空闲后把它收掉(dsh-subagent `watchLocalSettlement`),之后的
9
9
  * 投递在新根下冷恢复。所以等该成员 `turn/end` + settleDelayMs 再投(r43:旧回合结束 5 秒后补投成功)。
10
10
  * 旧回合结束后仍被拒、退避用尽才放弃并记 `.fail`。
11
- * - `capacity`(团队超过宿主并发上限):宿主同时运行的子智能体有上限(`maxActiveSubagents`,默认 8),
12
- * 满了不排队而是直接拒绝(dsh-subagent activation.ts `ACTIVATION_LIMIT_REACHED`)。团队可以超过 8 人,
13
- * 多出来的排队:**任一**会话 `turn/end` 都可能腾出名额,按入队先后补投最早的一条;不设放弃上限
14
- * (排多久都等),只按退避定时器兜底重试。
11
+ * - `capacity`:DSH 按根代理树预留子智能体槽位,满了返回 `ACTIVATION_LIMIT_REACHED`。
12
+ * 一棵树释放槽位时,按入队顺序补投该树最早的计划。退避定时器兜底,容量拒绝次数不设上限。
15
13
  *
16
14
  * 同一成员只留最新一条计划——唤醒内容在投递时按当时状态生成,旧计划没有额外信息。最终投到记
17
15
  * `wake.<类>.recovered`(errors 级可见)。
@@ -39,7 +37,7 @@ export function createDeferredWakes({
39
37
  redeliver, diag, backoffMs = DEFERRED_BACKOFF_MS, settleDelayMs = DEFERRED_SETTLE_MS,
40
38
  setTimer = setTimeout, clearTimer = clearTimeout, now = () => Date.now(),
41
39
  }) {
42
- /** `${projectId}:${memberId}` → { key, kind, sessionId, projectId, memberId, plan, queuedAt, timer, armedBy } */
40
+ /** `${projectId}:${memberId}` → { key, kind, sessionId, root, projectId, memberId, plan, queuedAt, timer, armedBy } */
43
41
  const pending = new Map();
44
42
  /**
45
43
  * key → { kind, tries, attempts, ended, queuedAt }。queuedAt 是首次入队时间:补投又被拒时仍按它排队,不掉到队尾。
@@ -73,10 +71,10 @@ export function createDeferredWakes({
73
71
  return {
74
72
  /**
75
73
  * 暂存一条被宿主暂时拒绝的唤醒。retry=true 表示这是补投又被拒。
76
- * @param {{ kind: 'stale-tree'|'capacity', sessionId?: string|null, projectId: string, memberId: string, plan: any, retry?: boolean }} input
74
+ * @param {{ kind: 'stale-tree'|'capacity', sessionId?: string|null, root?: object|null, projectId: string, memberId: string, plan: any, retry?: boolean }} input
77
75
  * @returns {boolean} false:放弃(仅 stale-tree 退避用尽)、未知类或已卸载,调用方按普通失败处理
78
76
  */
79
- defer({ kind, sessionId = null, projectId, memberId, plan, retry = false }) {
77
+ defer({ kind, sessionId = null, root = null, projectId, memberId, plan, retry = false }) {
80
78
  if (disposed || !(kind in EVENT)) return false;
81
79
  const key = keyOf(projectId, memberId);
82
80
  const s = state.get(key) ?? { kind, tries: 0, attempts: 0, ended: false, queuedAt: now() };
@@ -94,17 +92,17 @@ export function createDeferredWakes({
94
92
  diag?.append?.({ ev: ev(kind, '.giveup.fail'), projectId, memberId, sessionId, attempts: s.attempts, tries: s.tries, reason: plan?.reason ?? null });
95
93
  return false;
96
94
  }
97
- if (previous !== undefined && previous.kind === kind) {
95
+ if (previous !== undefined && previous.kind === kind && previous.root === root) {
98
96
  // 还没投出去又来新计划:换成最新的;排队位置与定时器照旧。
99
97
  Object.assign(previous, { plan, sessionId: sessionId ?? previous.sessionId });
100
98
  return true;
101
99
  }
102
100
  if (previous !== undefined) clearTimer(previous.timer);
103
101
  const delayMs = backoffMs[Math.min(s.tries, backoffMs.length - 1)];
104
- const entry = { key, kind, sessionId, projectId, memberId, plan, queuedAt: s.queuedAt, timer: undefined, armedBy: null };
102
+ const entry = { key, kind, sessionId, root, projectId, memberId, plan, queuedAt: s.queuedAt, timer: undefined, armedBy: null };
105
103
  pending.set(key, entry);
106
104
  arm(entry, delayMs, 'timer');
107
- diag?.append?.({ ev: ev(kind), projectId, memberId, sessionId, tries: s.tries, attempts: s.attempts, delayMs, queued: [...pending.values()].filter((item) => item.kind === kind).length, reason: plan?.reason ?? null });
105
+ diag?.append?.({ ev: ev(kind), projectId, memberId, sessionId, tries: s.tries, attempts: s.attempts, delayMs, queued: [...pending.values()].filter((item) => item.kind === kind && item.root === root).length, reason: plan?.reason ?? null });
108
106
  return true;
109
107
  },
110
108
  /** 投递成功:曾被暂存过的成员记一行 recovered,并清掉计数。 */
@@ -116,9 +114,7 @@ export function createDeferredWakes({
116
114
  state.delete(key);
117
115
  },
118
116
  /**
119
- * `session/event` 观察者,只看 `turn/end`:
120
- * - stale-tree:该成员自己的回合结束 → 等宿主收尾后补投;此后再被拒才计入放弃次数。
121
- * - capacity:任一回合结束都可能腾出一个名额 → 补投排队最久、还没被叫的那一条。
117
+ * 旧树上的成员回合结束后等待宿主收尾,此后再被拒才计入放弃次数。
122
118
  */
123
119
  observe(session, event) {
124
120
  const sessionId = session?.id;
@@ -129,12 +125,16 @@ export function createDeferredWakes({
129
125
  if (s !== undefined) s.ended = true;
130
126
  arm(entry, settleDelayMs, 'turn-end');
131
127
  }
128
+ },
129
+ /** 宿主已为这棵树释放一个槽位。根代理不可确认时,由原有定时器兜底。 */
130
+ capacityReleased(root) {
131
+ if (disposed || !root) return;
132
132
  let oldest;
133
133
  for (const entry of pending.values()) {
134
- if (entry.kind !== 'capacity' || entry.armedBy === 'turn-end') continue;
134
+ if (entry.kind !== 'capacity' || entry.root !== root || entry.armedBy === 'slot-release') continue;
135
135
  if (oldest === undefined || entry.queuedAt < oldest.queuedAt) oldest = entry;
136
136
  }
137
- if (oldest !== undefined) arm(oldest, settleDelayMs, 'turn-end');
137
+ if (oldest !== undefined) arm(oldest, settleDelayMs, 'slot-release');
138
138
  },
139
139
  /** 测试与诊断:当前暂存的成员,按入队先后。 */
140
140
  pending: () => [...pending.values()].sort((a, b) => a.queuedAt - b.queuedAt).map(({ kind, projectId, memberId }) => ({ kind, projectId, memberId })),
@@ -48,6 +48,19 @@ export function capacityLimit(error) {
48
48
  return match === null ? null : Number(match[1]);
49
49
  }
50
50
 
51
+ /** DSH reserves activation slots per root Agent. A replacement root starts with no observed limit. */
52
+ export function observeTreeCapacity() {
53
+ const limits = new WeakMap();
54
+ return {
55
+ get: (root) => limits.get(root) ?? null,
56
+ record(root, error) {
57
+ if (root == null || typeof root !== 'object') return;
58
+ const limit = capacityLimit(error);
59
+ if (limit !== null) limits.set(root, limit);
60
+ },
61
+ };
62
+ }
63
+
51
64
  /**
52
65
  * 被宿主暂时拒绝、该延后重投的唤醒属于哪一类;不属于延后类返回 null。
53
66
  * @returns {'stale-tree'|'capacity'|null}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@suifei/dsh-ai-team",
3
- "version": "0.4.154",
3
+ "version": "0.4.155",
4
4
  "type": "module",
5
5
  "description": "文渊阁 (Wenyuan Pavilion) — AI Team mode for DeepSeek Harness: concurrent projects, owned tasks, threads, inbox and an append-only team ledger",
6
6
  "license": "MIT",