@suifei/dsh-ai-team 0.4.155 → 0.4.157

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,13 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.157 - 2026-12-03
4
+
5
+ - DSH 会话可根据目标建议团队,显示匹配的交付物。有多个候选时请用户选择。`/ai-team 调整` 可用一句话准备增员、改岗位或离队交接草稿,沿用会话确认和原卡交接。感谢 @buger-gif 的会话建队与编制反馈(#121)。
6
+
7
+ ## 0.4.156 - 2026-12-03
8
+
9
+ - 在 DSH 会话查看当前工作区的项目编制,从人才库增员、修改岗位或指定接手人后离队。确认时重新核对成员、人才和未收口任务,交接成功后原成员进入人才池。感谢 @buger-gif 的会话调整与任务交接场景(#121、#116)。
10
+
3
11
  ## 0.4.155 - 2026-12-03
4
12
 
5
13
  - DSH 会话可用 `/ai-team 建队` 预览当前工作目录和团队预设,确认后创建项目。取消草稿和重复确认均有回归,创建后 PMO 自动初始关闭。感谢 @buger-gif 提供会话建队场景(#121)。
package/README.md CHANGED
@@ -37,6 +37,8 @@
37
37
 
38
38
  ## 最近更新
39
39
 
40
+ - **会话建队建议与一句话调整编制**(0.4.157)。根据目标匹配团队预设并显示依据。可用一句话准备增员、改岗位或离队交接的草稿。感谢 [@buger-gif](https://github.com/buger-gif),[#121](https://github.com/suifei/dsh-ai-team/issues/121)。
41
+ - **从会话调整编制**(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)。
40
42
  - **从会话建队与分树容量**(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
43
  - **目录浏览和验收补位**(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)。
42
44
  - **看板受阻、离队交接和只读巡检**(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)。
@@ -137,10 +139,32 @@ const svg = HashAvatar.svg('墨渊', { gender: 'male', age: 'middle', race: 'asi
137
139
  /ai-team 建队 --team docs 整理接口文档
138
140
  ```
139
141
 
140
- 会话会显示工作目录、目标、团队预设与岗位。输入草稿末尾的 `/ai-team 确认 草稿ID` 创建项目,或用对应的取消命令丢弃草稿。省略 `--team` 时使用设置中的默认团队预设。草稿跟随当前会话,宿主重启后可以重新生成。
142
+ 可用 `/ai-team 建队 --recommend 整理接口文档` 根据目标匹配文档、内容、教育、视频或游戏预设。唯一候选会随匹配依据进入草稿。有多个候选或线索不足时,用 `--team` 指定预设。省略这两个选项时使用设置中的团队。
143
+
144
+ 会话会显示工作目录、目标、团队预设与岗位。输入草稿末尾的 `/ai-team 确认 草稿ID` 创建项目,或用对应的取消命令丢弃草稿。草稿跟随当前会话,宿主重启后可以重新生成。
141
145
 
142
146
  新项目会出现在文渊阁,PMO 自动初始关闭。团队准备好后,可以在项目页开启 PMO 自动。
143
147
 
148
+ ### 从 DSH 会话调整编制
149
+
150
+ `/ai-team 编制` 显示当前工作区的项目与成员编号。同一工作区有多个项目时,先选项目,使用 `/ai-team 编制 项目ID` 查看成员。用 `/ai-team 人才 [关键词]` 查看人才编号。
151
+
152
+ 也可以用 `/ai-team 调整` 说清一件事。同一工作区有多个项目时,在句子前加项目编号。同名成员或人才会列出编号供选择。
153
+
154
+ ```text
155
+ /ai-team 调整 给团队加一位文案
156
+ /ai-team 调整 把校书的岗位改为文档协调
157
+ /ai-team 调整 让墨痕把任务交给校书后离队
158
+ ```
159
+
160
+ ```text
161
+ /ai-team 增员 项目ID 人才ID
162
+ /ai-team 改岗位 项目ID 成员ID 新岗位
163
+ /ai-team 离队 项目ID 成员ID [接手人ID]
164
+ ```
165
+
166
+ 变更命令先显示草稿,用同一会话里的确认命令写入。有未收口任务时须指定项目内的接手人,插件交接原卡后再将成员移入人才池。草稿生成后若成员、人才或任务有变化,重新预览再确认。
167
+
144
168
  ### 按蓝图试跑
145
169
 
146
170
  在「新建项目 → 按蓝图试跑」填写业务、月目标、你保留的工作、每周可投入时间和手工耗时。插件比较候选的已知手工负担,把首发收窄到一个真实样本和一份待审草稿。预览里可以查看岗位提示词、验收清单和七天上线步骤。
@@ -404,7 +428,7 @@ round-19 DeepSeek + Zhipu 双 provider
404
428
  | 贡献者 | 贡献 | 带来的进展 |
405
429
  |---|---|---|
406
430
  | [@idontlikefruit](https://github.com/idontlikefruit) | 受阻状态的三组复现输入 [#115](https://github.com/suifei/dsh-ai-team/issues/115) | 统一看板徽标、读屏和分组统计的受阻判定,保留历史依赖 |
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 会话里预览和确认建队 |
431
+ | [@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 会话按目标建议预设,并确认一句话编制草稿及原任务交接 |
408
432
  | [@Estelle00](https://github.com/Estelle00) | DSH 0.2.3 启动 503 的复现和桌面验证 [#122](https://github.com/suifei/dsh-ai-team/issues/122) | 接入新版会话鉴权接口,恢复工作台初始化 |
409
433
  | [@phm101299-ui](https://github.com/phm101299-ui) | PMO 冷恢复的复现、根因和桌面验证 [#112](https://github.com/suifei/dsh-ai-team/issues/112) | 让原 PMO 在宿主重启后带着模型路由继续工作,保留成员关系和任务 |
410
434
  | [@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
@@ -22,6 +22,7 @@ import { ProjectRegistry } from './lib/host/project-registry.js';
22
22
  import { resolveDefaultWorkspace } from './lib/host/default-workspace.js';
23
23
  import { hostPlatform, requireWorkspaceDirectory, workspaceExample } from './lib/host/workspace-path.js';
24
24
  import { sessionTeamCommand } from './lib/host/session-team-command.js';
25
+ import { createSessionRoster } from './lib/host/session-roster.js';
25
26
  import { migrateLegacyNamespace, resolveProfile } from './lib/ledger/namespace.js';
26
27
  import { ids } from './lib/domain/ids.js';
27
28
  import { ERRORS, fail } from './lib/domain/errors.js';
@@ -81,7 +82,7 @@ import { readAttachment, uploadAttachment } from './lib/host/attachment-routes.j
81
82
  import { createDiagLogger, defaultDiagDir, installDiagSink } from './lib/diaglog.js';
82
83
  import { CATALOG_PACKAGE, clearOfficialCatalog, officialStatus, syncOfficialCatalog } from './lib/domain/catalog-sync.js';
83
84
  import { AVATAR_PACKAGE, avatarFile, avatarOptions, renderAvatarSvg, startAvatarLib } from './lib/domain/avatar.js';
84
- import { DEFAULT_TEAM, catalogRoots, deleteTalent, deleteTeam, forkTalent, installSkill, listInstallableSkills, listTalents, listTeams, loadCatalog, readSkillText, resolveTeam, talentFromMember, talentIdFrom, uniqueTalentId, uniqueTeamId, userCatalogDir, writeTalent, writeTeam } from './lib/domain/catalog.js';
85
+ import { DEFAULT_TEAM, catalogRoots, deleteTalent, deleteTeam, forkTalent, installSkill, listInstallableSkills, listTalents, listTeams, loadCatalog, matchTeamPresets, readSkillText, resolveTeam, talentFromMember, talentIdFrom, uniqueTalentId, uniqueTeamId, userCatalogDir, writeTalent, writeTeam } from './lib/domain/catalog.js';
85
86
 
86
87
  export const name = 'ai-team';
87
88
 
@@ -181,8 +182,7 @@ async function memberHostSkillReferences(names, ownedRoots, summaries) {
181
182
  }
182
183
 
183
184
  /** 新项目用哪个团队:新建时选的优先,其次插件设置 `teamPreset`,最后内置默认团队。 */
184
- function teamPresetFor(config, diag, chosen = '') {
185
- const catalog = talentCatalog(diag);
185
+ function teamPresetFor(config, diag, chosen = '', catalog = talentCatalog(diag)) {
186
186
  if (chosen !== '') {
187
187
  const entry = listTeams(catalog).find((team) => team.id === chosen);
188
188
  if (entry === undefined) fail(ERRORS.INVALID_ARGUMENT, `团队不存在:${chosen}`, { status: 400 });
@@ -2530,13 +2530,15 @@ export function apply(ctx, config = {}) {
2530
2530
  };
2531
2531
 
2532
2532
  const blueprintCreations = new Map();
2533
- const projectActivations = new Set();
2533
+ const projectOperations = new Set();
2534
+ function trackProjectOperation(operation) {
2535
+ const settled = () => projectOperations.delete(operation);
2536
+ projectOperations.add(operation);
2537
+ operation.then(settled, settled);
2538
+ return operation;
2539
+ }
2534
2540
  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;
2541
+ return trackProjectOperation(activateProjectRuntime(projectId, input));
2540
2542
  }
2541
2543
  async function activateProjectRuntime(nextProjectId, { name, goal, workspacePath = '', teamPreset = null, blueprint = null, pmoAuto = true }) {
2542
2544
  await ready;
@@ -2577,15 +2579,52 @@ export function apply(ctx, config = {}) {
2577
2579
  if (!disposed) broadcast(undefined, next);
2578
2580
  return next;
2579
2581
  }
2582
+ async function disposeMemberActivation(runtime, memberId, reason) {
2583
+ const sessionId = runtime.service.state.members?.[memberId]?.sessionId;
2584
+ const activation = activations.get(sessionId);
2585
+ if (activation === undefined) return;
2586
+ activations.delete(sessionId);
2587
+ try { await activation.dispose?.(); } catch { /* already gone */ }
2588
+ diag.append({ ev: 'member.activation.disposed', memberId, sessionId, reason });
2589
+ }
2590
+
2580
2591
  const nativeTeamCommand = sessionTeamCommand({
2581
- prepare: (input) => ({ ...projectInput(input), teamPreset: teamPresetFor(config, diag, input.team) }),
2592
+ prepare(input) {
2593
+ const project = projectInput(input);
2594
+ if (!input.recommend) return { ...project, teamPreset: teamPresetFor(config, diag, input.team) };
2595
+ const catalog = talentCatalog(diag);
2596
+ const candidates = matchTeamPresets(catalog, project.goal);
2597
+ diag.append({ ev: 'session.team.recommendation', candidates: candidates.map(({ id, terms }) => ({ id, terms })) });
2598
+ if (candidates.length !== 1) {
2599
+ const hint = '请用 /ai-team 建队 --team 预设ID 目标 指定团队。';
2600
+ const summary = candidates.map(({ name, id, terms }) => `- ${name}(${id}) · ${terms.join('、')}`).join('\n');
2601
+ fail(ERRORS.INVALID_ARGUMENT, summary ? `目标对应多个团队。${hint}\n${summary}` : `目标中缺少明确的团队线索。${hint}`);
2602
+ }
2603
+ const [match] = candidates;
2604
+ return { ...project, teamPreset: teamPresetFor(config, diag, match.id, catalog), matchedTerms: match.terms };
2605
+ },
2582
2606
  create: async (id, input) => (await activateProject(id, { ...input, pmoAuto: false })).service.state.projects[id],
2607
+ prepareRoster: createSessionRoster({
2608
+ async runtimes() {
2609
+ await ready;
2610
+ if (disposed || booted === null) fail(ERRORS.INVALID_STATE, '文渊阁账本尚未就绪。');
2611
+ return booted.runtimes.values();
2612
+ },
2613
+ isAvailable: (runtime) => !disposed && projectRuntime(runtime.id) === runtime
2614
+ && !peopleProjectIsArchived(booted.registry.list().find(({ id }) => id === runtime.id), runtime),
2615
+ catalog: () => talentCatalog(diag),
2616
+ actor: { kind: 'human', memberId: HUMAN_ID },
2617
+ disposeMemberActivation,
2618
+ }),
2583
2619
  diag,
2584
2620
  });
2585
2621
  const registerSessionCommand = (scoped) => {
2586
2622
  const registry = serviceOf(scoped, 'commands');
2587
2623
  if (typeof registry?.register !== 'function') return () => {};
2588
- const unregister = registry.register(nativeTeamCommand);
2624
+ const unregister = registry.register({
2625
+ ...nativeTeamCommand,
2626
+ handler: (input) => trackProjectOperation(nativeTeamCommand.handler(input)),
2627
+ });
2589
2628
  diag.append({ ev: 'session.team.command.registered' });
2590
2629
  return unregister;
2591
2630
  };
@@ -3613,17 +3652,7 @@ export function apply(ctx, config = {}) {
3613
3652
  // 退役/离队后必须释放常驻子代理:否则 activation 句柄只在 force
3614
3653
  // 重建或插件卸载时才回收,退役成员的会话会一直挂在进程里。
3615
3654
  if (body.type === 'member.retire' || body.type === 'member.leave') {
3616
- const retiredId = body.payload?.memberId;
3617
- const retired = runtime.service.state.members?.[retiredId];
3618
- const retiredSession = retired?.sessionId;
3619
- if (typeof retiredSession === 'string') {
3620
- const activation = activations.get(retiredSession);
3621
- if (activation !== undefined) {
3622
- activations.delete(retiredSession);
3623
- try { await activation.dispose?.(); } catch { /* already gone */ }
3624
- diag.append({ ev: 'member.activation.disposed', memberId: retiredId, sessionId: retiredSession, reason: body.type });
3625
- }
3626
- }
3655
+ await disposeMemberActivation(runtime, body.payload?.memberId, body.type);
3627
3656
  }
3628
3657
  send(res, { ok: true, ...result });
3629
3658
  // 唤醒只由账本事件路径规划(attachRuntime 的 onEvent):dispatch 的
@@ -3655,8 +3684,8 @@ export function apply(ctx, config = {}) {
3655
3684
  try { teamDiscipline.dispose(); } catch { /* already disposed */ }
3656
3685
  try { deferredWakes.dispose(); } catch { /* already disposed */ }
3657
3686
  hostSessionGate.dispose();
3658
- // 先收完已确认的项目创建,再关闭它们可能刚打开的账本。
3659
- const closeRuntimes = Promise.allSettled([ready, ...projectActivations]).then(() =>
3687
+ // 先收完建队和会话编制操作,再关闭账本。
3688
+ const closeRuntimes = Promise.allSettled([ready, ...projectOperations]).then(() =>
3660
3689
  Promise.allSettled([...(booted?.runtimes?.values() ?? [])].map(async (runtime) => runtime.close())));
3661
3690
  const cleanup = [closeRuntimes, Promise.resolve().then(disposeSessionCommand)];
3662
3691
  for (const client of sseClients) {
@@ -371,6 +371,33 @@ export function listTeams(catalog) {
371
371
  .sort((a, b) => (a.id === DEFAULT_TEAM ? -1 : b.id === DEFAULT_TEAM ? 1 : 0) || a.source.localeCompare(b.source) || a.name.localeCompare(b.name, 'zh'));
372
372
  }
373
373
 
374
+ const PRESET_GOAL_TERMS = {
375
+ docs: ['文档', '手册', '知识库', 'readme', 'api documentation'],
376
+ content: ['公众号', '博客', '社媒', '文案', 'blog'],
377
+ education: ['课件', '教材', '题库', '教案', '复习', '课程', 'quiz'],
378
+ video: ['视频', '分镜', '剪辑', '字幕', 'video'],
379
+ game: ['小游戏', '游戏开发', '游戏原型', '游戏玩法', 'game prototype'],
380
+ };
381
+
382
+ /** 只按现有预设的交付物找候选。命中多种方向时保留候选,交给用户选。 */
383
+ export function matchTeamPresets(catalog, goal) {
384
+ const clauses = goal.normalize('NFKC').toLowerCase().split(/[,。;、!?,;!?\r\n]+/u)
385
+ .filter((clause) => !/(?:不要|不用|无需|不需要|不做|别|排除|\b(?:not|no|without|exclude)\b)/u.test(clause));
386
+ const candidates = [];
387
+ for (const team of listTeams(catalog)) {
388
+ if (!Object.hasOwn(PRESET_GOAL_TERMS, team.id) || team.broken || team.source === 'user') continue;
389
+ const terms = PRESET_GOAL_TERMS[team.id].filter((term) => {
390
+ if (/^[a-z ]+$/u.test(term)) {
391
+ const word = new RegExp(`\\b${term}\\b`, 'u');
392
+ return clauses.some((clause) => word.test(clause));
393
+ }
394
+ return clauses.some((clause) => clause.includes(term));
395
+ });
396
+ if (terms.length > 0) candidates.push({ id: team.id, name: team.name, terms });
397
+ }
398
+ return candidates;
399
+ }
400
+
374
401
  /**
375
402
  * 组队:写一个用户团队 `<userRoot>/teams/<id>/team.yml`。
376
403
  * `members` 是 [{ talent, name? }](同一人才可招多位,成员 id 自动生成且不重复),`lead` 是成员下标或成员 id(缺省第一位)。
@@ -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));
@@ -1080,15 +1081,42 @@ export class TeamService {
1080
1081
  return { member: this.state.members[member.id] };
1081
1082
  }
1082
1083
 
1083
- async leaveMember(command, payload) {
1084
- if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may move a member to the talent pool');
1084
+ describeMemberDeparture(projectId, payload, { reviewed = false } = {}) {
1085
1085
  const member = this.state.members?.[payload.memberId];
1086
1086
  if (member === undefined || member.kind !== 'agent') fail(ERRORS.NOT_FOUND, `agent ${String(payload.memberId)} not found`);
1087
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
+ });
1088
1115
  await this.append(command, 'member/left-team', { memberId: member.id, reason: payload.reason ?? '' });
1089
1116
  return {
1090
1117
  member: this.state.members[member.id],
1091
- 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 }),
1092
1120
  };
1093
1121
  }
1094
1122
 
@@ -0,0 +1,180 @@
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 调整 [项目ID] 一句话',
10
+ 人才: '/ai-team 人才 [关键词]',
11
+ 增员: '/ai-team 增员 项目ID 人才ID',
12
+ 改岗位: '/ai-team 改岗位 项目ID 成员ID 新岗位',
13
+ 离队: '/ai-team 离队 项目ID 成员ID [接手人ID]',
14
+ };
15
+
16
+ export const rosterHelp = Object.values(USAGE).join('\n');
17
+ export const isRosterAction = (action) => Object.hasOwn(USAGE, action);
18
+
19
+ function workspaceProject(runtime, workspacePath) {
20
+ const project = runtime.service.state.projects?.[runtime.id];
21
+ if (!project || project.status === 'archived' || typeof project.workspacePath !== 'string' || !isAbsolute(project.workspacePath)) return null;
22
+ try {
23
+ return realpathSync(project.workspacePath) === workspacePath ? project : null;
24
+ } catch {
25
+ return null;
26
+ }
27
+ }
28
+
29
+ const memberLabel = (member) => `${member.name}(${member.id})`;
30
+
31
+ function resolveName(entries, value, label, aliases = (entry) => [entry.name]) {
32
+ const name = value.trim();
33
+ const direct = entries.find(({ id }) => id === name);
34
+ if (direct) return direct.id;
35
+ const matches = entries.filter((entry) => aliases(entry).includes(name));
36
+ if (matches.length === 1) return matches[0].id;
37
+ if (matches.length === 0) fail(ERRORS.NOT_FOUND, `找不到${label}「${name}」,请核对名字或编号。`);
38
+ fail(ERRORS.CONFLICT, `${label}「${name}」有多个候选,请使用编号。\n${matches.map(memberLabel).join('\n')}`);
39
+ }
40
+
41
+ function readRosterSentence(sentence, runtime, catalog) {
42
+ const statement = sentence.trim().replace(/[。!!.]$/u, '');
43
+ const hint = '一句话只能准备一项调整。示例:给团队加一位文案;把校书的岗位改为文档协调;让墨痕把任务交给校书后离队。';
44
+ if (/[。;;\r\n]|(?:并|同时|然后)\s*(?:给|把|让|再|加|离队|改)/u.test(statement)) fail(ERRORS.INVALID_ARGUMENT, hint);
45
+ const hire = /^给团队加(?:一位|一名)\s*(.+)$/u.exec(statement);
46
+ if (hire) {
47
+ const target = resolveName(listTalents(catalog()), hire[1], '人才', ({ name, role }) => [name, role]);
48
+ return { action: '增员', target, value: '' };
49
+ }
50
+ const members = Object.values(runtime.service.state.members ?? {}).filter(({ kind, status }) => kind === 'agent' && status !== 'retired');
51
+ const findMember = (name) => resolveName(members, name, '成员');
52
+ const edit = /^把(.+?)的岗位改为\s*(.+)$/u.exec(statement);
53
+ if (edit) return { action: '改岗位', target: findMember(edit[1]), value: edit[2].trim() };
54
+ const handoff = /^让(.+?)把任务交给(.+?)后离队$/u.exec(statement);
55
+ if (handoff) return { action: '离队', target: findMember(handoff[1]), value: findMember(handoff[2]) };
56
+ const leave = /^让(.+?)离队$/u.exec(statement);
57
+ if (leave) return { action: '离队', target: findMember(leave[1]), value: '' };
58
+ fail(ERRORS.INVALID_ARGUMENT, hint);
59
+ }
60
+
61
+ function describeRoster(runtime, project) {
62
+ const state = runtime.service.state;
63
+ const members = Object.values(state.members ?? {}).filter((member) => member.kind === 'agent');
64
+ return [
65
+ `「${project.name}」的编制(${project.id})`,
66
+ ...members.map((member) => {
67
+ const unfinished = unfinishedTasksFor(state, member.id).length;
68
+ const role = member.role ? ` · ${member.role}` : '';
69
+ const departed = member.status === 'retired' ? ' · 已离队' : '';
70
+ return `- ${memberLabel(member)}${role}${departed} · ${unfinished} 张未收口任务`;
71
+ }),
72
+ '使用 /ai-team 人才查看可选人才。',
73
+ ].join('\n');
74
+ }
75
+
76
+ function planChange(runtime, action, target, value, catalog) {
77
+ const reason = '会话编制草稿确认';
78
+ if (action === '增员') {
79
+ const talent = catalog().talents.get(target);
80
+ if (!talent) fail(ERRORS.NOT_FOUND, '人才库中找不到该人才。使用 /ai-team 人才 查看可选人才。');
81
+ return {
82
+ type: 'member.add',
83
+ payload: {
84
+ name: talent.name, role: talent.role, duty: talent.duty,
85
+ personality: talent.personality, skills: talent.skills, avatar: talent.avatar,
86
+ talent: talent.id, talentVersion: talent.version,
87
+ },
88
+ lines: [`增员 ${talent.name} · ${talent.role}(${talent.id})`],
89
+ };
90
+ }
91
+ if (action === '改岗位') {
92
+ const member = runtime.service.state.members?.[target];
93
+ if (member?.kind !== 'agent' || member.status === 'retired') fail(ERRORS.NOT_FOUND, '同一项目中找不到这位在队成员。');
94
+ if (member.role === value) fail(ERRORS.INVALID_ARGUMENT, '该成员已经是这个岗位。');
95
+ return {
96
+ type: 'member.profile.update', payload: { memberId: target, role: value, reason },
97
+ lines: [`岗位 ${memberLabel(member)} 从「${member.role || '未设置'}」改为「${value}」`],
98
+ };
99
+ }
100
+ const payload = { memberId: target, ...(value ? { successorId: value } : {}), reason };
101
+ const { member, successor, unfinished } = runtime.service.describeMemberDeparture(runtime.id, payload, { reviewed: true });
102
+ return {
103
+ type: 'member.leave', payload,
104
+ lines: [
105
+ `离队 ${memberLabel(member)}进入人才池`,
106
+ ...(successor === null ? [] : [`接手人 ${memberLabel(successor)}`]),
107
+ ...(unfinished.length === 0 ? ['该成员没有未收口任务。'] : unfinished.map((task) => `- #${task.number} ${task.title}(${task.status})`)),
108
+ ],
109
+ taskRevisions: unfinished.map(({ id, revision }) => [id, revision]),
110
+ };
111
+ }
112
+
113
+ export function createSessionRoster({ runtimes, isAvailable, catalog, actor, disposeMemberActivation }) {
114
+ return async function prepareRoster({ action: requested, argument, workspacePath }) {
115
+ if (requested === '人才') {
116
+ const query = argument.trim().toLowerCase();
117
+ const talents = listTalents(catalog()).filter((talent) => [talent.id, talent.name, talent.role].some((value) => value.toLowerCase().includes(query)));
118
+ return { text: talents.length === 0 ? '没有匹配的人才。' : talents.map((talent) => `- ${talent.id} · ${talent.name} · ${talent.role}`).join('\n') };
119
+ }
120
+ const input = argument.trim();
121
+ const [, first, supplied, rest = ''] = /^(\S+)(?:\s+(\S+))?(?:\s+([\s\S]+))?$/.exec(input) ?? [];
122
+ const requestedSentence = requested === '调整';
123
+ const requestedProject = requestedSentence && !first?.startsWith('prj_') ? undefined : first;
124
+ if (!requestedSentence) {
125
+ const wrongTarget = requested === '编制' ? supplied !== undefined : supplied === undefined;
126
+ if (wrongTarget || (requested === '增员' && rest !== '') || (requested === '改岗位' && rest === '')
127
+ || (requested === '离队' && /\s/.test(rest))) fail(ERRORS.INVALID_ARGUMENT, `用 ${USAGE[requested]}。`);
128
+ }
129
+ const options = [];
130
+ for (const runtime of await runtimes()) {
131
+ const project = isAvailable(runtime) ? workspaceProject(runtime, workspacePath) : null;
132
+ if (project !== null) options.push({ runtime, project });
133
+ }
134
+ if (requestedProject === undefined && options.length > 1) {
135
+ const usage = requestedSentence ? '/ai-team 调整 项目ID 一句话' : '/ai-team 编制 项目ID';
136
+ return { text: [`同一工作区有多个项目,请使用 ${usage}。`, ...options.map(({ project }) => `- ${project.id} · ${project.name}`)].join('\n') };
137
+ }
138
+ const selection = requestedProject === undefined ? options[0] : options.find(({ project }) => project.id === requestedProject);
139
+ if (!selection) fail(ERRORS.NOT_FOUND, '当前会话的工作区找不到该项目。使用 /ai-team 编制 查看同一工作区的项目。');
140
+ const { runtime, project } = selection;
141
+ if (requested === '编制') return { text: describeRoster(runtime, project) };
142
+ const { action, target, value } = requestedSentence
143
+ ? readRosterSentence(requestedProject ? input.slice(first.length) : input, runtime, catalog)
144
+ : { action: requested, target: supplied, value: rest };
145
+ const projectId = project.id;
146
+
147
+ const change = planChange(runtime, action, target, value, catalog);
148
+ const command = { type: change.type, payload: change.payload, actor, projectId };
149
+ runtime.service.checkBlueprintCommand(command, change.payload);
150
+ const approved = JSON.stringify(change);
151
+ return {
152
+ projectId, action,
153
+ lines: [`编制草稿 ${project.name}(${projectId})`, ...change.lines],
154
+ async apply(draftId) {
155
+ const result = await runtime.service.dispatch({
156
+ ...command, correlationId: draftId,
157
+ verifyDraft() {
158
+ const currentProject = isAvailable(runtime) ? workspaceProject(runtime, workspacePath) : null;
159
+ if (!currentProject || currentProject.name !== project.name) {
160
+ fail(ERRORS.REVISION, '项目或工作目录已变化,请重新生成草稿。');
161
+ }
162
+ let current;
163
+ try {
164
+ current = planChange(runtime, action, target, value, catalog);
165
+ } catch (error) {
166
+ if (error instanceof DomainError) fail(ERRORS.REVISION, `${error.message} 请核对编制后重新生成草稿。`);
167
+ throw error;
168
+ }
169
+ if (JSON.stringify(current) !== approved) fail(ERRORS.REVISION, '成员、人才或任务已变化,请重新生成草稿。');
170
+ },
171
+ });
172
+ if (action === '离队') {
173
+ await disposeMemberActivation(runtime, target, command.type);
174
+ return `已将${memberLabel(result.member)}移入人才池,交接了 ${result.transferredTasks?.length ?? 0} 张原任务。`;
175
+ }
176
+ return action === '增员' ? `已添加${memberLabel(result.member)}。` : `已将${memberLabel(result.member)}的岗位更新为「${result.member.role}」。`;
177
+ },
178
+ };
179
+ };
180
+ }
@@ -1,85 +1,113 @@
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
- }
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 或 --recommend。按草稿中的命令确认或取消。\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 recommend = /^--recommend(?:\s|$)/.test(argument);
52
+ const goal = (recommend ? argument.slice('--recommend'.length) : selected?.[2] ?? argument).trim();
53
+ if (goal === '' || (!selected && argument.startsWith('--team'))) return { kind: 'error', text: HELP };
54
+ const input = { name: goal.split(/\r?\n/, 1)[0], goal, workspacePath, team: selected?.[1] ?? '', recommend };
55
+ const proposed = prepare(input);
56
+ const id = ids.project();
57
+ const signature = presetSignature(proposed.teamPreset);
58
+ return preview(session, workspacePath, {
59
+ id, action,
60
+ details: { preset: proposed.teamPreset.id, members: proposed.teamPreset.team.members.length },
61
+ lines: [
62
+ `建队草稿 ${input.name}`,
63
+ `目标 ${goal}`,
64
+ `工作目录 ${workspacePath}`,
65
+ `预设 ${proposed.teamPreset.team.name}(${proposed.teamPreset.id})`,
66
+ ...(proposed.matchedTerms ? [`匹配依据 ${proposed.matchedTerms.join('、')}`] : []),
67
+ ...proposed.teamPreset.team.members.map((member) => `- ${member.name} · ${member.role}`),
68
+ '确认后创建项目,PMO 自动为关闭状态。',
69
+ ],
70
+ async apply() {
71
+ let approved;
72
+ try {
73
+ approved = prepare(input);
74
+ } catch (error) {
75
+ if (error instanceof DomainError) fail(ERRORS.REVISION, '团队预设已更新,请重新生成草稿后再确认。');
76
+ throw error;
77
+ }
78
+ if (presetSignature(approved.teamPreset) !== signature) {
79
+ fail(ERRORS.REVISION, '团队预设已更新,请重新生成草稿后再确认。');
80
+ }
81
+ const project = await create(id, approved);
82
+ return `已创建「${project.name}」(${project.id})。可在文渊阁查看团队,准备好后开启 PMO 自动。`;
83
+ },
84
+ });
85
+ }
86
+ if (!existing || argument.trim() !== existing.id || workspacePath !== existing.workspacePath) {
87
+ return { kind: 'error', text: '当前会话和工作区没有这份草稿。请在这里重新生成。' };
88
+ }
89
+ if (action === '取消') {
90
+ if (existing.pending || existing.result) return { kind: 'error', text: '这份草稿已经确认。' };
91
+ drafts.delete(session);
92
+ diag.append({ ev: 'session.team.cancelled', projectId: existing.projectId, action: existing.action });
93
+ return { kind: 'success', text: existing.action === '建队' ? '已取消建队草稿。' : '已取消编制草稿。' };
94
+ }
95
+ if (existing.result) return existing.result;
96
+ if (existing.pending) return await existing.pending;
97
+ existing.pending = existing.apply(existing.id).then((text) => {
98
+ const result = { kind: 'success', text };
99
+ existing.result = result;
100
+ diag.append({ ev: 'session.team.confirmed', projectId: existing.projectId, action: existing.action });
101
+ return result;
102
+ }).catch((error) => {
103
+ if (error instanceof DomainError && error.code === ERRORS.REVISION) drafts.delete(session);
104
+ throw error;
105
+ }).finally(() => { existing.pending = null; });
106
+ return await existing.pending;
107
+ } catch (error) {
108
+ diag.append({ ev: 'session.team.fail', code: error?.code ?? 'E_RUNTIME', message: error?.message ?? String(error) });
109
+ return { kind: 'error', text: error instanceof DomainError ? error.message : '文渊阁暂未能完成操作。可在相同会话中重试。' };
110
+ }
111
+ },
112
+ };
113
+ }
@@ -1,109 +1,109 @@
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
- }
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
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@suifei/dsh-ai-team",
3
- "version": "0.4.155",
3
+ "version": "0.4.157",
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",