@suifei/dsh-ai-team 0.4.153 → 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,16 @@
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
+
8
+ ## 0.4.154 - 2026-12-03
9
+
10
+ - 新建和编辑项目可用宿主的浏览式目录列表。选定后回填路径,提交表单时才保存或创建项目。感谢 @ljyzww 提供 Windows 复现与宿主契约(#100)。
11
+ - 桌面首次安装说明明确初始化后先退出应用,再安装到内置 `desktop` profile。感谢 @Arnoldnuo 的桌面安装反馈(#102)。
12
+ - 编制巡检列出缺少合格验收人的任务、宿主回合观察值和容量来源。补位建议按每张卡的实际验收资格判断能否恢复现有成员或需要补位。感谢 @buger-gif 的现场案例和巡检建议(#116)。
13
+
3
14
  ## 0.4.153 - 2026-12-03
4
15
 
5
16
  - 看板的受阻徽标、读屏名称和分组计数使用宿主提供的当前受阻状态,依赖编号保持可查。感谢 @idontlikefruit 提供复现(#115)。
package/README.md CHANGED
@@ -37,6 +37,8 @@
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)。
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)。
40
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)。
41
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)。
42
44
  - **PMO 重启后续跑**(0.4.152)。恢复原会话时即提供模型路由,避免首轮因缺少模型而失败。保留原 PMO 会话、成员关系和任务。感谢 [@phm101299-ui](https://github.com/phm101299-ui),[#112](https://github.com/suifei/dsh-ai-team/issues/112)。
@@ -127,6 +129,18 @@ const svg = HashAvatar.svg('墨渊', { gender: 'male', age: 'middle', race: 'asi
127
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 同形的私有源。在线人才同样只读,可「复制为可编辑」。
128
130
  - 成员在账本里记下来源人才与版本、职责;人才文件之后再改,不会悄悄改动已招成员的性格与职责。已有项目不受新团队影响。文件写坏时跳过它并在诊断日志记 `catalog.load.fail` / `catalog.team.fail`。
129
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
+
130
144
  ### 按蓝图试跑
131
145
 
132
146
  在「新建项目 → 按蓝图试跑」填写业务、月目标、你保留的工作、每周可投入时间和手工耗时。插件比较候选的已知手工负担,把首发收窄到一个真实样本和一份待审草稿。预览里可以查看岗位提示词、验收清单和七天上线步骤。
@@ -141,6 +155,8 @@ const svg = HashAvatar.svg('墨渊', { gender: 'male', age: 'middle', race: 'asi
141
155
 
142
156
  在当前 DSH profile 的 `ai-team` 配置中设 `staffingReviewMinutes: 180` 和 `diagLevel: full` 后,启用 PMO 自动的运行中普通项目会随现有巡检周期采样,每个时间窗口记录一次。`staffingReviewMinutes: 0`(默认)关闭采样。诊断日志中的 `pmo.staffing.review` 包含岗位已分配队列、可认领与待验收队列、最长及平均等待,以及采样窗口内每位成员的提交、验收和退回。返工率按退回的本窗口提交除以本窗口提交数计算,零样本为空。
143
157
 
158
+ 巡检还会记录没有合格验收人的任务 ID、插件观察到的在队成员运行回合数和容量来源。并发上限按当前项目的根代理树记录,来源为 `default` 时使用默认估计,为 `host` 时来自这棵树的宿主容量回执。宿主释放槽位后,插件优先补投本树排队最久的成员。PMO 会把长期无人可验收的任务带进现有补位建议。
159
+
144
160
  巡检复用现有派员建议和冷却规则,记录被暂缓的建议。人员动作仍由已有授权流程处理。试跑样本和调整建议可回到 [#116](https://github.com/suifei/dsh-ai-team/issues/116)。
145
161
 
146
162
  ---
@@ -164,7 +180,7 @@ const svg = HashAvatar.svg('墨渊', { gender: 'male', age: 'middle', race: 'asi
164
180
 
165
181
  ### DSH 桌面应用
166
182
 
167
- 首次使用时先打开一次 DSH 桌面应用,初始化 `desktop`。使用桌面版自带的 `dsh` 安装。
183
+ 首次使用时先打开一次 DSH 桌面应用,初始化 `desktop`。完全退出应用后,使用桌面版自带的 `dsh` 安装。
168
184
 
169
185
  ```powershell
170
186
  dsh plugin --profile desktop add "@suifei/dsh-ai-team"
@@ -185,6 +201,8 @@ dsh --profile web --no-open --port 33271
185
201
 
186
202
  第一次进入 Project 先设置 **工作目录**:工作目录编辑器会自动弹出,并预填宿主给出的建议值——配置项 `defaultWorkspace` → 当前进程目录 → **`~/works`**(Windows 为 `%USERPROFILE%\works`,Linux/macOS 为 `~/works`;不存在时自动创建)。点「选择目录」或用输入框改成任意已存在的目录即可;**新建项目必须填工作目录**(服务端强制,空目录会被 400 拒绝)。每个 Project 独立一个目录,成员只在这个目录里执行 Task。
187
203
 
204
+ 「选择目录」会使用宿主的原生对话框或在文渊阁内浏览宿主目录。选定后先回填路径,保存或创建项目时生效。
205
+
188
206
  ### 打开文渊阁后提示 503
189
207
 
190
208
  先确认插件安装在当前入口使用的 profile。桌面应用可用 `dsh plugin --profile desktop list "@suifei/dsh-ai-team" --depth 0` 回读版本。浏览器入口把命令里的 `desktop` 换成 `web`,并打开当前 Web 进程输出的完整 URL。
@@ -386,14 +404,14 @@ round-19 DeepSeek + Zhipu 双 provider
386
404
  | 贡献者 | 贡献 | 带来的进展 |
387
405
  |---|---|---|
388
406
  | [@idontlikefruit](https://github.com/idontlikefruit) | 受阻状态的三组复现输入 [#115](https://github.com/suifei/dsh-ai-team/issues/115) | 统一看板徽标、读屏和分组统计的受阻判定,保留历史依赖 |
389
- | [@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 会话里预览和确认建队 |
390
408
  | [@Estelle00](https://github.com/Estelle00) | DSH 0.2.3 启动 503 的复现和桌面验证 [#122](https://github.com/suifei/dsh-ai-team/issues/122) | 接入新版会话鉴权接口,恢复工作台初始化 |
391
409
  | [@phm101299-ui](https://github.com/phm101299-ui) | PMO 冷恢复的复现、根因和桌面验证 [#112](https://github.com/suifei/dsh-ai-team/issues/112) | 让原 PMO 在宿主重启后带着模型路由继续工作,保留成员关系和任务 |
392
410
  | [@godfay-g](https://github.com/godfay-g) | 技能目录和 ZIP 的导入建议 [#109](https://github.com/suifei/dsh-ai-team/issues/109) | 成员与自定义人才可在文渊阁选择已安装的技能或导入完整技能包。0.4.151 统一新建人才的导入入口,并由文渊阁直接安装整包 |
393
411
  | [@qq958691165](https://github.com/qq958691165) | 归档项目的成员反馈、团队管理建议 [#103](https://github.com/suifei/dsh-ai-team/issues/103) | 人员池排除归档项目,侧栏集中管理项目成员与团队预设 |
394
- | [@Arnoldnuo](https://github.com/Arnoldnuo) | 桌面端启动 503 反馈 [#102](https://github.com/suifei/dsh-ai-team/issues/102) | 工作台提供分情况的 503 提示,快速开始说明内置 `desktop` 与 `web` 的安装和启动方式,连接错误提示引导核对 profile |
412
+ | [@Arnoldnuo](https://github.com/Arnoldnuo) | 桌面端启动 503 反馈 [#102](https://github.com/suifei/dsh-ai-team/issues/102) | 工作台提示核对 profile,快速开始说明内置 `desktop` 与 `web` 的入口和安装方式,以及桌面端首次初始化和退出步骤 |
395
413
  | [@Lamooner](https://github.com/Lamooner) | PMO 决策反馈与建议 [#99](https://github.com/suifei/dsh-ai-team/issues/99) | 避免选中「不推荐」项,移除编号偏向并补充括注编号回归 |
396
- | [@ljyzww](https://github.com/ljyzww) | Windows 目录选择反馈 [#100](https://github.com/suifei/dsh-ai-team/issues/100) | 新建和编辑项目共用目录选择失败提示,保留手填路径 |
414
+ | [@ljyzww](https://github.com/ljyzww) | Windows 目录选择复现及宿主能力说明 [#100](https://github.com/suifei/dsh-ai-team/issues/100) | 新建和编辑项目共用浏览式目录选择,选定后回填路径 |
397
415
  | [@xiuchuan666](https://github.com/xiuchuan666) | 反馈与建议 [#65](https://github.com/suifei/dsh-ai-team/issues/65) | 输入框长高可拖大、贴图拖文件、@ 点名成员(0.4.120–0.4.123);人才市场与在线人才库(0.4.124–0.4.131);团队扩编:超限排队、开发验收配对、空闲必派、写入范围、加人建议(0.4.140) |
398
416
  | [@TardisBooo](https://github.com/TardisBooo) | 代码 [#88](https://github.com/suifei/dsh-ai-team/pull/88) | 工具参数改为对象 JSON Schema,Grok 4.7 可用(0.4.139) |
399
417
 
package/client.js CHANGED
@@ -299,6 +299,13 @@ window.__ModuleLoader__.load({
299
299
  workspacePathPlaceholder: '例如 D:/work/my-project',
300
300
  workspacePickUnavailable: '当前宿主的目录选择器不能用于此表单。请在「工作目录」中粘贴或输入完整路径。',
301
301
  workspacePickFailed: '未能打开目录选择器。请重试,或在「工作目录」中粘贴或输入完整路径。',
302
+ workspaceBrowseTitle: '浏览工作目录',
303
+ workspaceBrowseHome: '主目录',
304
+ workspaceBrowseParent: '上一级',
305
+ workspaceBrowseChoose: '使用当前目录',
306
+ workspaceBrowseEmpty: '此目录没有子目录。',
307
+ workspaceBrowseTruncated: '仅显示宿主返回的部分目录。',
308
+ workspaceBrowseError: '未能读取目录。{message}',
302
309
  workspaceSave: '保存目录',
303
310
  projectCreate: '创建项目',
304
311
  projectCreated: '已创建项目 {name}。',
@@ -809,6 +816,13 @@ window.__ModuleLoader__.load({
809
816
  workspacePathPlaceholder: 'e.g. D:/work/my-project',
810
817
  workspacePickUnavailable: 'The host’s directory picker is unavailable for this form. Paste or enter the full path in the Workspace field.',
811
818
  workspacePickFailed: 'Could not open the directory picker. Retry, or paste or enter the full path in the Workspace field.',
819
+ workspaceBrowseTitle: 'Browse workspace directories',
820
+ workspaceBrowseHome: 'Home',
821
+ workspaceBrowseParent: 'Parent directory',
822
+ workspaceBrowseChoose: 'Use this directory',
823
+ workspaceBrowseEmpty: 'This directory has no subdirectories.',
824
+ workspaceBrowseTruncated: 'Only some directories were returned by the host.',
825
+ workspaceBrowseError: 'Could not read the directory. {message}',
812
826
  workspaceSave: 'Save directory',
813
827
  projectCreate: 'Create project',
814
828
  projectCreated: 'Created project {name}.',
@@ -1575,6 +1589,11 @@ window.__ModuleLoader__.load({
1575
1589
  .at-modal.at-modal-wide { width: 90%; height: 90%; max-height: 90%; }
1576
1590
  .at-modal.at-blueprint-dialog { width: min(720px, 90cqi); max-width: 90%; height: auto; }
1577
1591
  .at-modal.at-blueprint-setup { width: min(820px, 90cqi); height: auto; }
1592
+ .at-modal.at-directory-picker { width: min(460px, 90cqi); overflow-x: hidden; }
1593
+ .at-directory-nav { display: flex; flex-wrap: wrap; gap: 8px; }
1594
+ .at-directory-path { overflow-wrap: anywhere; }
1595
+ .at-directory-list { display: grid; gap: 4px; max-height: 42vh; overflow: auto; overscroll-behavior: contain; }
1596
+ .at-directory-list .at-btn { display: block; min-width: 0; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; text-align: start; }
1578
1597
  .at-blueprint-fields { display: grid; gap: 10px; min-width: 0; }
1579
1598
  .at-blueprint-fields fieldset { min-inline-size: 0; margin: 0; padding: 10px; border: 1px solid var(--dsw-alias-border-l1); border-radius: var(--dsw-radius-sm); }
1580
1599
  .at-blueprint-fields p { margin: 0; overflow-wrap: anywhere; }
@@ -2101,6 +2120,58 @@ window.__ModuleLoader__.load({
2101
2120
  return h('div', { className: 'at-modalback', ref: backRef }, children);
2102
2121
  }
2103
2122
 
2123
+ function WorkspaceDirectoryBrowser({ t, service, initialPath, onPick, onClose }) {
2124
+ const [request, setRequest] = React.useState({ path: initialPath });
2125
+ const [listing, setListing] = React.useState(null);
2126
+ const [error, setError] = React.useState('');
2127
+ const [loading, setLoading] = React.useState(true);
2128
+ const closeButton = React.useRef(null);
2129
+ React.useEffect(() => {
2130
+ const previous = document.activeElement;
2131
+ closeButton.current?.focus({ preventScroll: true });
2132
+ return () => previous?.focus?.({ preventScroll: true });
2133
+ }, []);
2134
+ React.useEffect(() => {
2135
+ const controller = new AbortController();
2136
+ const { signal } = controller;
2137
+ const load = async () => {
2138
+ try {
2139
+ const result = await service.listDirectory(request.path, signal);
2140
+ if (!signal.aborted) setListing(result);
2141
+ } catch (cause) {
2142
+ if (!signal.aborted) setError(cause?.message ?? String(cause));
2143
+ } finally {
2144
+ if (!signal.aborted) setLoading(false);
2145
+ }
2146
+ };
2147
+ void load();
2148
+ return () => controller.abort();
2149
+ }, [request, service]);
2150
+ const browse = (path) => {
2151
+ setLoading(true);
2152
+ setError('');
2153
+ setRequest({ path });
2154
+ };
2155
+ const parentPath = listing?.crumbs?.at(-2)?.path;
2156
+ return h(ModalBack, { onClose },
2157
+ h('div', { className: 'at-modal at-directory-picker', role: 'dialog', 'aria-modal': 'true', 'aria-label': t('workspaceBrowseTitle') },
2158
+ h('h2', { className: 'at-modaltitle' }, t('workspaceBrowseTitle')),
2159
+ h('div', { className: 'at-modalactions' },
2160
+ h('button', { ref: closeButton, className: 'at-btn', type: 'button', onClick: onClose }, t('cancel')),
2161
+ h('button', { className: 'at-btn at-btn-primary', type: 'button', disabled: loading || !listing?.path || Boolean(error), onClick: () => onPick(listing.path) }, t('workspaceBrowseChoose'))),
2162
+ h('div', { className: 'at-directory-nav' },
2163
+ h('button', { className: 'at-btn', type: 'button', disabled: loading, onClick: () => browse(undefined) }, t('workspaceBrowseHome')),
2164
+ h('button', { className: 'at-btn', type: 'button', disabled: loading || !parentPath, onClick: () => browse(parentPath) }, t('workspaceBrowseParent'))),
2165
+ listing?.path ? h('div', { className: 'at-modalmeta at-directory-path' }, listing.path) : null,
2166
+ loading ? h('div', { className: 'at-modalmeta', role: 'status' }, t('loading')) : null,
2167
+ error ? h('div', { className: 'at-modalerror at-directory-path', role: 'alert' }, tf(t, 'workspaceBrowseError', { message: error })) : null,
2168
+ h('div', { className: 'at-directory-list', 'aria-busy': loading },
2169
+ (listing?.entries ?? []).map(({ name, path }) =>
2170
+ h('button', { className: 'at-btn', key: path, title: name, type: 'button', disabled: loading, onClick: () => browse(path) }, name))),
2171
+ !loading && !error && listing?.entries?.length === 0 ? h('p', { className: 'at-modalmeta' }, t('workspaceBrowseEmpty')) : null,
2172
+ listing?.truncated ? h('p', { className: 'at-modalmeta' }, t('workspaceBrowseTruncated')) : null));
2173
+ }
2174
+
2104
2175
  const emptyBlueprintOpportunity = () => ({ kind: '', work: '', minutes: '', perWeek: '' });
2105
2176
  const emptyBlueprintIntake = () => ({ business: '', humanWork: '', weeklyHours: '', opportunities: [emptyBlueprintOpportunity()] });
2106
2177
 
@@ -4295,6 +4366,12 @@ window.__ModuleLoader__.load({
4295
4366
  const [workspaceDraft, setWorkspaceDraft] = React.useState('');
4296
4367
  const [workspaceError, setWorkspaceError] = React.useState('');
4297
4368
  const [workspaceBusy, setWorkspaceBusy] = React.useState(false);
4369
+ const [workspacePicker, setWorkspacePicker] = React.useState(null);
4370
+ const workspacePickRequest = React.useRef(0);
4371
+ React.useEffect(() => {
4372
+ setWorkspacePicker((picker) => (picker && (picker.form === 'new' ? !newOpen : !workspaceOpen) ? null : picker));
4373
+ return () => { workspacePickRequest.current += 1; };
4374
+ }, [newOpen, workspaceOpen]);
4298
4375
  const [memberViewId, setMemberViewId] = React.useState(null);
4299
4376
  // 人员池(全局层):进入该 scope 时拉取一次聚合视图。
4300
4377
  const [peopleData, setPeopleData] = React.useState(null);
@@ -4996,31 +5073,41 @@ window.__ModuleLoader__.load({
4996
5073
  }
4997
5074
  async function pickWorkspacePath() {
4998
5075
  const service = ctx?.get?.('uiWorkspace') ?? ctx?.uiWorkspace;
4999
- if (service === undefined || service === null || typeof service.pickDirectory !== 'function') {
5000
- return { error: 'unavailable', path: null };
5001
- }
5002
- try {
5003
- return { path: await service.pickDirectory(), error: null };
5004
- } catch (error) {
5005
- // Harness rc.5 wraps the RPC error in a plain Error and retains only its message.
5006
- const unavailable = error?.code === 'directory-picker/unavailable'
5007
- || error?.message === 'directory picker failed: directoryPicker.pick needs the native capability; the composed picker serves "browse"';
5008
- return { error: unavailable ? 'unavailable' : 'failed', path: null };
5076
+ if (typeof service?.pickDirectory === 'function') {
5077
+ try {
5078
+ return { path: await service.pickDirectory() };
5079
+ } catch (error) {
5080
+ // Harness rc.5 retains only the message from the native pick RPC failure.
5081
+ const unavailable = (error?.code ?? error?.rpcError?.code) === 'directory-picker/unavailable'
5082
+ || error?.message === 'directory picker failed: directoryPicker.pick needs the native capability; the composed picker serves "browse"';
5083
+ if (!unavailable) {
5084
+ console.warn('[ai-team] directory picker failed', error);
5085
+ return { error: 'failed' };
5086
+ }
5087
+ }
5009
5088
  }
5089
+ return typeof service?.listDirectory === 'function' ? { browse: service } : { error: 'unavailable' };
5010
5090
  }
5011
- async function applyWorkspacePick(setPath, setError) {
5091
+ async function applyWorkspacePick(form, draft, setPath, setError) {
5092
+ const request = ++workspacePickRequest.current;
5012
5093
  const picked = await pickWorkspacePath();
5094
+ if (workspacePickRequest.current !== request) return;
5013
5095
  const unavailable = t('workspacePickUnavailable');
5014
5096
  const failed = t('workspacePickFailed');
5015
- if (picked.path) {
5016
- setPath(picked.path);
5097
+ const onPick = (path) => {
5098
+ setPath(path);
5017
5099
  setError((previous) => previous === unavailable || previous === failed ? '' : previous);
5100
+ };
5101
+ if (picked.browse) {
5102
+ setWorkspacePicker({ form, service: picked.browse, initialPath: draft.trim() || undefined, onPick });
5103
+ } else if (picked.path) {
5104
+ onPick(picked.path);
5018
5105
  } else if (picked.error) {
5019
5106
  setError(picked.error === 'unavailable' ? unavailable : failed);
5020
5107
  }
5021
5108
  }
5022
5109
  async function pickNewWorkspace() {
5023
- await applyWorkspacePick(setNWorkspace, setNError);
5110
+ await applyWorkspacePick('new', nWorkspace, setNWorkspace, setNError);
5024
5111
  }
5025
5112
  function openWorkspaceEditor() {
5026
5113
  setWorkspaceDraft(project?.workspacePath ?? '');
@@ -5028,7 +5115,7 @@ window.__ModuleLoader__.load({
5028
5115
  setWorkspaceOpen(true);
5029
5116
  }
5030
5117
  async function pickProjectWorkspace() {
5031
- await applyWorkspacePick(setWorkspaceDraft, setWorkspaceError);
5118
+ await applyWorkspacePick('edit', workspaceDraft, setWorkspaceDraft, setWorkspaceError);
5032
5119
  }
5033
5120
  async function saveWorkspace() {
5034
5121
  if (!project || workspaceBusy || !workspaceDraft.trim()) return;
@@ -6585,6 +6672,11 @@ window.__ModuleLoader__.load({
6585
6672
  h('h2', { className: 'at-modaltitle' }, withIco('users', t('teamComposeTitle'), 16)),
6586
6673
  h(TeamComposer, { t, talents, onSaved: (team) => { setTeamComposeOpen(false); void loadTeams(team && team.id); }, onCancel: () => setTeamComposeOpen(false) }))) : null,
6587
6674
  peopleModel ? h(PeopleModelDialog, { t, catalog: modelCatalog, catalogError: modelCatalogError, people: peopleData ?? [], initial: peopleModel, onApply: applyPeopleModel, onClose: () => setPeopleModel(null) }) : null,
6675
+ workspacePicker && (workspacePicker.form === 'new' ? newOpen : workspaceOpen) ? h(WorkspaceDirectoryBrowser, {
6676
+ t, service: workspacePicker.service, initialPath: workspacePicker.initialPath,
6677
+ onPick: (path) => { workspacePicker.onPick(path); setWorkspacePicker(null); },
6678
+ onClose: () => setWorkspacePicker(null),
6679
+ }) : null,
6588
6680
  dialog ? h(WorkbenchDialog, { key: dialogSeqRef.current, t, dialog, onDismiss: () => setDialog(null) }) : null,
6589
6681
  shortcutsOpen ? h(ModalBack, { onClose: () => setShortcutsOpen(false) },
6590
6682
  h('div', { className: 'at-modal', role: 'dialog', 'aria-modal': 'true', 'aria-label': t('shortcutTitle') },
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 hostCapacity = HOST_SUBAGENT_LIMIT;
983
- const noteHostCapacity = (error) => {
984
- const limit = capacityLimit(error);
985
- if (limit !== null) hostCapacity = 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);
@@ -1485,8 +1509,11 @@ export function apply(ctx, config = {}) {
1485
1509
  const reviewWindow = diag.level === 'full' && reviewInterval > 0 ? Math.floor(now / reviewInterval) : null;
1486
1510
  const reviewDue = reviewWindow !== null && pmoStaffingReviewWindows.get(projectRuntime.id) !== reviewWindow;
1487
1511
  const suppressed = [];
1512
+ const inTurn = (id) => turnsInFlight.has(id);
1513
+ const observedHostCapacity = treeCapacity.get(hosts.get(projectRuntime.id)?.agent);
1514
+ const capacity = observedHostCapacity ?? HOST_SUBAGENT_LIMIT;
1488
1515
  const adviceList = planStaffingAdvice(staffingState, {
1489
- now, inTurn: (id) => turnsInFlight.has(id), capacity: hostCapacity,
1516
+ now, inTurn, capacity,
1490
1517
  humanId: projectRuntime.service.humanId(), wait: (config.staffingAdviceMinutes ?? 30) * 60_000,
1491
1518
  onSuppressed: reviewDue ? (entry) => suppressed.push(entry) : undefined,
1492
1519
  });
@@ -1494,7 +1521,8 @@ export function apply(ctx, config = {}) {
1494
1521
  pmoStaffingReviewWindows.set(projectRuntime.id, reviewWindow);
1495
1522
  try {
1496
1523
  const review = staffingReview(staffingState, projectRuntime.ledger.events, {
1497
- now, intervalMs: reviewInterval, capacity: hostCapacity, advice: adviceList, suppressed,
1524
+ now, intervalMs: reviewInterval, capacity, capacitySource: observedHostCapacity === null ? 'default' : 'host',
1525
+ inTurn, advice: adviceList, suppressed,
1498
1526
  });
1499
1527
  diag.append({ ev: 'pmo.staffing.review', projectId: projectRuntime.id, window: reviewWindow, ...review });
1500
1528
  } catch (error) {
@@ -2291,6 +2319,7 @@ export function apply(ctx, config = {}) {
2291
2319
  diag?.append({ ev: 'activate.reject', projectId: projectRuntime.id, memberId: member.id, code: 'E_RUNTIME_UNAVAILABLE', detail: 'no provider' });
2292
2320
  return { error: { code: 'E_RUNTIME_UNAVAILABLE', message: 'no subagent provider is registered' }, status: 503 };
2293
2321
  }
2322
+ let capacityRoot;
2294
2323
  try {
2295
2324
  const selection = serviceOf(ctx, 'agentDefaultModel')?.currentSelection?.();
2296
2325
  const activationMember = member.config?.provider && member.config?.model
@@ -2307,6 +2336,7 @@ export function apply(ctx, config = {}) {
2307
2336
  return { error: { code: 'E_RUNTIME_UNAVAILABLE', message: 'no member or default provider/model is configured' }, status: 503 };
2308
2337
  }
2309
2338
  const parentInfo = await ensureParent(projectRuntime);
2339
+ capacityRoot = parentInfo.agent;
2310
2340
  const runtime = new MemberRuntime({
2311
2341
  subagents,
2312
2342
  sessions,
@@ -2384,7 +2414,7 @@ export function apply(ctx, config = {}) {
2384
2414
  // 超过宿主并发上限:不是成员失败——记 failed 会让 waker 再也不叫它(团队超过 8 人时第 9 位
2385
2415
  // 首次激活就会被永久搁置)。保持原状态,唤醒路径会把它排进 deferredWakes 的 capacity 队列。
2386
2416
  if (isCapacityError(error)) {
2387
- noteHostCapacity(error);
2417
+ treeCapacity.record(capacityRoot, error);
2388
2418
  diag.append({ ev: 'member.activate.capacity', memberId: member.id, projectId: projectRuntime.id, message: error?.message ?? String(error) });
2389
2419
  } else if (currentStatus !== 'retired') {
2390
2420
  try {
@@ -2500,31 +2530,41 @@ export function apply(ctx, config = {}) {
2500
2530
  };
2501
2531
 
2502
2532
  const blueprintCreations = new Map();
2503
- 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 }) {
2504
2542
  await ready;
2505
- if (booted === null) throw new Error('team ledger is unavailable');
2543
+ if (disposed || booted === null) throw new Error('team ledger is unavailable');
2506
2544
  let next = projectRuntime(nextProjectId);
2507
2545
  if (next === null) {
2508
2546
  next = await ProjectRuntime.open({
2509
2547
  rootDir: booted.dataDir,
2510
2548
  projectId: nextProjectId,
2511
- projectName,
2512
- projectGoal,
2549
+ projectName: name,
2550
+ projectGoal: goal,
2513
2551
  workspacePath,
2514
2552
  diag,
2515
2553
  pmoMaxRounds: config.pmoMaxRounds,
2516
- teamPreset: blueprint ? null : teamPresetFor(config, diag, team),
2554
+ teamPreset: blueprint ? null : teamPreset ?? teamPresetFor(config, diag),
2517
2555
  blueprint,
2556
+ pmoAuto,
2518
2557
  });
2519
2558
  // 账本和两个岗位先落地,重启时才不会把半写的蓝图项目播种成预设团队。
2520
2559
  try {
2521
- booted.registry.add({ id: nextProjectId, name: projectName, goal: projectGoal, workspacePath });
2560
+ booted.registry.add({ id: nextProjectId, name, goal, workspacePath });
2522
2561
  } catch (error) {
2523
- next.close();
2562
+ await next.close();
2524
2563
  throw error;
2525
2564
  }
2526
2565
  booted.runtimes.set(nextProjectId, next);
2527
- attachRuntime(next);
2566
+ if (!disposed) attachRuntime(next);
2567
+ diag.append({ ev: 'project.create', id: nextProjectId, team: teamPreset?.id ?? null });
2528
2568
  }
2529
2569
  booted.registry.setActive(nextProjectId);
2530
2570
  booted = {
@@ -2534,9 +2574,25 @@ export function apply(ctx, config = {}) {
2534
2574
  ledger: next.ledger,
2535
2575
  service: next.service,
2536
2576
  };
2537
- broadcast(undefined, next);
2577
+ if (!disposed) broadcast(undefined, next);
2538
2578
  return next;
2539
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();
2540
2596
 
2541
2597
  const dispose = webServer.register({
2542
2598
  kind: 'prefix',
@@ -3349,28 +3405,9 @@ export function apply(ctx, config = {}) {
3349
3405
  return send(res, distilled);
3350
3406
  }
3351
3407
  if (body.type === 'project.create' || body.type === 'project.blueprint.preview') {
3352
- const name = typeof body.payload?.name === 'string' ? body.payload.name.trim() : '';
3353
- const goal = typeof body.payload?.goal === 'string' ? body.payload.goal.trim() : '';
3354
- const workspacePath = typeof body.payload?.workspacePath === 'string' ? body.payload.workspacePath.trim() : '';
3408
+ const input = projectInput(body.payload);
3409
+ const { name, goal, workspacePath } = input;
3355
3410
  const preview = body.type === 'project.blueprint.preview';
3356
- if (name === '') return send(res, { error: { code: 'E_INVALID_ARGUMENT', message: 'project name is required' } }, 400);
3357
- // 每个项目都必须指定工作目录:先在这里挡,别把一行没有目录的
3358
- // registry 记录写进去(service 也会再校验一次)。
3359
- if (workspacePath === '') {
3360
- return send(res, { error: { code: 'E_INVALID_ARGUMENT', message: '工作目录是必填项:请选择一个已存在的目录' } }, 400);
3361
- }
3362
- // 工作目录可空(稍后设置):讨论与建卡不受限;成员激活在
3363
- // activateMember 处 fail-closed,绝不落到宿主默认目录执行。
3364
- // 但给了就必须真实存在:非法路径若先写进 registry,boot 会在
3365
- // 该项上抛出,导致整个插件起不来(所有路由 503),只能手工改
3366
- // projects.json 才能恢复。
3367
- if (workspacePath !== '') {
3368
- let stat = null;
3369
- try { stat = statSync(workspacePath); } catch { stat = null; }
3370
- if (stat === null || (typeof stat.isDirectory === 'function' && stat.isDirectory() !== true)) {
3371
- return send(res, { error: { code: 'E_INVALID_ARGUMENT', message: `工作目录不存在或不是目录:${workspacePath}` } }, 400);
3372
- }
3373
- }
3374
3411
  const blueprint = preview || body.payload?.blueprint !== undefined ? buildTeamBlueprint({ ...body.payload?.blueprint, goal }) : null;
3375
3412
  if (blueprint) {
3376
3413
  const id = preview ? ids.project() : body.payload?.blueprintId;
@@ -3394,23 +3431,16 @@ export function apply(ctx, config = {}) {
3394
3431
  let pending = blueprintCreations.get(id);
3395
3432
  if (pending && pending.fingerprint !== fingerprint) return send(res, { error: { code: 'E_CONFLICT', message: '这个蓝图正在创建' } }, 409);
3396
3433
  if (!pending) {
3397
- const runtimePromise = activateProject(id, name, goal, workspacePath, '', blueprint).finally(() => blueprintCreations.delete(id));
3434
+ const runtimePromise = activateProject(id, { ...input, blueprint }).finally(() => blueprintCreations.delete(id));
3398
3435
  pending = { fingerprint, runtimePromise };
3399
3436
  blueprintCreations.set(id, pending);
3400
3437
  }
3401
3438
  const next = await pending.runtimePromise;
3402
3439
  return send(res, { ok: true, project: next.service.state.projects[id] });
3403
3440
  }
3404
- // 新建时选的团队:必须在目录里且引用的人才都在(否则种成员会悄悄退回默认团队)。
3405
3441
  const team = typeof body.payload?.team === 'string' ? body.payload.team.trim() : '';
3406
- if (team !== '') {
3407
- const chosen = listTeams(talentCatalog(diag)).find((entry) => entry.id === team);
3408
- if (chosen === undefined) return send(res, { error: { code: 'E_INVALID_ARGUMENT', message: `团队不存在:${team}` } }, 400);
3409
- if (chosen.broken) return send(res, { error: { code: 'E_INVALID_ARGUMENT', message: `团队「${chosen.name}」引用了不存在的人才,先修好再用` } }, 400);
3410
- }
3411
3442
  const id = ids.project();
3412
- const next = await activateProject(id, name, goal, workspacePath, team);
3413
- diag?.append({ ev: 'project.create', id, team: team || null });
3443
+ const next = await activateProject(id, { ...input, teamPreset: teamPresetFor(config, diag, team) });
3414
3444
  return send(res, { ok: true, project: next.service.state.projects[id] ?? { id, name } });
3415
3445
  }
3416
3446
  if (body.type === 'project.blueprint.start' && runtime.service.state.projects?.[runtime.id]?.blueprint && !blueprintGuardReady) {
@@ -3424,7 +3454,7 @@ export function apply(ctx, config = {}) {
3424
3454
  const record = booted.registry.list().find((project) => project.id === target);
3425
3455
  // 透传 workspacePath:否则账本里的 project/created 会把工作目录写成空,
3426
3456
  // 之后该项目的成员激活永远 E_WORKSPACE_REQUIRED。
3427
- const next = await activateProject(target, record?.name, record?.goal, record?.workspacePath);
3457
+ const next = await activateProject(target, record);
3428
3458
  return send(res, { ok: true, project: next.service.state.projects[target] ?? record });
3429
3459
  }
3430
3460
  if (body.type === 'member.activate') {
@@ -3572,7 +3602,7 @@ export function apply(ctx, config = {}) {
3572
3602
  const fallback = booted.registry.list().find((project) => project.id === fallbackId);
3573
3603
  if (fallback !== undefined && fallback.id !== runtime.id) {
3574
3604
  try {
3575
- await activateProject(fallback.id, fallback.name, fallback.goal, fallback.workspacePath);
3605
+ await activateProject(fallback.id, fallback);
3576
3606
  diag.append({ ev: 'project.archive.reactivated', from: runtime.id, to: fallback.id });
3577
3607
  } catch (error) {
3578
3608
  diag.append({ ev: 'project.archive.reactivate.fail', from: runtime.id, to: fallback.id, message: error?.message ?? String(error) });
@@ -3625,9 +3655,10 @@ export function apply(ctx, config = {}) {
3625
3655
  try { teamDiscipline.dispose(); } catch { /* already disposed */ }
3626
3656
  try { deferredWakes.dispose(); } catch { /* already disposed */ }
3627
3657
  hostSessionGate.dispose();
3628
- // 在途的 boot 也算本组合的资源:等它落定(落定时见 disposed 会自行关账本),
3629
- // 否则下一组合抢在关锁之前打开同一账本。
3630
- 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)];
3631
3662
  for (const client of sseClients) {
3632
3663
  try { client.res.end(); } catch { /* socket already gone */ }
3633
3664
  }
@@ -3656,13 +3687,9 @@ export function apply(ctx, config = {}) {
3656
3687
  offRequestError();
3657
3688
  offSessionEvent();
3658
3689
  offAgentCreated();
3690
+ offSubagentEnd();
3659
3691
  disposeTool();
3660
3692
  dispose();
3661
- for (const runtime of booted?.runtimes?.values() ?? []) {
3662
- cleanup.push(Promise.resolve().then(async () => {
3663
- try { await runtime.close(); } catch { /* ledger already closed */ }
3664
- }));
3665
- }
3666
3693
  return Promise.allSettled(cleanup).then(() => undefined);
3667
3694
  };
3668
3695
  }, 'ai-team: workbench routes');
package/lib/host/pmo.js CHANGED
@@ -1,4 +1,4 @@
1
- import { STALLED_MEMBER_STATUSES, dependenciesDone, teamRoles, writeScopeConflict } from '../domain/policy.js';
1
+ import { STALLED_MEMBER_STATUSES, dependenciesDone, isReviewCandidate, teamRoles, writeScopeConflict } from '../domain/policy.js';
2
2
  import { canDispatchTask } from '../domain/task.js';
3
3
 
4
4
  /**
@@ -254,8 +254,13 @@ function waitingSummary(tasks, now) {
254
254
  return { count: tasks.length, oldestMinutes: Math.round(oldest / MINUTE), meanMinutes: tasks.length ? Math.round(total / tasks.length / MINUTE) : 0 };
255
255
  }
256
256
 
257
+ function tasksWithoutReviewer(state, tasks) {
258
+ const members = Object.values(state.members ?? {});
259
+ return tasks.filter((task) => !members.some((member) => isReviewCandidate(member, task, state)));
260
+ }
261
+
257
262
  /** A read-only rollup of the existing queues and observed submissions in this window. */
258
- export function staffingReview(state, events, { now, intervalMs, capacity, advice = [], suppressed = [] }) {
263
+ export function staffingReview(state, events, { now, intervalMs, capacity, capacitySource = null, inTurn, advice = [], suppressed = [] }) {
259
264
  const since = now - intervalMs;
260
265
  const people = new Map(Object.values(state.members ?? {})
261
266
  .filter((member) => member.kind === 'agent' && member.status !== 'retired')
@@ -282,6 +287,11 @@ export function staffingReview(state, events, { now, intervalMs, capacity, advic
282
287
  groups.set(member.role, group);
283
288
  }
284
289
  const open = openTasks(state);
290
+ const waitingReview = open.filter(({ status }) => status === 'pending_acceptance');
291
+ const missingReviewers = tasksWithoutReviewer(state, waitingReview);
292
+ const activeMemberTurns = typeof inTurn === 'function'
293
+ ? [...people.keys()].map((id) => state.members[id].sessionId).filter((id) => typeof id === 'string' && inTurn(id)).length
294
+ : null;
285
295
  for (const task of open) {
286
296
  const group = groups.get(people.get(task.assigneeId)?.role);
287
297
  if (!group) continue;
@@ -289,9 +299,10 @@ export function staffingReview(state, events, { now, intervalMs, capacity, advic
289
299
  if (task.status === 'in_progress') group.inProgress += 1;
290
300
  }
291
301
  return {
292
- since, now, capacity,
302
+ since, now, capacity, capacitySource, capacityScope: 'agent-tree', activeMemberTurns,
293
303
  claimable: waitingSummary(claimableTasks(state, open), now),
294
- pendingAcceptance: waitingSummary(open.filter(({ status }) => status === 'pending_acceptance'), now),
304
+ pendingAcceptance: waitingSummary(waitingReview, now),
305
+ pendingAcceptanceWithoutReviewer: { ...waitingSummary(missingReviewers, now), taskIds: missingReviewers.map(({ id }) => id) },
295
306
  roles: [...groups.values()].map(({ assigned, ...group }) => ({ ...group, assignedQueue: waitingSummary(assigned, now) })),
296
307
  advice,
297
308
  suppressed,
@@ -302,7 +313,7 @@ export function staffingReview(state, events, { now, intervalMs, capacity, advic
302
313
  * 加人建议(用户 2026-11-20:从管理角度看推进过慢就该加人,由 Human 决定)。插件自己按看板判定,不靠模型:
303
314
  * - 开发不够:有可认领的待办等了 ≥ 30 分钟,却没有空闲开发(空闲开发会先被 planIdleStaffing 派活)。
304
315
  * 建议人数 = 等着的待办数,最多 3。
305
- * - 验收不够:待验收的卡等了 ≥ 30 分钟,且没有验收人,或每位验收人摊到 ≥ 2 张。建议加 1 名。
316
+ * - 验收不够:待验收的卡等了 ≥ 30 分钟,且卡片没有合格验收人、团队没有验收岗位或每个验收岗位摊到 ≥ 2 张。建议加 1 名。
306
317
  * 团队人数加上建议人数超过宿主同时在跑的上限时,理由里写明多出的人会排队、提速有限。
307
318
  * 该岗位有人停摆(failed / unavailable,等 Human 恢复)时改为「建议恢复」:人还在,只是停了,恢复比加人快,
308
319
  * 也不占新名额(实机 il2c 2026-11-20:验收人白砚 06:53 模型报错停摆,两张卡待验收 9 小时,旧版却说「团队没有验收人,建议加 1 名」)。
@@ -331,13 +342,18 @@ export function planStaffingAdvice(state, { now, inTurn, capacity = HOST_SUBAGEN
331
342
  : { role: 'developer', action: 'add', count: Math.min(waitingWork.length, 3), memberIds: [], reasons: [waited] }) });
332
343
  }
333
344
  const waitingReview = open.filter((task) => task.status === 'pending_acceptance' && age(task) >= wait);
334
- if (waitingReview.length > 0 && (qas.length === 0 || waitingReview.length >= 2 * qas.length)) {
335
- const waited = `${waitingReview.length} 张卡待验收已等 ${longest(waitingReview)} 分钟`;
336
- advice.push({ taskIds: waitingReview.map((task) => task.id), ...(stalled.qas.length > 0
337
- ? recover('qa', stalled.qas, waited)
338
- : { role: 'qa', action: 'add', count: 1, memberIds: [], reasons: [qas.length === 0
339
- ? `${waited},团队没有验收人`
340
- : `${waited},${qas.length} 位验收人每人摊到 ${Math.ceil(waitingReview.length / qas.length)} 张`] }) });
345
+ const missingReviewers = tasksWithoutReviewer(state, waitingReview);
346
+ if (waitingReview.length > 0 && (missingReviewers.length > 0 || qas.length === 0 || waitingReview.length >= 2 * qas.length)) {
347
+ const affected = missingReviewers.length > 0 ? missingReviewers : waitingReview;
348
+ const waited = `${affected.length} 张卡待验收已等 ${longest(affected)} 分钟`;
349
+ const restorable = stalled.qas.filter((member) =>
350
+ affected.some((task) => isReviewCandidate({ ...member, status: 'idle' }, task, state)));
351
+ const shortage = qas.length === 0 ? '团队没有验收人'
352
+ : missingReviewers.length > 0 ? '没有符合任务规则的验收人'
353
+ : `${qas.length} 位验收人每人摊到 ${Math.ceil(waitingReview.length / qas.length)} 张`;
354
+ advice.push({ taskIds: affected.map((task) => task.id), ...(restorable.length > 0
355
+ ? recover('qa', restorable, waited)
356
+ : { role: 'qa', action: 'add', count: 1, memberIds: [], reasons: [`${waited},${shortage}`] }) });
341
357
  }
342
358
  const headcount = Object.values(state?.members ?? {}).filter((member) => member?.kind === 'agent' && member.status !== 'retired' && !STALLED_MEMBER_STATUSES.includes(member.status)).length;
343
359
  const recent = (role) => Object.values(state?.inbox ?? {}).find((item) =>
@@ -353,7 +369,7 @@ export function planStaffingAdvice(state, { now, inTurn, capacity = HOST_SUBAGEN
353
369
  const reasons = [...entry.reasons];
354
370
  const who = entry.role === 'developer' ? '开发' : '验收';
355
371
  if (entry.action === 'recover') return { ...entry, reasons, title: `建议恢复停摆的${who}:${reasons.join(';')}` };
356
- if (headcount + entry.count > capacity) reasons.push(`团队现有 ${headcount} 名 AI 成员,宿主同时在跑上限 ${capacity},加人后超出的部分会排队,提速有限`);
372
+ if (headcount + entry.count > capacity) reasons.push(`团队现有 ${headcount} 名 AI 成员,按这棵代理树的 ${capacity} 个并发位估算,同时跑满时会排队`);
357
373
  return { ...entry, reasons, title: `建议加 ${entry.count} 名${who}:${reasons.join(';')}` };
358
374
  });
359
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.153",
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",