@suifei/dsh-ai-team 0.4.154 → 0.4.156

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,14 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.156 - 2026-12-03
4
+
5
+ - 在 DSH 会话查看当前工作区的项目编制,从人才库增员、修改岗位或指定接手人后离队。确认时重新核对成员、人才和未收口任务,交接成功后原成员进入人才池。感谢 @buger-gif 的会话调整与任务交接场景(#121、#116)。
6
+
7
+ ## 0.4.155 - 2026-12-03
8
+
9
+ - DSH 会话可用 `/ai-team 建队` 预览当前工作目录和团队预设,确认后创建项目。取消草稿和重复确认均有回归,创建后 PMO 自动初始关闭。感谢 @buger-gif 提供会话建队场景(#121)。
10
+ - 编制巡检和补位建议按各项目的根代理树跟踪并发上限。并发排队在本树释放槽位后补投,保留定时重试。感谢 @buger-gif 的容量与编制案例(#116)。
11
+
3
12
  ## 0.4.154 - 2026-12-03
4
13
 
5
14
  - 新建和编辑项目可用宿主的浏览式目录列表。选定后回填路径,提交表单时才保存或创建项目。感谢 @ljyzww 提供 Windows 复现与宿主契约(#100)。
package/README.md CHANGED
@@ -37,6 +37,8 @@
37
37
 
38
38
  ## 最近更新
39
39
 
40
+ - **从会话调整编制**(0.4.156)。可查看同一工作区的团队,从人才库增员、修改岗位或把原任务交给接手人后离队。变更经草稿确认。感谢 [@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)。
41
+ - **从会话建队与分树容量**(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
42
  - **目录浏览和验收补位**(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
43
  - **看板受阻、离队交接和只读巡检**(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
44
  - **派发预检和 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 +130,30 @@ const svg = HashAvatar.svg('墨渊', { gender: 'male', age: 'middle', race: 'asi
128
130
  - **在线人才库同步**:人才市场顶部「同步在线库」从官方在线人才库 [`@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
131
  - 成员在账本里记下来源人才与版本、职责;人才文件之后再改,不会悄悄改动已招成员的性格与职责。已有项目不受新团队影响。文件写坏时跳过它并在诊断日志记 `catalog.load.fail` / `catalog.team.fail`。
130
132
 
133
+ ### 从 DSH 会话建队
134
+
135
+ 在已有工作目录的 DSH 会话中输入以下命令。
136
+
137
+ ```text
138
+ /ai-team 建队 --team docs 整理接口文档
139
+ ```
140
+
141
+ 会话会显示工作目录、目标、团队预设与岗位。输入草稿末尾的 `/ai-team 确认 草稿ID` 创建项目,或用对应的取消命令丢弃草稿。省略 `--team` 时使用设置中的默认团队预设。草稿跟随当前会话,宿主重启后可以重新生成。
142
+
143
+ 新项目会出现在文渊阁,PMO 自动初始关闭。团队准备好后,可以在项目页开启 PMO 自动。
144
+
145
+ ### 从 DSH 会话调整编制
146
+
147
+ `/ai-team 编制` 显示当前工作区的项目与成员编号。同一工作区有多个项目时,先选项目,使用 `/ai-team 编制 项目ID` 查看成员。用 `/ai-team 人才 [关键词]` 查看人才编号。
148
+
149
+ ```text
150
+ /ai-team 增员 项目ID 人才ID
151
+ /ai-team 改岗位 项目ID 成员ID 新岗位
152
+ /ai-team 离队 项目ID 成员ID [接手人ID]
153
+ ```
154
+
155
+ 变更命令先显示草稿,用同一会话里的确认命令写入。有未收口任务时须指定项目内的接手人,插件交接原卡后再将成员移入人才池。草稿生成后若成员、人才或任务有变化,重新预览再确认。
156
+
131
157
  ### 按蓝图试跑
132
158
 
133
159
  在「新建项目 → 按蓝图试跑」填写业务、月目标、你保留的工作、每周可投入时间和手工耗时。插件比较候选的已知手工负担,把首发收窄到一个真实样本和一份待审草稿。预览里可以查看岗位提示词、验收清单和七天上线步骤。
@@ -142,7 +168,7 @@ const svg = HashAvatar.svg('墨渊', { gender: 'male', age: 'middle', race: 'asi
142
168
 
143
169
  在当前 DSH profile 的 `ai-team` 配置中设 `staffingReviewMinutes: 180` 和 `diagLevel: full` 后,启用 PMO 自动的运行中普通项目会随现有巡检周期采样,每个时间窗口记录一次。`staffingReviewMinutes: 0`(默认)关闭采样。诊断日志中的 `pmo.staffing.review` 包含岗位已分配队列、可认领与待验收队列、最长及平均等待,以及采样窗口内每位成员的提交、验收和退回。返工率按退回的本窗口提交除以本窗口提交数计算,零样本为空。
144
170
 
145
- 巡检还会记录没有合格验收人的任务 ID、插件观察到的在队成员运行回合数和容量来源。容量来源为 `default` 时使用默认估计,为 `host` 时来自宿主报告。PMO 会把长期无人可验收的任务带进现有补位建议。
171
+ 巡检还会记录没有合格验收人的任务 ID、插件观察到的在队成员运行回合数和容量来源。并发上限按当前项目的根代理树记录,来源为 `default` 时使用默认估计,为 `host` 时来自这棵树的宿主容量回执。宿主释放槽位后,插件优先补投本树排队最久的成员。PMO 会把长期无人可验收的任务带进现有补位建议。
146
172
 
147
173
  巡检复用现有派员建议和冷却规则,记录被暂缓的建议。人员动作仍由已有授权流程处理。试跑样本和调整建议可回到 [#116](https://github.com/suifei/dsh-ai-team/issues/116)。
148
174
 
@@ -391,7 +417,7 @@ round-19 DeepSeek + Zhipu 双 provider
391
417
  | 贡献者 | 贡献 | 带来的进展 |
392
418
  |---|---|---|
393
419
  | [@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) | 统一认领与离队的执行顺序,在唤醒前检查认领条件,巡检识别缺少合格验收人的任务并记录运行回合和容量来源 |
420
+ | [@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
421
  | [@Estelle00](https://github.com/Estelle00) | DSH 0.2.3 启动 503 的复现和桌面验证 [#122](https://github.com/suifei/dsh-ai-team/issues/122) | 接入新版会话鉴权接口,恢复工作台初始化 |
396
422
  | [@phm101299-ui](https://github.com/phm101299-ui) | PMO 冷恢复的复现、根因和桌面验证 [#112](https://github.com/suifei/dsh-ai-team/issues/112) | 让原 PMO 在宿主重启后带着模型路由继续工作,保留成员关系和任务 |
397
423
  | [@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,18 @@ 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';
25
+ import { createSessionRoster } from './lib/host/session-roster.js';
24
26
  import { migrateLegacyNamespace, resolveProfile } from './lib/ledger/namespace.js';
25
27
  import { ids } from './lib/domain/ids.js';
28
+ import { ERRORS, fail } from './lib/domain/errors.js';
26
29
  import { MemberRuntime, validatePermissionProfile } from './lib/runtime/member-runtime.js';
27
30
  import { ensureHostAgent } from './lib/runtime/host-agent.js';
28
31
  import { activationSpec } from './lib/runtime/activation-spec.js';
@@ -61,7 +64,7 @@ import { buildModelCatalog, buildModelEfforts } from './lib/host/model-catalog.j
61
64
  import { createTeamTool } from './lib/host/member-tools.js';
62
65
  import { canDeliverWake, describeTaskContext, describeWake, planWakes } from './lib/host/waker.js';
63
66
  import { describeCauseChain } from './lib/runtime/error-chain.js';
64
- import { capacityLimit, classifyWakeFailure, deferredWakeKind, isCapacityError, isMalformedTurnError } from './lib/runtime/wake-failure.js';
67
+ import { classifyWakeFailure, deferredWakeKind, isCapacityError, isMalformedTurnError, observeTreeCapacity } from './lib/runtime/wake-failure.js';
65
68
  import { createDeferredWakes } from './lib/runtime/deferred-wakes.js';
66
69
  import { registerShellGuard } from './lib/runtime/shell-guard.js';
67
70
  import { registerOneShotToolGuard, registerStopGuard } from './lib/runtime/stop-guard.js';
@@ -180,11 +183,27 @@ async function memberHostSkillReferences(names, ownedRoots, summaries) {
180
183
 
181
184
  /** 新项目用哪个团队:新建时选的优先,其次插件设置 `teamPreset`,最后内置默认团队。 */
182
185
  function teamPresetFor(config, diag, chosen = '') {
183
- const preset = resolveTeam(talentCatalog(diag), chosen || config?.teamPreset || DEFAULT_TEAM, { diag });
186
+ const catalog = talentCatalog(diag);
187
+ if (chosen !== '') {
188
+ const entry = listTeams(catalog).find((team) => team.id === chosen);
189
+ if (entry === undefined) fail(ERRORS.INVALID_ARGUMENT, `团队不存在:${chosen}`, { status: 400 });
190
+ if (entry.broken) fail(ERRORS.INVALID_ARGUMENT, `团队「${entry.name}」引用了不存在的人才,先修好再用`, { status: 400 });
191
+ }
192
+ const preset = resolveTeam(catalog, chosen || config?.teamPreset || DEFAULT_TEAM, { diag });
184
193
  diag?.append?.({ ev: 'catalog.team', name: preset.id, source: preset.source, dir: preset.dir, members: preset.team.members.length });
185
194
  return preset;
186
195
  }
187
196
 
197
+ function projectInput(payload) {
198
+ const name = typeof payload?.name === 'string' ? payload.name.trim() : '';
199
+ const goal = typeof payload?.goal === 'string' ? payload.goal.trim() : '';
200
+ const workspacePath = typeof payload?.workspacePath === 'string' ? payload.workspacePath.trim() : '';
201
+ if (name === '') fail(ERRORS.INVALID_ARGUMENT, 'project name is required', { status: 400 });
202
+ if (workspacePath === '') fail(ERRORS.INVALID_ARGUMENT, '工作目录是必填项:请选择一个已存在的目录', { status: 400 });
203
+ requireWorkspaceDirectory(workspacePath, 400);
204
+ return { name, goal, workspacePath };
205
+ }
206
+
188
207
  /**
189
208
  * 惰性 shell 服务代理:插件注入时机可能早于 shell 服务就绪,注册与 tick 都
190
209
  * 必须在调用时现取,避免「boot 时未就绪 → 整条技能链静默跳过」。
@@ -947,6 +966,16 @@ export function apply(ctx, config = {}) {
947
966
  await deliverWakePlans(runtime, [plan], { retry: true });
948
967
  },
949
968
  });
969
+ const offSubagentEnd = typeof ctx.on === 'function'
970
+ ? ctx.on('subagent/end', (info) => {
971
+ if (typeof info?.parentSessionId !== 'string') return;
972
+ try {
973
+ const parent = serviceOf(ctx, 'agents')?.get?.(info.parentSessionId);
974
+ const subagents = serviceOf(ctx, 'subagents');
975
+ if (parent) deferredWakes.capacityReleased(subagents?.rootOf?.(parent));
976
+ } catch { /* the durable creator may have exited; the queued retry retains its timer */ }
977
+ })
978
+ : () => {};
950
979
  // provider 探测状态去重:能力缺失/确认无 provider 只各记一次,避免每轮刷日志。
951
980
  let lastProviderState = '';
952
981
  // PMO tick 是 fire-and-forget:慢 tick(模型/IO)会被下一分钟的定时器再入,
@@ -978,12 +1007,8 @@ export function apply(ctx, config = {}) {
978
1007
  // 空闲必派的节流状态(按项目):上次叫的时间、局面签名、同一局面重复次数(planIdleStaffing)。
979
1008
  const pmoLastStaffing = new Map();
980
1009
  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
- };
1010
+ // DSH 的 ActivationPool 按根 Agent 分配,已观察的上限随当前项目树而变。
1011
+ const treeCapacity = observeTreeCapacity();
987
1012
  const pmoLastEscalate = new Map();
988
1013
  const pmoLastReview = new Map();
989
1014
  let pmoTimer = null;
@@ -1216,9 +1241,9 @@ export function apply(ctx, config = {}) {
1216
1241
  // - 超过宿主并发上限(默认 8):宿主不排队直接拒绝,团队多出来的人由插件排队。
1217
1242
  const deferMember = projectRuntime.service.state.members?.[plan.memberId];
1218
1243
  const deferKind = deferredWakeKind(error);
1219
- noteHostCapacity(error);
1244
+ treeCapacity.record(parentInfo.agent, error);
1220
1245
  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 })) {
1246
+ && deferredWakes.defer({ kind: deferKind, sessionId: deferMember?.sessionId ?? null, root: parentInfo.agent, projectId: projectRuntime.id, memberId: plan.memberId, plan, retry })) {
1222
1247
  continue;
1223
1248
  }
1224
1249
  const causeChain = describeCauseChain(error);
@@ -1486,6 +1511,7 @@ export function apply(ctx, config = {}) {
1486
1511
  const reviewDue = reviewWindow !== null && pmoStaffingReviewWindows.get(projectRuntime.id) !== reviewWindow;
1487
1512
  const suppressed = [];
1488
1513
  const inTurn = (id) => turnsInFlight.has(id);
1514
+ const observedHostCapacity = treeCapacity.get(hosts.get(projectRuntime.id)?.agent);
1489
1515
  const capacity = observedHostCapacity ?? HOST_SUBAGENT_LIMIT;
1490
1516
  const adviceList = planStaffingAdvice(staffingState, {
1491
1517
  now, inTurn, capacity,
@@ -2294,6 +2320,7 @@ export function apply(ctx, config = {}) {
2294
2320
  diag?.append({ ev: 'activate.reject', projectId: projectRuntime.id, memberId: member.id, code: 'E_RUNTIME_UNAVAILABLE', detail: 'no provider' });
2295
2321
  return { error: { code: 'E_RUNTIME_UNAVAILABLE', message: 'no subagent provider is registered' }, status: 503 };
2296
2322
  }
2323
+ let capacityRoot;
2297
2324
  try {
2298
2325
  const selection = serviceOf(ctx, 'agentDefaultModel')?.currentSelection?.();
2299
2326
  const activationMember = member.config?.provider && member.config?.model
@@ -2310,6 +2337,7 @@ export function apply(ctx, config = {}) {
2310
2337
  return { error: { code: 'E_RUNTIME_UNAVAILABLE', message: 'no member or default provider/model is configured' }, status: 503 };
2311
2338
  }
2312
2339
  const parentInfo = await ensureParent(projectRuntime);
2340
+ capacityRoot = parentInfo.agent;
2313
2341
  const runtime = new MemberRuntime({
2314
2342
  subagents,
2315
2343
  sessions,
@@ -2387,7 +2415,7 @@ export function apply(ctx, config = {}) {
2387
2415
  // 超过宿主并发上限:不是成员失败——记 failed 会让 waker 再也不叫它(团队超过 8 人时第 9 位
2388
2416
  // 首次激活就会被永久搁置)。保持原状态,唤醒路径会把它排进 deferredWakes 的 capacity 队列。
2389
2417
  if (isCapacityError(error)) {
2390
- noteHostCapacity(error);
2418
+ treeCapacity.record(capacityRoot, error);
2391
2419
  diag.append({ ev: 'member.activate.capacity', memberId: member.id, projectId: projectRuntime.id, message: error?.message ?? String(error) });
2392
2420
  } else if (currentStatus !== 'retired') {
2393
2421
  try {
@@ -2503,31 +2531,43 @@ export function apply(ctx, config = {}) {
2503
2531
  };
2504
2532
 
2505
2533
  const blueprintCreations = new Map();
2506
- async function activateProject(nextProjectId, projectName, projectGoal, workspacePath = '', team = '', blueprint = null) {
2534
+ const projectOperations = new Set();
2535
+ function trackProjectOperation(operation) {
2536
+ const settled = () => projectOperations.delete(operation);
2537
+ projectOperations.add(operation);
2538
+ operation.then(settled, settled);
2539
+ return operation;
2540
+ }
2541
+ function activateProject(projectId, input) {
2542
+ return trackProjectOperation(activateProjectRuntime(projectId, input));
2543
+ }
2544
+ async function activateProjectRuntime(nextProjectId, { name, goal, workspacePath = '', teamPreset = null, blueprint = null, pmoAuto = true }) {
2507
2545
  await ready;
2508
- if (booted === null) throw new Error('team ledger is unavailable');
2546
+ if (disposed || booted === null) throw new Error('team ledger is unavailable');
2509
2547
  let next = projectRuntime(nextProjectId);
2510
2548
  if (next === null) {
2511
2549
  next = await ProjectRuntime.open({
2512
2550
  rootDir: booted.dataDir,
2513
2551
  projectId: nextProjectId,
2514
- projectName,
2515
- projectGoal,
2552
+ projectName: name,
2553
+ projectGoal: goal,
2516
2554
  workspacePath,
2517
2555
  diag,
2518
2556
  pmoMaxRounds: config.pmoMaxRounds,
2519
- teamPreset: blueprint ? null : teamPresetFor(config, diag, team),
2557
+ teamPreset: blueprint ? null : teamPreset ?? teamPresetFor(config, diag),
2520
2558
  blueprint,
2559
+ pmoAuto,
2521
2560
  });
2522
2561
  // 账本和两个岗位先落地,重启时才不会把半写的蓝图项目播种成预设团队。
2523
2562
  try {
2524
- booted.registry.add({ id: nextProjectId, name: projectName, goal: projectGoal, workspacePath });
2563
+ booted.registry.add({ id: nextProjectId, name, goal, workspacePath });
2525
2564
  } catch (error) {
2526
- next.close();
2565
+ await next.close();
2527
2566
  throw error;
2528
2567
  }
2529
2568
  booted.runtimes.set(nextProjectId, next);
2530
- attachRuntime(next);
2569
+ if (!disposed) attachRuntime(next);
2570
+ diag.append({ ev: 'project.create', id: nextProjectId, team: teamPreset?.id ?? null });
2531
2571
  }
2532
2572
  booted.registry.setActive(nextProjectId);
2533
2573
  booted = {
@@ -2537,9 +2577,49 @@ export function apply(ctx, config = {}) {
2537
2577
  ledger: next.ledger,
2538
2578
  service: next.service,
2539
2579
  };
2540
- broadcast(undefined, next);
2580
+ if (!disposed) broadcast(undefined, next);
2541
2581
  return next;
2542
2582
  }
2583
+ async function disposeMemberActivation(runtime, memberId, reason) {
2584
+ const sessionId = runtime.service.state.members?.[memberId]?.sessionId;
2585
+ const activation = activations.get(sessionId);
2586
+ if (activation === undefined) return;
2587
+ activations.delete(sessionId);
2588
+ try { await activation.dispose?.(); } catch { /* already gone */ }
2589
+ diag.append({ ev: 'member.activation.disposed', memberId, sessionId, reason });
2590
+ }
2591
+
2592
+ const nativeTeamCommand = sessionTeamCommand({
2593
+ prepare: (input) => ({ ...projectInput(input), teamPreset: teamPresetFor(config, diag, input.team) }),
2594
+ create: async (id, input) => (await activateProject(id, { ...input, pmoAuto: false })).service.state.projects[id],
2595
+ prepareRoster: createSessionRoster({
2596
+ async runtimes() {
2597
+ await ready;
2598
+ if (disposed || booted === null) fail(ERRORS.INVALID_STATE, '文渊阁账本尚未就绪。');
2599
+ return booted.runtimes.values();
2600
+ },
2601
+ isAvailable: (runtime) => !disposed && projectRuntime(runtime.id) === runtime
2602
+ && !peopleProjectIsArchived(booted.registry.list().find(({ id }) => id === runtime.id), runtime),
2603
+ catalog: () => talentCatalog(diag),
2604
+ actor: { kind: 'human', memberId: HUMAN_ID },
2605
+ disposeMemberActivation,
2606
+ }),
2607
+ diag,
2608
+ });
2609
+ const registerSessionCommand = (scoped) => {
2610
+ const registry = serviceOf(scoped, 'commands');
2611
+ if (typeof registry?.register !== 'function') return () => {};
2612
+ const unregister = registry.register({
2613
+ ...nativeTeamCommand,
2614
+ handler: (input) => trackProjectOperation(nativeTeamCommand.handler(input)),
2615
+ });
2616
+ diag.append({ ev: 'session.team.command.registered' });
2617
+ return unregister;
2618
+ };
2619
+ const commandScope = typeof ctx.inject === 'function'
2620
+ ? ctx.inject(['commands'], (scoped) => scoped.effect(() => registerSessionCommand(scoped), 'ai-team: session command'))
2621
+ : null;
2622
+ const disposeSessionCommand = commandScope === null ? registerSessionCommand(ctx) : () => commandScope.dispose();
2543
2623
 
2544
2624
  const dispose = webServer.register({
2545
2625
  kind: 'prefix',
@@ -3352,28 +3432,9 @@ export function apply(ctx, config = {}) {
3352
3432
  return send(res, distilled);
3353
3433
  }
3354
3434
  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() : '';
3435
+ const input = projectInput(body.payload);
3436
+ const { name, goal, workspacePath } = input;
3358
3437
  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
3438
  const blueprint = preview || body.payload?.blueprint !== undefined ? buildTeamBlueprint({ ...body.payload?.blueprint, goal }) : null;
3378
3439
  if (blueprint) {
3379
3440
  const id = preview ? ids.project() : body.payload?.blueprintId;
@@ -3397,23 +3458,16 @@ export function apply(ctx, config = {}) {
3397
3458
  let pending = blueprintCreations.get(id);
3398
3459
  if (pending && pending.fingerprint !== fingerprint) return send(res, { error: { code: 'E_CONFLICT', message: '这个蓝图正在创建' } }, 409);
3399
3460
  if (!pending) {
3400
- const runtimePromise = activateProject(id, name, goal, workspacePath, '', blueprint).finally(() => blueprintCreations.delete(id));
3461
+ const runtimePromise = activateProject(id, { ...input, blueprint }).finally(() => blueprintCreations.delete(id));
3401
3462
  pending = { fingerprint, runtimePromise };
3402
3463
  blueprintCreations.set(id, pending);
3403
3464
  }
3404
3465
  const next = await pending.runtimePromise;
3405
3466
  return send(res, { ok: true, project: next.service.state.projects[id] });
3406
3467
  }
3407
- // 新建时选的团队:必须在目录里且引用的人才都在(否则种成员会悄悄退回默认团队)。
3408
3468
  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
3469
  const id = ids.project();
3415
- const next = await activateProject(id, name, goal, workspacePath, team);
3416
- diag?.append({ ev: 'project.create', id, team: team || null });
3470
+ const next = await activateProject(id, { ...input, teamPreset: teamPresetFor(config, diag, team) });
3417
3471
  return send(res, { ok: true, project: next.service.state.projects[id] ?? { id, name } });
3418
3472
  }
3419
3473
  if (body.type === 'project.blueprint.start' && runtime.service.state.projects?.[runtime.id]?.blueprint && !blueprintGuardReady) {
@@ -3427,7 +3481,7 @@ export function apply(ctx, config = {}) {
3427
3481
  const record = booted.registry.list().find((project) => project.id === target);
3428
3482
  // 透传 workspacePath:否则账本里的 project/created 会把工作目录写成空,
3429
3483
  // 之后该项目的成员激活永远 E_WORKSPACE_REQUIRED。
3430
- const next = await activateProject(target, record?.name, record?.goal, record?.workspacePath);
3484
+ const next = await activateProject(target, record);
3431
3485
  return send(res, { ok: true, project: next.service.state.projects[target] ?? record });
3432
3486
  }
3433
3487
  if (body.type === 'member.activate') {
@@ -3575,7 +3629,7 @@ export function apply(ctx, config = {}) {
3575
3629
  const fallback = booted.registry.list().find((project) => project.id === fallbackId);
3576
3630
  if (fallback !== undefined && fallback.id !== runtime.id) {
3577
3631
  try {
3578
- await activateProject(fallback.id, fallback.name, fallback.goal, fallback.workspacePath);
3632
+ await activateProject(fallback.id, fallback);
3579
3633
  diag.append({ ev: 'project.archive.reactivated', from: runtime.id, to: fallback.id });
3580
3634
  } catch (error) {
3581
3635
  diag.append({ ev: 'project.archive.reactivate.fail', from: runtime.id, to: fallback.id, message: error?.message ?? String(error) });
@@ -3586,17 +3640,7 @@ export function apply(ctx, config = {}) {
3586
3640
  // 退役/离队后必须释放常驻子代理:否则 activation 句柄只在 force
3587
3641
  // 重建或插件卸载时才回收,退役成员的会话会一直挂在进程里。
3588
3642
  if (body.type === 'member.retire' || body.type === 'member.leave') {
3589
- const retiredId = body.payload?.memberId;
3590
- const retired = runtime.service.state.members?.[retiredId];
3591
- const retiredSession = retired?.sessionId;
3592
- if (typeof retiredSession === 'string') {
3593
- const activation = activations.get(retiredSession);
3594
- if (activation !== undefined) {
3595
- activations.delete(retiredSession);
3596
- try { await activation.dispose?.(); } catch { /* already gone */ }
3597
- diag.append({ ev: 'member.activation.disposed', memberId: retiredId, sessionId: retiredSession, reason: body.type });
3598
- }
3599
- }
3643
+ await disposeMemberActivation(runtime, body.payload?.memberId, body.type);
3600
3644
  }
3601
3645
  send(res, { ok: true, ...result });
3602
3646
  // 唤醒只由账本事件路径规划(attachRuntime 的 onEvent):dispatch 的
@@ -3628,9 +3672,10 @@ export function apply(ctx, config = {}) {
3628
3672
  try { teamDiscipline.dispose(); } catch { /* already disposed */ }
3629
3673
  try { deferredWakes.dispose(); } catch { /* already disposed */ }
3630
3674
  hostSessionGate.dispose();
3631
- // 在途的 boot 也算本组合的资源:等它落定(落定时见 disposed 会自行关账本),
3632
- // 否则下一组合抢在关锁之前打开同一账本。
3633
- const cleanup = [ready.then(() => undefined, () => undefined)];
3675
+ // 先收完建队和会话编制操作,再关闭账本。
3676
+ const closeRuntimes = Promise.allSettled([ready, ...projectOperations]).then(() =>
3677
+ Promise.allSettled([...(booted?.runtimes?.values() ?? [])].map(async (runtime) => runtime.close())));
3678
+ const cleanup = [closeRuntimes, Promise.resolve().then(disposeSessionCommand)];
3634
3679
  for (const client of sseClients) {
3635
3680
  try { client.res.end(); } catch { /* socket already gone */ }
3636
3681
  }
@@ -3659,13 +3704,9 @@ export function apply(ctx, config = {}) {
3659
3704
  offRequestError();
3660
3705
  offSessionEvent();
3661
3706
  offAgentCreated();
3707
+ offSubagentEnd();
3662
3708
  disposeTool();
3663
3709
  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
3710
  return Promise.allSettled(cleanup).then(() => undefined);
3670
3711
  };
3671
3712
  }, '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';
@@ -434,7 +434,7 @@ export class TeamService {
434
434
  /**
435
435
  * Dispatch one command. The caller is an exact Team member (or Human) and
436
436
  * the ledger serializes commands per Project.
437
- * @param {{ type: string, payload?: any, actor: { kind: string, memberId?: string }, correlationId?: string, projectId?: string }} command
437
+ * @param {{ type: string, payload?: any, actor: { kind: string, memberId?: string }, correlationId?: string, projectId?: string, verifyDraft?: () => void }} command
438
438
  */
439
439
  async dispatch(command) {
440
440
  const payload = command.payload ?? {};
@@ -470,6 +470,7 @@ export class TeamService {
470
470
  const dispatchExclusive = (work) => this.runExclusive(() => {
471
471
  // A queued task mutation can outlive the actor's team membership.
472
472
  checkCommand();
473
+ command.verifyDraft?.();
473
474
  return work();
474
475
  });
475
476
  try {
@@ -481,19 +482,19 @@ export class TeamService {
481
482
  case 'project.blueprint.start':
482
483
  case 'project.blueprint.measure':
483
484
  case 'project.blueprint.expand': return await dispatchExclusive(() => this.advanceBlueprint(command, payload));
484
- case 'project.owner.update': return await this.changeProjectOwner(command, payload);
485
- case 'project.workspace.update': return await this.changeProjectWorkspace(command, payload);
485
+ case 'project.owner.update': return await dispatchExclusive(() => this.changeProjectOwner(command, payload));
486
+ case 'project.workspace.update': return await dispatchExclusive(() => this.changeProjectWorkspace(command, payload));
486
487
  case 'project.repair': return await dispatchExclusive(() => this.repairLedger(command));
487
488
  case 'project.pmo.update': return await dispatchExclusive(() => this.setProjectPmo(command, payload));
488
489
  case 'project.archive': return await dispatchExclusive(() => this.setProjectArchive(command, payload));
489
490
  case 'project.runState': return await dispatchExclusive(() => this.setProjectRunState(command, payload));
490
491
  case 'project.handoff': return await this.handoffProject(command, payload);
491
492
  case 'stream.post': return await this.postStream(command, payload);
492
- case 'member.add': return await this.addMember(command, payload);
493
+ case 'member.add': return await dispatchExclusive(() => this.addMember(command, payload));
493
494
  case 'member.bind': return await this.bindMemberSession(command, payload);
494
495
  case 'member.fail': return await this.failMember(command, payload);
495
496
  case 'member.retire': return await dispatchExclusive(() => this.retireMember(command, payload));
496
- case 'member.profile.update': return await this.updateMemberProfile(command, payload);
497
+ case 'member.profile.update': return await dispatchExclusive(() => this.updateMemberProfile(command, payload));
497
498
  case 'member.evolve': return await this.evolveMember(command, payload);
498
499
  case 'member.distill': return await this.distillMember(command, payload);
499
500
  case 'member.leave': return await dispatchExclusive(() => this.leaveMember(command, payload));
@@ -674,21 +675,10 @@ export class TeamService {
674
675
  // 例外只有内部播种(payload.seed):它先建出「待设定目录」的默认项目,
675
676
  // 由首次使用引导补上目录,否则 boot 自己就会被这条校验挡住。
676
677
  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
678
  if (rawWorkspace === '' && payload.seed !== true) {
682
679
  fail(ERRORS.INVALID_ARGUMENT, '工作目录是必填项:请选择一个已存在的目录作为项目工作区');
683
680
  }
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
- }
681
+ if (rawWorkspace !== '') requireWorkspaceDirectory(rawWorkspace);
692
682
  const ownerMemberId = payload.ownerId ?? command.actor.memberId ?? this.humanId();
693
683
  const project = {
694
684
  id,
@@ -743,22 +733,7 @@ export class TeamService {
743
733
  if (typeof payload.workspacePath !== 'string' || payload.workspacePath.trim() === '') {
744
734
  fail(ERRORS.INVALID_ARGUMENT, 'workspacePath is required');
745
735
  }
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
- }
736
+ const workspacePath = requireWorkspaceDirectory(payload.workspacePath.trim());
762
737
  await this.append(command, 'project/workspace-changed', {
763
738
  projectId,
764
739
  workspacePath,
@@ -1106,15 +1081,42 @@ export class TeamService {
1106
1081
  return { member: this.state.members[member.id] };
1107
1082
  }
1108
1083
 
1109
- async leaveMember(command, payload) {
1110
- if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may move a member to the talent pool');
1084
+ describeMemberDeparture(projectId, payload, { reviewed = false } = {}) {
1111
1085
  const member = this.state.members?.[payload.memberId];
1112
1086
  if (member === undefined || member.kind !== 'agent') fail(ERRORS.NOT_FOUND, `agent ${String(payload.memberId)} not found`);
1113
1087
  const unfinished = unfinishedTasksFor(this.state, member.id);
1088
+ let successor = null;
1089
+ if (payload.successorId !== undefined) {
1090
+ successor = this.state.members?.[payload.successorId];
1091
+ if (successor?.kind !== 'agent' || successor.id === member.id
1092
+ || ![MEMBER_STATUS.IDLE, MEMBER_STATUS.RUNNING].includes(successor.status)) {
1093
+ fail(ERRORS.INVALID_ARGUMENT, '接手人须是同项目内另一位可以工作的成员。');
1094
+ }
1095
+ }
1096
+ if (reviewed || successor !== null) {
1097
+ const project = this.state.projects?.[projectId];
1098
+ if (member.status === MEMBER_STATUS.RETIRED) fail(ERRORS.INVALID_STATE, '该成员已经离队。');
1099
+ if ((project?.ownerMemberId ?? project?.ownerId) === member.id) fail(ERRORS.INVALID_STATE, '请先变更项目负责人,再办理离队。');
1100
+ if (unfinished.length > 0 && successor === null) {
1101
+ fail(ERRORS.INVALID_ARGUMENT, '该成员还有未收口任务,请指定接手成员后重新生成草稿。');
1102
+ }
1103
+ }
1104
+ return { member, unfinished, successor };
1105
+ }
1106
+
1107
+ async leaveMember(command, payload) {
1108
+ if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may move a member to the talent pool');
1109
+ const { member, unfinished, successor } = this.describeMemberDeparture(command.projectId, payload, { reviewed: command.verifyDraft !== undefined });
1110
+ // With a successor, commit the existing task transfers first. A partial write can
1111
+ // leave the departing member active, but must never strand their unfinished cards.
1112
+ const transfer = successor === null ? null : await this.takeoverMember(command, {
1113
+ fromMemberId: member.id, toMemberId: successor.id, reason: payload.reason,
1114
+ });
1114
1115
  await this.append(command, 'member/left-team', { memberId: member.id, reason: payload.reason ?? '' });
1115
1116
  return {
1116
1117
  member: this.state.members[member.id],
1117
- unfinishedTasks: unfinished.map((task) => ({ id: task.id, number: task.number, title: task.title, status: task.status })),
1118
+ unfinishedTasks: (transfer === null ? unfinished : []).map((task) => ({ id: task.id, number: task.number, title: task.title, status: task.status })),
1119
+ ...(transfer === null ? {} : { transferredTasks: transfer.tasks }),
1118
1120
  };
1119
1121
  }
1120
1122
 
@@ -0,0 +1,141 @@
1
+ import { realpathSync } from 'node:fs';
2
+ import { isAbsolute } from 'node:path';
3
+ import { listTalents } from '../domain/catalog.js';
4
+ import { DomainError, ERRORS, fail } from '../domain/errors.js';
5
+ import { unfinishedTasksFor } from '../domain/member-profile.js';
6
+
7
+ const USAGE = {
8
+ 编制: '/ai-team 编制 [项目ID]',
9
+ 人才: '/ai-team 人才 [关键词]',
10
+ 增员: '/ai-team 增员 项目ID 人才ID',
11
+ 改岗位: '/ai-team 改岗位 项目ID 成员ID 新岗位',
12
+ 离队: '/ai-team 离队 项目ID 成员ID [接手人ID]',
13
+ };
14
+
15
+ export const rosterHelp = Object.values(USAGE).join('\n');
16
+ export const isRosterAction = (action) => Object.hasOwn(USAGE, action);
17
+
18
+ function workspaceProject(runtime, workspacePath) {
19
+ const project = runtime.service.state.projects?.[runtime.id];
20
+ if (!project || project.status === 'archived' || typeof project.workspacePath !== 'string' || !isAbsolute(project.workspacePath)) return null;
21
+ try {
22
+ return realpathSync(project.workspacePath) === workspacePath ? project : null;
23
+ } catch {
24
+ return null;
25
+ }
26
+ }
27
+
28
+ const memberLabel = (member) => `${member.name}(${member.id})`;
29
+
30
+ function describeRoster(runtime, project) {
31
+ const state = runtime.service.state;
32
+ const members = Object.values(state.members ?? {}).filter((member) => member.kind === 'agent');
33
+ return [
34
+ `「${project.name}」的编制(${project.id})`,
35
+ ...members.map((member) => {
36
+ const unfinished = unfinishedTasksFor(state, member.id).length;
37
+ const role = member.role ? ` · ${member.role}` : '';
38
+ const departed = member.status === 'retired' ? ' · 已离队' : '';
39
+ return `- ${memberLabel(member)}${role}${departed} · ${unfinished} 张未收口任务`;
40
+ }),
41
+ '使用 /ai-team 人才查看可选人才。',
42
+ ].join('\n');
43
+ }
44
+
45
+ function planChange(runtime, action, target, value, catalog) {
46
+ const reason = '会话编制草稿确认';
47
+ if (action === '增员') {
48
+ const talent = catalog().talents.get(target);
49
+ if (!talent) fail(ERRORS.NOT_FOUND, '人才库中找不到该人才。使用 /ai-team 人才 查看可选人才。');
50
+ return {
51
+ type: 'member.add',
52
+ payload: {
53
+ name: talent.name, role: talent.role, duty: talent.duty,
54
+ personality: talent.personality, skills: talent.skills, avatar: talent.avatar,
55
+ talent: talent.id, talentVersion: talent.version,
56
+ },
57
+ lines: [`增员 ${talent.name} · ${talent.role}(${talent.id})`],
58
+ };
59
+ }
60
+ if (action === '改岗位') {
61
+ const member = runtime.service.state.members?.[target];
62
+ if (member?.kind !== 'agent' || member.status === 'retired') fail(ERRORS.NOT_FOUND, '同一项目中找不到这位在队成员。');
63
+ if (member.role === value) fail(ERRORS.INVALID_ARGUMENT, '该成员已经是这个岗位。');
64
+ return {
65
+ type: 'member.profile.update', payload: { memberId: target, role: value, reason },
66
+ lines: [`岗位 ${memberLabel(member)} 从「${member.role || '未设置'}」改为「${value}」`],
67
+ };
68
+ }
69
+ const payload = { memberId: target, ...(value ? { successorId: value } : {}), reason };
70
+ const { member, successor, unfinished } = runtime.service.describeMemberDeparture(runtime.id, payload, { reviewed: true });
71
+ return {
72
+ type: 'member.leave', payload,
73
+ lines: [
74
+ `离队 ${memberLabel(member)}进入人才池`,
75
+ ...(successor === null ? [] : [`接手人 ${memberLabel(successor)}`]),
76
+ ...(unfinished.length === 0 ? ['该成员没有未收口任务。'] : unfinished.map((task) => `- #${task.number} ${task.title}(${task.status})`)),
77
+ ],
78
+ taskRevisions: unfinished.map(({ id, revision }) => [id, revision]),
79
+ };
80
+ }
81
+
82
+ export function createSessionRoster({ runtimes, isAvailable, catalog, actor, disposeMemberActivation }) {
83
+ return async function prepareRoster({ action, argument, workspacePath }) {
84
+ if (action === '人才') {
85
+ const query = argument.trim().toLowerCase();
86
+ const talents = listTalents(catalog()).filter((talent) => [talent.id, talent.name, talent.role].some((value) => value.toLowerCase().includes(query)));
87
+ return { text: talents.length === 0 ? '没有匹配的人才。' : talents.map((talent) => `- ${talent.id} · ${talent.name} · ${talent.role}`).join('\n') };
88
+ }
89
+ const [, projectId, target, value = ''] = /^(\S+)(?:\s+(\S+))?(?:\s+([\s\S]+))?$/.exec(argument.trim()) ?? [];
90
+ const wrongTarget = action === '编制' ? target !== undefined : target === undefined;
91
+ if (wrongTarget || (action === '增员' && value !== '') || (action === '改岗位' && value === '')
92
+ || (action === '离队' && /\s/.test(value))) {
93
+ fail(ERRORS.INVALID_ARGUMENT, `用 ${USAGE[action]}。`);
94
+ }
95
+ const options = [];
96
+ for (const runtime of await runtimes()) {
97
+ const project = isAvailable(runtime) ? workspaceProject(runtime, workspacePath) : null;
98
+ if (project !== null) options.push({ runtime, project });
99
+ }
100
+ if (projectId === undefined && options.length > 1) {
101
+ return { text: ['同一工作区有多个项目,请使用 /ai-team 编制 项目ID。', ...options.map(({ project }) => `- ${project.id} · ${project.name}`)].join('\n') };
102
+ }
103
+ const selection = projectId === undefined ? options[0] : options.find(({ project }) => project.id === projectId);
104
+ if (!selection) fail(ERRORS.NOT_FOUND, '当前会话的工作区找不到该项目。使用 /ai-team 编制 查看同一工作区的项目。');
105
+ const { runtime, project } = selection;
106
+ if (action === '编制') return { text: describeRoster(runtime, project) };
107
+
108
+ const change = planChange(runtime, action, target, value, catalog);
109
+ const command = { type: change.type, payload: change.payload, actor, projectId };
110
+ runtime.service.checkBlueprintCommand(command, change.payload);
111
+ const approved = JSON.stringify(change);
112
+ return {
113
+ projectId, action,
114
+ lines: [`编制草稿 ${project.name}(${projectId})`, ...change.lines],
115
+ async apply(draftId) {
116
+ const result = await runtime.service.dispatch({
117
+ ...command, correlationId: draftId,
118
+ verifyDraft() {
119
+ const currentProject = isAvailable(runtime) ? workspaceProject(runtime, workspacePath) : null;
120
+ if (!currentProject || currentProject.name !== project.name) {
121
+ fail(ERRORS.REVISION, '项目或工作目录已变化,请重新生成草稿。');
122
+ }
123
+ let current;
124
+ try {
125
+ current = planChange(runtime, action, target, value, catalog);
126
+ } catch (error) {
127
+ if (error instanceof DomainError) fail(ERRORS.REVISION, `${error.message} 请核对编制后重新生成草稿。`);
128
+ throw error;
129
+ }
130
+ if (JSON.stringify(current) !== approved) fail(ERRORS.REVISION, '成员、人才或任务已变化,请重新生成草稿。');
131
+ },
132
+ });
133
+ if (action === '离队') {
134
+ await disposeMemberActivation(runtime, target, command.type);
135
+ return `已将${memberLabel(result.member)}移入人才池,交接了 ${result.transferredTasks?.length ?? 0} 张原任务。`;
136
+ }
137
+ return action === '增员' ? `已添加${memberLabel(result.member)}。` : `已将${memberLabel(result.member)}的岗位更新为「${result.member.role}」。`;
138
+ },
139
+ };
140
+ };
141
+ }
@@ -0,0 +1,105 @@
1
+ import { realpathSync } from 'node:fs';
2
+ import { isAbsolute } from 'node:path';
3
+ import { DomainError, ERRORS, fail } from '../domain/errors.js';
4
+ import { ids, newId } from '../domain/ids.js';
5
+ import { isRosterAction, rosterHelp } from './session-roster.js';
6
+ import { requireWorkspaceDirectory } from './workspace-path.js';
7
+
8
+ const HELP = `用 /ai-team 建队 目标 生成草稿。可在目标前加 --team 预设ID。按草稿中的命令确认或取消。\n${rosterHelp}`;
9
+
10
+ function sessionWorkspace(session) {
11
+ const path = session?.header?.cwd;
12
+ if (typeof session?.id !== 'string' || typeof path !== 'string' || !isAbsolute(path)) {
13
+ fail(ERRORS.INVALID_ARGUMENT, '请先在项目所在工作区打开一个会话,再运行建队命令。');
14
+ }
15
+ return realpathSync(requireWorkspaceDirectory(path));
16
+ }
17
+
18
+ const presetSignature = (preset) => JSON.stringify([preset.id, preset.source, preset.dir, preset.team]);
19
+
20
+ /** 只有当前用户会话能确认它的草稿。建队和编制共用同一确认流程。 */
21
+ export function sessionTeamCommand({ prepare, create, prepareRoster, diag }) {
22
+ const drafts = new WeakMap();
23
+ const preview = (session, workspacePath, draft) => {
24
+ if (drafts.get(session)?.pending) return { kind: 'error', text: '上一份草稿正在执行,请等它完成。' };
25
+ const id = draft.id ?? newId('draft');
26
+ const projectId = draft.projectId ?? id;
27
+ drafts.set(session, { ...draft, id, projectId, workspacePath, pending: null, result: null });
28
+ diag.append({ ev: 'session.team.previewed', projectId, action: draft.action, ...draft.details });
29
+ return { kind: 'success', text: [...draft.lines, `确认用 /ai-team 确认 ${id}`, `取消用 /ai-team 取消 ${id}`].join('\n') };
30
+ };
31
+ return {
32
+ name: 'ai-team',
33
+ description: '在会话里建队和调整文渊阁编制',
34
+ input: { hint: '建队 / 编制 / 人才 / 增员 / 改岗位 / 离队 / 确认 / 取消' },
35
+ async handler({ agent, rawInput, signal }) {
36
+ const session = agent?.session;
37
+ const [, action, argument = ''] = /^(\S+)(?:\s+([\s\S]*))?$/.exec(rawInput.trim()) ?? [];
38
+ if (signal?.aborted) return { kind: 'error', text: '这次命令已取消。' };
39
+ try {
40
+ if (action === undefined || action === '帮助') return { kind: 'success', text: HELP };
41
+ if (action !== '建队' && action !== '确认' && action !== '取消' && !isRosterAction(action)) return { kind: 'error', text: HELP };
42
+ const workspacePath = sessionWorkspace(session);
43
+ const existing = drafts.get(session);
44
+ if (isRosterAction(action)) {
45
+ const draft = await prepareRoster({ action, argument, workspacePath });
46
+ if (signal?.aborted) return { kind: 'error', text: '这次命令已取消。' };
47
+ return draft.apply ? preview(session, workspacePath, draft) : { kind: 'success', text: draft.text };
48
+ }
49
+ if (action === '建队') {
50
+ const selected = /^--team\s+(\S+)\s+([\s\S]+)$/.exec(argument);
51
+ const goal = (selected?.[2] ?? argument).trim();
52
+ if (goal === '' || (!selected && argument.startsWith('--team'))) return { kind: 'error', text: HELP };
53
+ const input = { name: goal.split(/\r?\n/, 1)[0], goal, workspacePath, team: selected?.[1] ?? '' };
54
+ const proposed = prepare(input);
55
+ const id = ids.project();
56
+ const signature = presetSignature(proposed.teamPreset);
57
+ return preview(session, workspacePath, {
58
+ id, action,
59
+ details: { preset: proposed.teamPreset.id, members: proposed.teamPreset.team.members.length },
60
+ lines: [
61
+ `建队草稿 ${input.name}`,
62
+ `目标 ${goal}`,
63
+ `工作目录 ${workspacePath}`,
64
+ `预设 ${proposed.teamPreset.team.name}(${proposed.teamPreset.id})`,
65
+ ...proposed.teamPreset.team.members.map((member) => `- ${member.name} · ${member.role}`),
66
+ '确认后创建项目,PMO 自动为关闭状态。',
67
+ ],
68
+ async apply() {
69
+ const approved = prepare(input);
70
+ if (presetSignature(approved.teamPreset) !== signature) {
71
+ fail(ERRORS.REVISION, '团队预设已更新,请重新生成草稿后再确认。');
72
+ }
73
+ const project = await create(id, approved);
74
+ return `已创建「${project.name}」(${project.id})。可在文渊阁查看团队,准备好后开启 PMO 自动。`;
75
+ },
76
+ });
77
+ }
78
+ if (!existing || argument.trim() !== existing.id || workspacePath !== existing.workspacePath) {
79
+ return { kind: 'error', text: '当前会话和工作区没有这份草稿。请在这里重新生成。' };
80
+ }
81
+ if (action === '取消') {
82
+ if (existing.pending || existing.result) return { kind: 'error', text: '这份草稿已经确认。' };
83
+ drafts.delete(session);
84
+ diag.append({ ev: 'session.team.cancelled', projectId: existing.projectId, action: existing.action });
85
+ return { kind: 'success', text: existing.action === '建队' ? '已取消建队草稿。' : '已取消编制草稿。' };
86
+ }
87
+ if (existing.result) return existing.result;
88
+ if (existing.pending) return await existing.pending;
89
+ existing.pending = existing.apply(existing.id).then((text) => {
90
+ const result = { kind: 'success', text };
91
+ existing.result = result;
92
+ diag.append({ ev: 'session.team.confirmed', projectId: existing.projectId, action: existing.action });
93
+ return result;
94
+ }).catch((error) => {
95
+ if (error instanceof DomainError && error.code === ERRORS.REVISION) drafts.delete(session);
96
+ throw error;
97
+ }).finally(() => { existing.pending = null; });
98
+ return await existing.pending;
99
+ } catch (error) {
100
+ diag.append({ ev: 'session.team.fail', code: error?.code ?? 'E_RUNTIME', message: error?.message ?? String(error) });
101
+ return { kind: 'error', text: error instanceof DomainError ? error.message : '文渊阁暂未能完成操作。可在相同会话中重试。' };
102
+ }
103
+ },
104
+ };
105
+ }
@@ -1,94 +1,109 @@
1
- /**
2
- * 工作目录的**平台形态**校验。
3
- *
4
- * 实机事故:DSH web 在 WSL(Linux)里启动,用户在目录框里填了 `D:\works\localservice`
5
- * ——Windows 形态。POSIX 上这只是一串**带反斜杠的文件名**(相对路径),既不是那个盘,
6
- * 也不会给出有用的报错;成员会话随后在错误目录里干活。
7
- *
8
- * 这里只判断「路径形态与宿主平台是否匹配」,存在性仍由调用方的 statSync 负责。
9
- */
10
-
11
- import { readFileSync } from 'node:fs';
12
-
13
- const WINDOWS_DRIVE = /^[A-Za-z]:[\\/]/;
14
- const WINDOWS_DRIVE_BARE = /^[A-Za-z]:$/;
15
- const UNC = /^\\\\[^\\]/;
16
- const BACKSLASH = /\\/;
17
-
18
- /** 把 `D:\works\a` 这类 Windows 路径转换成 WSL 的 `/mnt/d/works/a`。 */
19
- export function windowsToWsl(raw) {
20
- const match = /^([A-Za-z]):[\\/]*(.*)$/.exec(String(raw ?? ''));
21
- if (match === null) return null;
22
- const drive = match[1].toLowerCase();
23
- const rest = match[2].replace(/\\/g, '/').replace(/\/+/g, '/').replace(/\/$/, '');
24
- return rest === '' ? `/mnt/${drive}` : `/mnt/${drive}/${rest}`;
25
- }
26
-
27
- /** 宿主是否运行在 WSL 里(`/proc/version` 含 microsoft)。读不到就按普通 Linux 处理。 */
28
- export function isWsl() {
29
- if (process.platform !== 'linux') return false;
30
- try {
31
- return /microsoft/i.test(readFileSync('/proc/version', 'utf8'));
32
- } catch {
33
- return false;
34
- }
35
- }
36
-
37
- /** 'win32' | 'wsl' | 'posix' */
38
- export function hostPlatform(platform = process.platform, wsl = undefined) {
39
- if (platform === 'win32') return 'win32';
40
- if (platform === 'linux' && (wsl ?? isWsl()) === true) return 'wsl';
41
- return 'posix';
42
- }
43
-
44
- /**
45
- * 校验路径形态是否与宿主平台兼容。
46
- * @returns {{ ok: true } | { ok: false, code: string, message: string, suggestion?: string }}
47
- */
48
- export function checkWorkspacePath(raw, options = {}) {
49
- const value = typeof raw === 'string' ? raw.trim() : '';
50
- if (value === '') return { ok: false, code: 'E_EMPTY', message: '工作目录不能为空' };
51
- const platform = options.platform ?? process.platform;
52
- const host = hostPlatform(platform, options.wsl);
53
- if (host === 'win32') {
54
- // Windows 上 POSIX 绝对路径(`/mnt/d/x`)不是有效盘符路径;Node 会把它解释成
55
- // 当前盘根目录,容易落进意料之外的位置。直接给出明确提示。
56
- if (value.startsWith('/') && !WINDOWS_DRIVE.test(value)) {
57
- return {
58
- ok: false,
59
- code: 'E_PLATFORM_PATH',
60
- message: `工作目录「${value}」是 POSIX 路径,而当前宿主是 Windows;请改用盘符路径,例如 D:/works/my-project`,
61
- };
62
- }
63
- return { ok: true };
64
- }
65
- // POSIX(含 WSL):Windows 形态一律拒绝,并给出可用的替代写法。
66
- if (UNC.test(value)) {
67
- return {
68
- ok: false,
69
- code: 'E_PLATFORM_PATH',
70
- message: `工作目录「${value}」是 Windows UNC 路径(\\\\wsl.localhost\\…),Linux 宿主无法使用;请改用挂载点路径,例如 /home/<user>/works`,
71
- };
72
- }
73
- if (WINDOWS_DRIVE.test(value) || WINDOWS_DRIVE_BARE.test(value) || (BACKSLASH.test(value) && !value.startsWith('/'))) {
74
- const suggestion = windowsToWsl(value);
75
- const hint = host === 'wsl' && suggestion !== null
76
- ? `请改用 WSL 内的挂载路径:${suggestion}`
77
- : '请改用 POSIX 路径,例如 /home/<user>/works/my-project';
78
- return {
79
- ok: false,
80
- code: 'E_PLATFORM_PATH',
81
- message: `工作目录「${value}」是 Windows 路径,而当前宿主是 Linux;${hint}`,
82
- ...(suggestion === null ? {} : { suggestion }),
83
- };
84
- }
85
- return { ok: true };
86
- }
87
-
88
- /** 目录输入框的示例路径(与宿主平台一致)。 */
89
- export function workspaceExample(platform = process.platform, options = {}) {
90
- const host = hostPlatform(platform, options.wsl);
91
- if (host === 'win32') return 'D:/works/my-project';
92
- if (host === 'wsl') return '/mnt/d/works/my-project';
93
- return '/home/user/works/my-project';
94
- }
1
+ /**
2
+ * 工作目录的**平台形态**校验。
3
+ *
4
+ * 实机事故:DSH web 在 WSL(Linux)里启动,用户在目录框里填了 `D:\works\localservice`
5
+ * ——Windows 形态。POSIX 上这只是一串**带反斜杠的文件名**(相对路径),既不是那个盘,
6
+ * 也不会给出有用的报错;成员会话随后在错误目录里干活。
7
+ *
8
+ * 路径形态和存在性分别检查,以便在对话或表单里保留准确错误。
9
+ */
10
+
11
+ import { readFileSync, statSync } from 'node:fs';
12
+ import { ERRORS, fail } from '../domain/errors.js';
13
+
14
+ const WINDOWS_DRIVE = /^[A-Za-z]:[\\/]/;
15
+ const WINDOWS_DRIVE_BARE = /^[A-Za-z]:$/;
16
+ const UNC = /^\\\\[^\\]/;
17
+ const BACKSLASH = /\\/;
18
+
19
+ /** 把 `D:\works\a` 这类 Windows 路径转换成 WSL 的 `/mnt/d/works/a`。 */
20
+ export function windowsToWsl(raw) {
21
+ const match = /^([A-Za-z]):[\\/]*(.*)$/.exec(String(raw ?? ''));
22
+ if (match === null) return null;
23
+ const drive = match[1].toLowerCase();
24
+ const rest = match[2].replace(/\\/g, '/').replace(/\/+/g, '/').replace(/\/$/, '');
25
+ return rest === '' ? `/mnt/${drive}` : `/mnt/${drive}/${rest}`;
26
+ }
27
+
28
+ /** 宿主是否运行在 WSL 里(`/proc/version` 含 microsoft)。读不到就按普通 Linux 处理。 */
29
+ export function isWsl() {
30
+ if (process.platform !== 'linux') return false;
31
+ try {
32
+ return /microsoft/i.test(readFileSync('/proc/version', 'utf8'));
33
+ } catch {
34
+ return false;
35
+ }
36
+ }
37
+
38
+ /** 'win32' | 'wsl' | 'posix' */
39
+ export function hostPlatform(platform = process.platform, wsl = undefined) {
40
+ if (platform === 'win32') return 'win32';
41
+ if (platform === 'linux' && (wsl ?? isWsl()) === true) return 'wsl';
42
+ return 'posix';
43
+ }
44
+
45
+ /**
46
+ * 校验路径形态是否与宿主平台兼容。
47
+ * @returns {{ ok: true } | { ok: false, code: string, message: string, suggestion?: string }}
48
+ */
49
+ export function checkWorkspacePath(raw, options = {}) {
50
+ const value = typeof raw === 'string' ? raw.trim() : '';
51
+ if (value === '') return { ok: false, code: 'E_EMPTY', message: '工作目录不能为空' };
52
+ const platform = options.platform ?? process.platform;
53
+ const host = hostPlatform(platform, options.wsl);
54
+ if (host === 'win32') {
55
+ // Windows 上 POSIX 绝对路径(`/mnt/d/x`)不是有效盘符路径;Node 会把它解释成
56
+ // 当前盘根目录,容易落进意料之外的位置。直接给出明确提示。
57
+ if (value.startsWith('/') && !WINDOWS_DRIVE.test(value)) {
58
+ return {
59
+ ok: false,
60
+ code: 'E_PLATFORM_PATH',
61
+ message: `工作目录「${value}」是 POSIX 路径,而当前宿主是 Windows;请改用盘符路径,例如 D:/works/my-project`,
62
+ };
63
+ }
64
+ return { ok: true };
65
+ }
66
+ // POSIX(含 WSL):Windows 形态一律拒绝,并给出可用的替代写法。
67
+ if (UNC.test(value)) {
68
+ return {
69
+ ok: false,
70
+ code: 'E_PLATFORM_PATH',
71
+ message: `工作目录「${value}」是 Windows UNC 路径(\\\\wsl.localhost\\…),Linux 宿主无法使用;请改用挂载点路径,例如 /home/<user>/works`,
72
+ };
73
+ }
74
+ if (WINDOWS_DRIVE.test(value) || WINDOWS_DRIVE_BARE.test(value) || (BACKSLASH.test(value) && !value.startsWith('/'))) {
75
+ const suggestion = windowsToWsl(value);
76
+ const hint = host === 'wsl' && suggestion !== null
77
+ ? `请改用 WSL 内的挂载路径:${suggestion}`
78
+ : '请改用 POSIX 路径,例如 /home/<user>/works/my-project';
79
+ return {
80
+ ok: false,
81
+ code: 'E_PLATFORM_PATH',
82
+ message: `工作目录「${value}」是 Windows 路径,而当前宿主是 Linux;${hint}`,
83
+ ...(suggestion === null ? {} : { suggestion }),
84
+ };
85
+ }
86
+ return { ok: true };
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
+
103
+ /** 目录输入框的示例路径(与宿主平台一致)。 */
104
+ export function workspaceExample(platform = process.platform, options = {}) {
105
+ const host = hostPlatform(platform, options.wsl);
106
+ if (host === 'win32') return 'D:/works/my-project';
107
+ if (host === 'wsl') return '/mnt/d/works/my-project';
108
+ return '/home/user/works/my-project';
109
+ }
@@ -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.156",
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",