@suifei/dsh-ai-team 0.4.79 → 0.4.82

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/client.js CHANGED
@@ -268,6 +268,11 @@ window.__ModuleLoader__.load({
268
268
  presetCordis: '创造模式',
269
269
  memberProvider: '模型提供商',
270
270
  memberModel: '模型',
271
+ memberReasoning: '推理等级',
272
+ memberReasoningDefault: '跟随模型默认',
273
+ memberReasoningNone: '该模型没有声明推理档位;在 DSH 提供商设置里为它配置 reasoningEfforts 后,这里才会出现可选档位',
274
+ memberReasoningError: '推理等级读取失败:{message}',
275
+ memberReasoningAsk: '为 {model} 选择推理等级',
271
276
  memberProviderDefault: '跟随系统默认',
272
277
  memberModelDefault: '跟随系统默认',
273
278
  memberNoProviders: 'DSH 暂未提供可用模型',
@@ -680,6 +685,11 @@ window.__ModuleLoader__.load({
680
685
  presetCordis: 'Creative',
681
686
  memberProvider: 'Model provider',
682
687
  memberModel: 'Model',
688
+ memberReasoning: 'Reasoning',
689
+ memberReasoningDefault: 'Model default',
690
+ memberReasoningNone: 'This model declares no reasoning levels; add reasoningEfforts for it in the DSH provider settings to enable this selector',
691
+ memberReasoningError: 'Could not read reasoning levels: {message}',
692
+ memberReasoningAsk: 'Pick a reasoning level for {model}',
683
693
  memberProviderDefault: 'Follow system default',
684
694
  memberModelDefault: 'Follow system default',
685
695
  memberNoProviders: 'DSH exposes no models yet',
@@ -2491,8 +2501,61 @@ window.__ModuleLoader__.load({
2491
2501
  }
2492
2502
  }
2493
2503
 
2494
- function ModelFields({ t, catalog, provider, model, onProvider, onModel, error }) {
2504
+ function ModelFields({ t, catalog, provider, model, effort, onEffort, onProvider, onModel, error }) {
2495
2505
  const providers = Array.isArray(catalog?.providers) ? catalog.providers.slice() : [];
2506
+ // 推理等级按「提供商 + 模型」按需解析:不同模型支持的档位不同,宿主也随时可能
2507
+ // 换适配器,写死一份档位表必然漂移。查不到(服务/适配器报错)与「该模型没有档位」
2508
+ // 分开提示,前者不该让用户以为模型不支持推理。
2509
+ const [efforts, setEfforts] = React.useState(null);
2510
+ const [effortsError, setEffortsError] = React.useState('');
2511
+ const [effortsLoading, setEffortsLoading] = React.useState(false);
2512
+ React.useEffect(() => {
2513
+ let alive = true;
2514
+ const routeProvider = provider.trim();
2515
+ const routeModel = model.trim();
2516
+ if (routeProvider === '' || routeModel === '') {
2517
+ setEfforts(null);
2518
+ setEffortsError('');
2519
+ setEffortsLoading(false);
2520
+ return () => { alive = false; };
2521
+ }
2522
+ setEffortsLoading(true);
2523
+ const query = '?provider=' + encodeURIComponent(routeProvider) + '&model=' + encodeURIComponent(routeModel);
2524
+ fetch('/ai-team/api/model-efforts' + query, { headers: { accept: 'application/json' } })
2525
+ .then(async (response) => {
2526
+ const body = await response.json().catch(() => null);
2527
+ if (!response.ok) throw new Error(body?.error?.message ?? ('HTTP ' + response.status));
2528
+ return body;
2529
+ })
2530
+ .then((body) => {
2531
+ if (!alive) return;
2532
+ // 端点用 ok:false 表达「查不到」:不能当成「该模型没有档位」,否则用户
2533
+ // 会以为模型不支持推理,而实际是适配器没回答。
2534
+ if (body !== null && typeof body === 'object' && body.ok === false) {
2535
+ throw new Error(body?.error?.message ?? t('memberReasoningError'));
2536
+ }
2537
+ setEfforts({ efforts: Array.isArray(body?.efforts) ? body.efforts : [], defaultEffort: body?.defaultEffort ?? null });
2538
+ setEffortsError('');
2539
+ })
2540
+ .catch((cause) => {
2541
+ if (!alive) return;
2542
+ setEfforts({ efforts: [], defaultEffort: null });
2543
+ setEffortsError(cause?.message ?? String(cause));
2544
+ })
2545
+ .finally(() => { if (alive) setEffortsLoading(false); });
2546
+ return () => { alive = false; };
2547
+ }, [provider, model]);
2548
+ const availableEfforts = Array.isArray(efforts?.efforts) ? efforts.efforts : [];
2549
+ const effortOptions = availableEfforts.slice();
2550
+ // 账本里已有的档位若不在当前列表(模型换过/宿主改了档位),保留它以免静默改写。
2551
+ if (typeof effort === 'string' && effort !== '' && !effortOptions.some((entry) => entry.id === effort)) {
2552
+ effortOptions.push({ id: effort, name: effort });
2553
+ }
2554
+ const effortHint = effortsError
2555
+ ? tf(t, 'memberReasoningError', { message: effortsError })
2556
+ : efforts !== null && availableEfforts.length === 0 && effortsLoading === false
2557
+ ? t('memberReasoningNone')
2558
+ : '';
2496
2559
  if (provider !== '' && !providers.some((entry) => entry.id === provider)) {
2497
2560
  providers.unshift({ id: provider, name: provider, models: model === '' ? [] : [{ id: model, name: model }], modelCount: model === '' ? 0 : 1 });
2498
2561
  }
@@ -2529,7 +2592,9 @@ window.__ModuleLoader__.load({
2529
2592
  h('label', { className: 'at-field' }, h('span', null, t('memberProvider')),
2530
2593
  h('select', { value: provider, onChange: chooseProvider },
2531
2594
  h('option', { value: '' }, t('memberProviderDefault')),
2532
- providers.map((entry) => h('option', { key: entry.id, value: entry.id }, entry.name + (entry.modelCount ? ' · ' + entry.modelCount : ''))))),
2595
+ providers.map((entry) => h('option', { key: entry.id, value: entry.id }, entry.name + (entry.modelCount ? ' · ' + entry.modelCount : ''))),
2596
+ )
2597
+ ),
2533
2598
  h('label', { className: 'at-field' }, h('span', null, t('memberModel')),
2534
2599
  h('select', {
2535
2600
  value: model,
@@ -2537,8 +2602,22 @@ window.__ModuleLoader__.load({
2537
2602
  onChange: (event) => onModel(event.target.value),
2538
2603
  },
2539
2604
  h('option', { value: '' }, t('memberModelDefault')),
2540
- models.map((entry) => h('option', { key: entry.id, value: entry.id }, entry.name === entry.id ? entry.id : entry.name + ' · ' + entry.id))))),
2541
- hint ? h('div', { className: 'at-fieldhint' }, hint) : null);
2605
+ models.map((entry) => h('option', { key: entry.id, value: entry.id }, entry.name === entry.id ? entry.id : entry.name + ' · ' + entry.id)),
2606
+ )
2607
+ ),
2608
+ h('label', { className: 'at-field' }, h('span', null, t('memberReasoning')),
2609
+ h('select', {
2610
+ value: typeof effort === 'string' ? effort : '',
2611
+ disabled: provider === '' || model === '' || effortsLoading,
2612
+ onChange: (event) => onEffort(event.target.value),
2613
+ },
2614
+ h('option', { value: '' }, t('memberReasoningDefault')),
2615
+ effortOptions.map((entry) => h('option', { key: entry.id, value: entry.id }, entry.name === entry.id ? entry.id : entry.name + ' · ' + entry.id)),
2616
+ )
2617
+ )
2618
+ ),
2619
+ hint ? h('div', { className: 'at-fieldhint' }, hint) : null,
2620
+ effortHint ? h('div', { className: 'at-fieldhint' }, effortHint) : null);
2542
2621
  }
2543
2622
 
2544
2623
  function Workbench({ t, ctx }) {
@@ -2572,6 +2651,7 @@ window.__ModuleLoader__.load({
2572
2651
  const [mRole, setMRole] = React.useState('');
2573
2652
  const [mPrompt, setMPrompt] = React.useState('');
2574
2653
  const [mProvider, setMProvider] = React.useState('');
2654
+ const [mEffort, setMEffort] = React.useState('');
2575
2655
  const [mModel, setMModel] = React.useState('');
2576
2656
  const [modelCatalog, setModelCatalog] = React.useState(null);
2577
2657
  const [modelCatalogError, setModelCatalogError] = React.useState('');
@@ -2586,6 +2666,7 @@ window.__ModuleLoader__.load({
2586
2666
  const [pProvider, setPProvider] = React.useState('');
2587
2667
  const [pModel, setPModel] = React.useState('');
2588
2668
  const [pMaxTokens, setPMaxTokens] = React.useState('');
2669
+ const [pEffort, setPEffort] = React.useState('');
2589
2670
  const [pNote, setPNote] = React.useState('');
2590
2671
  const [pSkill, setPSkill] = React.useState('');
2591
2672
  const [pMessage, setPMessage] = React.useState('');
@@ -3032,7 +3113,23 @@ window.__ModuleLoader__.load({
3032
3113
  const pickedIndex = labels.indexOf(picked);
3033
3114
  const target = values[pickedIndex >= 0 ? pickedIndex : 0];
3034
3115
  if (target === undefined) return;
3035
- const patch = { provider: target.providerId, model: target.model };
3116
+ // 该模型若支持推理等级,顺带让用户挑一档;读不到档位就保持模型默认,不阻断改模型。
3117
+ let effort = '';
3118
+ try {
3119
+ const effortsQuery = '?provider=' + encodeURIComponent(target.providerId) + '&model=' + encodeURIComponent(target.model);
3120
+ const effortsResponse = await fetch('/ai-team/api/model-efforts' + effortsQuery, { headers: { accept: 'application/json' } });
3121
+ const effortsBody = await effortsResponse.json().catch(() => null);
3122
+ const effortRows = Array.isArray(effortsBody?.efforts) ? effortsBody.efforts : [];
3123
+ if (effortRows.length > 0) {
3124
+ const effortLabels = [t('memberReasoningDefault')].concat(effortRows.map((entry) => (entry.name === entry.id ? entry.id : entry.name + ' · ' + entry.id)));
3125
+ const pickedEffort = await askPrompt(tf(t, 'memberReasoningAsk', { model: target.modelName ?? target.model }), { options: effortLabels });
3126
+ if (pickedEffort !== null) {
3127
+ const effortIndex = effortLabels.indexOf(pickedEffort) - 1;
3128
+ if (effortIndex >= 0 && effortRows[effortIndex] !== undefined) effort = effortRows[effortIndex].id;
3129
+ }
3130
+ }
3131
+ } catch { /* 读不到档位时按模型默认走 */ }
3132
+ const patch = { provider: target.providerId, model: target.model, ...(effort === '' ? {} : { reasoningEffort: effort }) };
3036
3133
  let done = 0; let failed = 0;
3037
3134
  for (const row of person.projects ?? []) {
3038
3135
  const memberIds = Array.isArray(row.memberIds) ? row.memberIds : [];
@@ -3368,6 +3465,7 @@ window.__ModuleLoader__.load({
3368
3465
  setMPrompt('');
3369
3466
  setMProvider(defaults.provider ?? '');
3370
3467
  setMModel(defaults.model ?? '');
3468
+ setMEffort(defaults.reasoningEffort ?? '');
3371
3469
  setMOwner((data?.agents ?? []).length === 0);
3372
3470
  setMError('');
3373
3471
  setAddOpen(true);
@@ -3390,6 +3488,7 @@ window.__ModuleLoader__.load({
3390
3488
  patch: {
3391
3489
  ...(mProvider.trim() ? { provider: mProvider.trim() } : {}),
3392
3490
  ...(mModel.trim() ? { model: mModel.trim() } : {}),
3491
+ ...(mEffort.trim() ? { reasoningEffort: mEffort.trim() } : {}),
3393
3492
  },
3394
3493
  reason: 'workbench add member',
3395
3494
  });
@@ -3471,6 +3570,7 @@ window.__ModuleLoader__.load({
3471
3570
  setPProvider(agent.config?.provider ?? '');
3472
3571
  setPModel(agent.config?.model ?? '');
3473
3572
  setPMaxTokens(agent.config?.maxTokens ?? '');
3573
+ setPEffort(agent.config?.reasoningEffort ?? '');
3474
3574
  setPNote('');
3475
3575
  setPSkill('');
3476
3576
  setPMessage('');
@@ -3495,6 +3595,9 @@ window.__ModuleLoader__.load({
3495
3595
  if (pPreset !== (config.preset ?? profileAgent.preset ?? 'standard')) patch.preset = pPreset;
3496
3596
  if (pProvider.trim() !== (config.provider ?? '')) patch.provider = pProvider.trim();
3497
3597
  if (pModel.trim() !== (config.model ?? '')) patch.model = pModel.trim();
3598
+ // 空串 = 跟随模型默认,显式写 null 才能真正清掉账本里的旧档位。
3599
+ const nextEffort = pEffort.trim();
3600
+ if (nextEffort !== (config.reasoningEffort ?? '')) patch.reasoningEffort = nextEffort === '' ? null : nextEffort;
3498
3601
  const maxTokens = Number(pMaxTokens);
3499
3602
  if (Number.isSafeInteger(maxTokens) && maxTokens > 0 && maxTokens !== config.maxTokens) patch.maxTokens = maxTokens;
3500
3603
  if (Object.keys(patch).length > 0) {
@@ -4294,6 +4397,8 @@ window.__ModuleLoader__.load({
4294
4397
  t,
4295
4398
  catalog: modelCatalog,
4296
4399
  provider: mProvider,
4400
+ effort: mEffort,
4401
+ onEffort: setMEffort,
4297
4402
  model: mModel,
4298
4403
  onProvider: setMProvider,
4299
4404
  onModel: setMModel,
@@ -4351,6 +4456,8 @@ window.__ModuleLoader__.load({
4351
4456
  t,
4352
4457
  catalog: modelCatalog,
4353
4458
  provider: pProvider,
4459
+ effort: pEffort,
4460
+ onEffort: setPEffort,
4354
4461
  model: pModel,
4355
4462
  onProvider: setPProvider,
4356
4463
  onModel: setPModel,
@@ -4485,4 +4592,4 @@ window.__ModuleLoader__.load({
4485
4592
 
4486
4593
  return { inject: ['slots', 'locale'], apply };
4487
4594
  },
4488
- });
4595
+ });
package/index.js CHANGED
@@ -45,7 +45,7 @@ import { collectReview, startReview } from './lib/skillopt/review-runner.js';
45
45
  import { REVIEWER_NAME } from './lib/skillopt/reviewer.js';
46
46
  import { createMemberPermissionGuard } from './lib/host/permission-guard.js';
47
47
  import { installFaultAdapter } from './lib/host/fault-adapter.js';
48
- import { buildModelCatalog } from './lib/host/model-catalog.js';
48
+ import { buildModelCatalog, buildModelEfforts } from './lib/host/model-catalog.js';
49
49
  import { createTeamTool } from './lib/host/member-tools.js';
50
50
  import { describeTaskContext, describeWake, planWakes } from './lib/host/waker.js';
51
51
  import { describeCauseChain } from './lib/runtime/error-chain.js';
@@ -407,12 +407,21 @@ export function apply(ctx, config = {}) {
407
407
  if (typeof sessionId !== 'string' || sessionId === '') return;
408
408
  if (typeof selection?.provider !== 'string' || selection.provider === ''
409
409
  || typeof selection?.model !== 'string' || selection.model === '') return;
410
- const route = `${selection.provider}/${selection.model}`;
410
+ // 推理等级也要记:只写 provider/model 会让下一轮回到模型默认档(实机:
411
+ // 创建时 max,追加这条事件后第二次请求变成 high)。
412
+ const effort = typeof selection.reasoningEffort === 'string' && selection.reasoningEffort !== ''
413
+ ? selection.reasoningEffort
414
+ : null;
415
+ const route = `${selection.provider}/${selection.model}` + (effort === null ? '' : `#${effort}`);
411
416
  if (modelSelectionLogged.get(sessionId) === route) return;
412
417
  try {
413
418
  const session = serviceOf(ctx, 'sessions')?.get?.(sessionId);
414
419
  if (session === undefined || session === null || typeof session.append !== 'function') return;
415
- session.append('model/selection', { provider: selection.provider, model: selection.model });
420
+ session.append('model/selection', {
421
+ provider: selection.provider,
422
+ model: selection.model,
423
+ ...(effort === null ? {} : { reasoningEffort: effort }),
424
+ });
416
425
  modelSelectionLogged.set(sessionId, route);
417
426
  diag.append({ ev: 'model.selection', sessionId, route, label: label ?? null });
418
427
  } catch (error) {
@@ -2064,6 +2073,15 @@ export function apply(ctx, config = {}) {
2064
2073
  const catalog = await buildModelCatalog(serviceOf(ctx, 'llm'), serviceOf(ctx, 'agentDefaultModel'));
2065
2074
  return send(res, catalog);
2066
2075
  }
2076
+ // 成员模型配置的「推理等级」选项:按选定路由按需解析(目录接口不承担这个成本)。
2077
+ if (req.method === 'GET' && url.pathname === '/ai-team/api/model-efforts') {
2078
+ const efforts = await buildModelEfforts(
2079
+ serviceOf(ctx, 'llm'),
2080
+ url.searchParams.get('provider') ?? '',
2081
+ url.searchParams.get('model') ?? '',
2082
+ );
2083
+ return send(res, efforts, efforts.ok ? 200 : (efforts.error?.code === 'E_INVALID_ARGUMENT' ? 400 : 200));
2084
+ }
2067
2085
  // R-17 person 别名:视图层绑定(name → personId),文件存策略数据
2068
2086
  // 目录;聚合时别名生效,未绑定回落同名聚合(可回退路径)。
2069
2087
  const aliasesPath = join(booted.dataDir, 'people-aliases.json');
@@ -1,85 +1,129 @@
1
- /**
2
- * Read the model directory from the live DSH `llm` service. The workbench must
3
- * never ask the user to type provider/model ids: those ids already exist in the
4
- * Host and can change when accounts/adapters are configured.
5
- */
6
-
7
- function safeDefault(agentDefaultModel) {
8
- try {
9
- const selection = agentDefaultModel?.currentSelection?.();
10
- if (selection === null || typeof selection !== 'object') return null;
11
- if (typeof selection.provider !== 'string' || typeof selection.model !== 'string') return null;
12
- return { provider: selection.provider, model: selection.model };
13
- } catch {
14
- return null;
15
- }
16
- }
17
-
18
- function modelRows(models) {
19
- const seen = new Set();
20
- const rows = [];
21
- for (const model of Array.isArray(models) ? models : []) {
22
- if (model === null || typeof model !== 'object' || typeof model.id !== 'string' || model.id === '') continue;
23
- if (seen.has(model.id)) continue;
24
- seen.add(model.id);
25
- rows.push({
26
- id: model.id,
27
- name: typeof model.name === 'string' && model.name !== '' ? model.name : model.id,
28
- ...(typeof model.description === 'string' && model.description !== '' ? { description: model.description } : {}),
29
- ...(Array.isArray(model.inputModalities) ? { inputModalities: model.inputModalities } : {}),
30
- });
31
- }
32
- return rows;
33
- }
34
-
35
- /**
36
- * @param {any} llm live DSH llm service
37
- * @param {any} agentDefaultModel live DSH default-model service
38
- */
39
- export async function buildModelCatalog(llm, agentDefaultModel) {
40
- const defaultModel = safeDefault(agentDefaultModel);
41
- if (llm === undefined || llm === null || typeof llm.listProviders !== 'function') {
42
- return {
43
- ok: false,
44
- defaultModel,
45
- providers: [],
46
- error: { code: 'E_RUNTIME_UNAVAILABLE', message: 'the DSH llm service is unavailable' },
47
- };
48
- }
49
- let providers;
50
- try {
51
- providers = llm.listProviders();
52
- } catch (error) {
53
- return {
54
- ok: false,
55
- defaultModel,
56
- providers: [],
57
- error: { code: 'E_MODEL_DIRECTORY', message: error?.message ?? String(error) },
58
- };
59
- }
60
- const rows = await Promise.all((Array.isArray(providers) ? providers : []).map(async (provider) => {
61
- const id = typeof provider?.id === 'string' ? provider.id : '';
62
- const name = typeof provider?.name === 'string' && provider.name !== '' ? provider.name : id;
63
- if (id === '') return null;
64
- try {
65
- const models = modelRows(await llm.listModels(id));
66
- return { id, name, models, modelCount: models.length };
67
- } catch (error) {
68
- return {
69
- id,
70
- name,
71
- models: [],
72
- modelCount: 0,
73
- error: error?.message ?? String(error),
74
- };
75
- }
76
- }));
77
- const available = rows.filter((row) => row !== null);
78
- return {
79
- ok: true,
80
- defaultModel,
81
- providers: available,
82
- providerCount: available.length,
83
- modelCount: available.reduce((total, row) => total + row.models.length, 0),
84
- };
85
- }
1
+ /**
2
+ * Read the model directory from the live DSH `llm` service. The workbench must
3
+ * never ask the user to type provider/model ids: those ids already exist in the
4
+ * Host and can change when accounts/adapters are configured.
5
+ */
6
+
7
+ function safeDefault(agentDefaultModel) {
8
+ try {
9
+ const selection = agentDefaultModel?.currentSelection?.();
10
+ if (selection === null || typeof selection !== 'object') return null;
11
+ if (typeof selection.provider !== 'string' || typeof selection.model !== 'string') return null;
12
+ // 宿主默认选择自身也可能带推理等级;没有就不写这个键,客户端据此回退「跟随默认」。
13
+ const effort = selection.reasoningEffort ?? selection.reasoning?.effort ?? null;
14
+ return {
15
+ provider: selection.provider,
16
+ model: selection.model,
17
+ ...(typeof effort === 'string' && effort !== '' ? { reasoningEffort: effort } : {}),
18
+ };
19
+ } catch {
20
+ return null;
21
+ }
22
+ }
23
+
24
+ /**
25
+ * 读取一个 provider/model 路由支持的推理等级(DSH `llm.resolveModelInfo().reasoning`)。
26
+ *
27
+ * 只在用户选定「提供商 + 模型」之后按需调用:`/api/models` 列目录时逐个解析会把
28
+ * 目录接口拖成 N 次适配器往返。返回 `ok:false` 表示**查不到**(服务缺失/适配器报错),
29
+ * 与 `ok:true, efforts: []`(模型确实没有推理等级)是两件事,界面提示也不同。
30
+ */
31
+ export async function buildModelEfforts(llm, provider, model) {
32
+ const route = { provider: typeof provider === 'string' ? provider.trim() : '', model: typeof model === 'string' ? model.trim() : '' };
33
+ if (route.provider === '' || route.model === '') {
34
+ return { ok: false, ...route, efforts: [], defaultEffort: null, error: { code: 'E_INVALID_ARGUMENT', message: 'provider and model are required' } };
35
+ }
36
+ if (llm === undefined || llm === null || typeof llm.resolveModelInfo !== 'function') {
37
+ return { ok: false, ...route, efforts: [], defaultEffort: null, error: { code: 'E_RUNTIME_UNAVAILABLE', message: 'the DSH llm service is unavailable' } };
38
+ }
39
+ let info;
40
+ try {
41
+ info = await llm.resolveModelInfo(route.provider, route.model);
42
+ } catch (error) {
43
+ return { ok: false, ...route, efforts: [], defaultEffort: null, error: { code: 'E_MODEL_EFFORTS', message: error?.message ?? String(error) } };
44
+ }
45
+ const reasoning = info?.reasoning;
46
+ const seen = new Set();
47
+ const efforts = [];
48
+ for (const effort of Array.isArray(reasoning?.efforts) ? reasoning.efforts : []) {
49
+ const id = typeof effort?.id === 'string' ? effort.id : '';
50
+ if (id === '' || seen.has(id)) continue;
51
+ seen.add(id);
52
+ efforts.push({
53
+ id,
54
+ name: typeof effort?.name === 'string' && effort.name !== '' ? effort.name : id,
55
+ ...(typeof effort?.description === 'string' && effort.description !== '' ? { description: effort.description } : {}),
56
+ });
57
+ }
58
+ const defaultEffort = typeof reasoning?.defaultEffort === 'string' && reasoning.defaultEffort !== '' ? reasoning.defaultEffort : null;
59
+ return { ok: true, ...route, efforts, defaultEffort };
60
+ }
61
+
62
+ function modelRows(models) {
63
+ const seen = new Set();
64
+ const rows = [];
65
+ for (const model of Array.isArray(models) ? models : []) {
66
+ if (model === null || typeof model !== 'object' || typeof model.id !== 'string' || model.id === '') continue;
67
+ if (seen.has(model.id)) continue;
68
+ seen.add(model.id);
69
+ rows.push({
70
+ id: model.id,
71
+ name: typeof model.name === 'string' && model.name !== '' ? model.name : model.id,
72
+ ...(typeof model.description === 'string' && model.description !== '' ? { description: model.description } : {}),
73
+ ...(Array.isArray(model.inputModalities) ? { inputModalities: model.inputModalities } : {}),
74
+ });
75
+ }
76
+ return rows;
77
+ }
78
+
79
+ /**
80
+ * @param {any} llm live DSH llm service
81
+ * @param {any} agentDefaultModel live DSH default-model service
82
+ */
83
+ export async function buildModelCatalog(llm, agentDefaultModel) {
84
+ const defaultModel = safeDefault(agentDefaultModel);
85
+ if (llm === undefined || llm === null || typeof llm.listProviders !== 'function') {
86
+ return {
87
+ ok: false,
88
+ defaultModel,
89
+ providers: [],
90
+ error: { code: 'E_RUNTIME_UNAVAILABLE', message: 'the DSH llm service is unavailable' },
91
+ };
92
+ }
93
+ let providers;
94
+ try {
95
+ providers = llm.listProviders();
96
+ } catch (error) {
97
+ return {
98
+ ok: false,
99
+ defaultModel,
100
+ providers: [],
101
+ error: { code: 'E_MODEL_DIRECTORY', message: error?.message ?? String(error) },
102
+ };
103
+ }
104
+ const rows = await Promise.all((Array.isArray(providers) ? providers : []).map(async (provider) => {
105
+ const id = typeof provider?.id === 'string' ? provider.id : '';
106
+ const name = typeof provider?.name === 'string' && provider.name !== '' ? provider.name : id;
107
+ if (id === '') return null;
108
+ try {
109
+ const models = modelRows(await llm.listModels(id));
110
+ return { id, name, models, modelCount: models.length };
111
+ } catch (error) {
112
+ return {
113
+ id,
114
+ name,
115
+ models: [],
116
+ modelCount: 0,
117
+ error: error?.message ?? String(error),
118
+ };
119
+ }
120
+ }));
121
+ const available = rows.filter((row) => row !== null);
122
+ return {
123
+ ok: true,
124
+ defaultModel,
125
+ providers: available,
126
+ providerCount: available.length,
127
+ modelCount: available.reduce((total, row) => total + row.models.length, 0),
128
+ };
129
+ }
@@ -1,174 +1,182 @@
1
- /**
2
- * Resolve the parent Agent that owns member activations.
3
- *
4
- * Preference order:
5
- * 1. an existing live root Agent (the Human's current session);
6
- * 2. a lazily created Team Host Agent (the Human owner has no
7
- * session, e.g. the workbench was opened without a chat).
8
- *
9
- * The Host Agent is a runtime root, not a product member: it owns no Task,
10
- * has no product decision power.
11
- *
12
- * IMPORTANT — the Host Agent must never be archived. Members are subagent
13
- * descendants of it, and `archived-session-gate` (dsh-api-session-controller)
14
- * rejects every `agent/pre-step` whose Session, or any Session above it in the
15
- * subagent lineage, is archived. The loop then ends the turn as
16
- * `{kind:'blocked'}` **without issuing a model request**, so archiving the host
17
- * silently disables the whole team (observed: 453 blocked turns, 0 completed).
18
- * Earlier revisions archived it to hide it from the session list; that is
19
- * repaired here by unarchiving on resolve.
20
- */
21
- import { randomUUID } from 'node:crypto';
22
- import { reportFail } from '../diaglog.js';
23
-
24
- /** Windows 路径大小写不敏感,末尾分隔符也不该影响判定。 */
25
- const samePath = (left, right) => {
26
- const norm = (value) => String(value).replace(/[\\/]+$/, '').replace(/\\/g, '/').toLowerCase();
27
- return norm(left) === norm(right);
28
- };
29
-
30
- export class HostAgentError extends Error {
31
- constructor(code, message, details = {}) {
32
- super(message);
33
- this.name = 'HostAgentError';
34
- this.code = code;
35
- this.details = details;
36
- }
37
- }
38
-
39
- /**
40
- * @param {{
41
- * agents: any,
42
- * agentDefaultModel: any,
43
- * workspaceRegistry?: any,
44
- * sessions?: any,
45
- * cwd: string,
46
- * newSessionId?: () => string
47
- * }} options
48
- */
49
- export async function ensureHostAgent(options) {
50
- const agents = options.agents;
51
- if (agents === undefined || typeof agents.create !== 'function') {
52
- throw new HostAgentError('E_RUNTIME_UNAVAILABLE', 'agents service is unavailable');
53
- }
54
- // Repair a Host Agent archived by an earlier revision: the archive gate
55
- // covers the host's whole subagent lineage, so every member turn would end
56
- // blocked before any model request. `unarchiveSession` resolves without
57
- // writing when the id is not archived, so no read-back is needed — and
58
- // gating on the undocumented `archivedSessionIds` accessor is what silently
59
- // skipped this repair before.
60
- const unarchiveHost = async (sessionId) => {
61
- const registry = options.workspaceRegistry;
62
- if (typeof registry?.unarchiveSession !== 'function') return;
63
- try {
64
- await registry.unarchiveSession(sessionId);
65
- } catch (error) {
66
- reportFail('host.unarchive.fail', { sessionId: sessionId ?? null }, '[ai-team] could not unarchive Team Host session: ' + (error?.message ?? error));
67
- }
68
- };
69
- // Persist the resolved route into the session log. Live AgentOptions die
70
- // with the process; without a recorded selection a restored session renders
71
- // prompts with an unresolvable {{model}} variable.
72
- const persistSelection = (sessionId, selection) => {
73
- try {
74
- const session = options.sessions?.get?.(sessionId);
75
- if (session === undefined || session === null || typeof session.append !== 'function') return;
76
- if (typeof selection?.provider !== 'string' || typeof selection?.model !== 'string') return;
77
- session.append('model/selection', { provider: selection.provider, model: selection.model });
78
- } catch (error) {
79
- reportFail('host.model.persist.fail', {}, '[ai-team] host model selection persist failed: ' + (error?.message ?? error));
80
- }
81
- };
82
- if (typeof options.resumeSessionId === 'string' && options.resumeSessionId !== '') {
83
- const live = typeof agents.get === 'function' ? agents.get(options.resumeSessionId) : undefined;
84
- if (live !== undefined) {
85
- await unarchiveHost(options.resumeSessionId);
86
- const selection = typeof options.agentDefaultModel?.currentSelection === 'function' ? options.agentDefaultModel.currentSelection() : null;
87
- persistSelection(options.resumeSessionId, selection);
88
- return { agent: live, created: false, resumed: true, sessionId: options.resumeSessionId, dispose: async () => {} };
89
- }
90
- try {
91
- const handle = await agents.resume({ resumeSessionId: options.resumeSessionId });
92
- await unarchiveHost(options.resumeSessionId);
93
- // 持久化的 host 会话保留着**创建时的 cwd**,而成员子会话会继承它。
94
- // 实机事故:2026-11-09 建的 host 记的是 `…/.dsh/ai-team/default`,于是
95
- // 30 个成员会话全在插件数据目录里干活,`workspace.attachSession` 每天被拒
96
- // 上百次。cwd 不一致时不能复用这条 host——释放它,落到下面的创建分支。
97
- const expectedCwd = typeof options.cwd === 'string' ? options.cwd.trim() : '';
98
- const actualCwd = handle?.agent?.session?.header?.cwd ?? options.sessions?.get?.(options.resumeSessionId)?.header?.cwd ?? null;
99
- if (expectedCwd !== '' && typeof actualCwd === 'string' && actualCwd !== ''
100
- && samePath(actualCwd, expectedCwd) === false) {
101
- try { await handle.dispose?.(); } catch { /* already gone */ }
102
- reportFail(
103
- 'host.resume.cwd-mismatch.fail',
104
- { sessionId: options.resumeSessionId, expectedCwd, actualCwd },
105
- '[ai-team] Team Host session cwd does not match the project workspace; creating a fresh host',
106
- );
107
- } else {
108
- const selection = typeof options.agentDefaultModel?.currentSelection === 'function' ? options.agentDefaultModel.currentSelection() : null;
109
- persistSelection(options.resumeSessionId, selection);
110
- return {
111
- agent: handle.agent,
112
- created: false,
113
- resumed: true,
114
- sessionId: options.resumeSessionId,
115
- dispose: async () => { try { await handle.dispose?.(); } catch { /* already gone */ } },
116
- };
117
- }
118
- } catch (error) {
119
- // A persisted host must be resumed: creating another one would break the
120
- // existing members' direct-child adjacency.
121
- throw new HostAgentError('E_HOST_AGENT', `Team Host Agent resume failed: ${error?.message ?? error}`, {
122
- sessionId: options.resumeSessionId,
123
- });
124
- }
125
- }
126
- const roots = typeof agents.roots === 'function' ? agents.roots() : [];
127
- if (roots.length > 0) {
128
- // roots() 只保证注册顺序,不保证某个元素是「Human 的根会话」;优先挑一个
129
- // 真正没有父会话、且不是 subagent 出来的根,避免把成员自己的父链当成
130
- // Human 通道(那会让成员成为彼此的 parent)。
131
- const rootAgent = roots.find((candidate) => {
132
- const header = candidate?.session?.header;
133
- if (header === undefined) return true;
134
- return header.origin !== 'subagent' && header.parentSession === undefined;
135
- }) ?? roots[0];
136
- // 被选中的 Human 根会话若已归档,成员血缘会被 gate 永久拒绝——这条快路径
137
- // 也必须解归档,否则 boot 期的 sweep 由于没有 hostSessionId 看不到它。
138
- await unarchiveHost(rootAgent.id);
139
- return { agent: rootAgent, created: false, sessionId: rootAgent.id, dispose: async () => {} };
140
- }
141
-
142
- const selection = typeof options.agentDefaultModel?.currentSelection === 'function'
143
- ? options.agentDefaultModel.currentSelection()
144
- : null;
145
- if (selection === null || typeof selection.provider !== 'string' || typeof selection.model !== 'string') {
146
- throw new HostAgentError('E_RUNTIME_UNAVAILABLE', 'no default provider/model is configured for the Team Host Agent');
147
- }
148
- const sessionId = options.newSessionId?.() ?? `session-team-host-${randomUUID()}`;
149
- const agentOptions = { provider: selection.provider, model: selection.model };
150
- if (typeof selection.reasoningEffort === 'string') agentOptions.reasoningEffort = selection.reasoningEffort;
151
- let handle;
152
- try {
153
- handle = await agents.create({
154
- sessionId,
155
- meta: { cwd: options.cwd },
156
- agentOptions,
157
- });
158
- } catch (error) {
159
- throw new HostAgentError('E_HOST_AGENT', `Team Host Agent creation failed: ${error?.message ?? error}`, {
160
- cause: error?.code ?? null,
161
- });
162
- }
163
- persistSelection(sessionId, selection);
164
- const host = handle.agent;
165
- await unarchiveHost(sessionId);
166
- return {
167
- agent: host,
168
- created: true,
169
- sessionId,
170
- dispose: async () => {
171
- try { await handle.dispose?.(); } catch { /* teardown already started */ }
172
- },
173
- };
174
- }
1
+ /**
2
+ * Resolve the parent Agent that owns member activations.
3
+ *
4
+ * Preference order:
5
+ * 1. an existing live root Agent (the Human's current session);
6
+ * 2. a lazily created Team Host Agent (the Human owner has no
7
+ * session, e.g. the workbench was opened without a chat).
8
+ *
9
+ * The Host Agent is a runtime root, not a product member: it owns no Task,
10
+ * has no product decision power.
11
+ *
12
+ * IMPORTANT — the Host Agent must never be archived. Members are subagent
13
+ * descendants of it, and `archived-session-gate` (dsh-api-session-controller)
14
+ * rejects every `agent/pre-step` whose Session, or any Session above it in the
15
+ * subagent lineage, is archived. The loop then ends the turn as
16
+ * `{kind:'blocked'}` **without issuing a model request**, so archiving the host
17
+ * silently disables the whole team (observed: 453 blocked turns, 0 completed).
18
+ * Earlier revisions archived it to hide it from the session list; that is
19
+ * repaired here by unarchiving on resolve.
20
+ */
21
+ import { randomUUID } from 'node:crypto';
22
+ import { reportFail } from '../diaglog.js';
23
+
24
+ /** Windows 路径大小写不敏感,末尾分隔符也不该影响判定。 */
25
+ const samePath = (left, right) => {
26
+ const norm = (value) => String(value).replace(/[\\/]+$/, '').replace(/\\/g, '/').toLowerCase();
27
+ return norm(left) === norm(right);
28
+ };
29
+
30
+ export class HostAgentError extends Error {
31
+ constructor(code, message, details = {}) {
32
+ super(message);
33
+ this.name = 'HostAgentError';
34
+ this.code = code;
35
+ this.details = details;
36
+ }
37
+ }
38
+
39
+ /**
40
+ * @param {{
41
+ * agents: any,
42
+ * agentDefaultModel: any,
43
+ * workspaceRegistry?: any,
44
+ * sessions?: any,
45
+ * cwd: string,
46
+ * newSessionId?: () => string
47
+ * }} options
48
+ */
49
+ export async function ensureHostAgent(options) {
50
+ const agents = options.agents;
51
+ if (agents === undefined || typeof agents.create !== 'function') {
52
+ throw new HostAgentError('E_RUNTIME_UNAVAILABLE', 'agents service is unavailable');
53
+ }
54
+ // Repair a Host Agent archived by an earlier revision: the archive gate
55
+ // covers the host's whole subagent lineage, so every member turn would end
56
+ // blocked before any model request. `unarchiveSession` resolves without
57
+ // writing when the id is not archived, so no read-back is needed — and
58
+ // gating on the undocumented `archivedSessionIds` accessor is what silently
59
+ // skipped this repair before.
60
+ const unarchiveHost = async (sessionId) => {
61
+ const registry = options.workspaceRegistry;
62
+ if (typeof registry?.unarchiveSession !== 'function') return;
63
+ try {
64
+ await registry.unarchiveSession(sessionId);
65
+ } catch (error) {
66
+ reportFail('host.unarchive.fail', { sessionId: sessionId ?? null }, '[ai-team] could not unarchive Team Host session: ' + (error?.message ?? error));
67
+ }
68
+ };
69
+ // Persist the resolved route into the session log. Live AgentOptions die
70
+ // with the process; without a recorded selection a restored session renders
71
+ // prompts with an unresolvable {{model}} variable.
72
+ const persistSelection = (sessionId, selection) => {
73
+ try {
74
+ const session = options.sessions?.get?.(sessionId);
75
+ if (session === undefined || session === null || typeof session.append !== 'function') return;
76
+ if (typeof selection?.provider !== 'string' || typeof selection?.model !== 'string') return;
77
+ // 推理等级一并记下,否则恢复出来的会话按模型默认档走。
78
+ const effort = typeof selection.reasoningEffort === 'string' && selection.reasoningEffort !== ''
79
+ ? selection.reasoningEffort
80
+ : null;
81
+ session.append('model/selection', {
82
+ provider: selection.provider,
83
+ model: selection.model,
84
+ ...(effort === null ? {} : { reasoningEffort: effort }),
85
+ });
86
+ } catch (error) {
87
+ reportFail('host.model.persist.fail', {}, '[ai-team] host model selection persist failed: ' + (error?.message ?? error));
88
+ }
89
+ };
90
+ if (typeof options.resumeSessionId === 'string' && options.resumeSessionId !== '') {
91
+ const live = typeof agents.get === 'function' ? agents.get(options.resumeSessionId) : undefined;
92
+ if (live !== undefined) {
93
+ await unarchiveHost(options.resumeSessionId);
94
+ const selection = typeof options.agentDefaultModel?.currentSelection === 'function' ? options.agentDefaultModel.currentSelection() : null;
95
+ persistSelection(options.resumeSessionId, selection);
96
+ return { agent: live, created: false, resumed: true, sessionId: options.resumeSessionId, dispose: async () => {} };
97
+ }
98
+ try {
99
+ const handle = await agents.resume({ resumeSessionId: options.resumeSessionId });
100
+ await unarchiveHost(options.resumeSessionId);
101
+ // 持久化的 host 会话保留着**创建时的 cwd**,而成员子会话会继承它。
102
+ // 实机事故:2026-11-09 建的 host 记的是 `…/.dsh/ai-team/default`,于是
103
+ // 30 个成员会话全在插件数据目录里干活,`workspace.attachSession` 每天被拒
104
+ // 上百次。cwd 不一致时不能复用这条 host——释放它,落到下面的创建分支。
105
+ const expectedCwd = typeof options.cwd === 'string' ? options.cwd.trim() : '';
106
+ const actualCwd = handle?.agent?.session?.header?.cwd ?? options.sessions?.get?.(options.resumeSessionId)?.header?.cwd ?? null;
107
+ if (expectedCwd !== '' && typeof actualCwd === 'string' && actualCwd !== ''
108
+ && samePath(actualCwd, expectedCwd) === false) {
109
+ try { await handle.dispose?.(); } catch { /* already gone */ }
110
+ reportFail(
111
+ 'host.resume.cwd-mismatch.fail',
112
+ { sessionId: options.resumeSessionId, expectedCwd, actualCwd },
113
+ '[ai-team] Team Host session cwd does not match the project workspace; creating a fresh host',
114
+ );
115
+ } else {
116
+ const selection = typeof options.agentDefaultModel?.currentSelection === 'function' ? options.agentDefaultModel.currentSelection() : null;
117
+ persistSelection(options.resumeSessionId, selection);
118
+ return {
119
+ agent: handle.agent,
120
+ created: false,
121
+ resumed: true,
122
+ sessionId: options.resumeSessionId,
123
+ dispose: async () => { try { await handle.dispose?.(); } catch { /* already gone */ } },
124
+ };
125
+ }
126
+ } catch (error) {
127
+ // A persisted host must be resumed: creating another one would break the
128
+ // existing members' direct-child adjacency.
129
+ throw new HostAgentError('E_HOST_AGENT', `Team Host Agent resume failed: ${error?.message ?? error}`, {
130
+ sessionId: options.resumeSessionId,
131
+ });
132
+ }
133
+ }
134
+ const roots = typeof agents.roots === 'function' ? agents.roots() : [];
135
+ if (roots.length > 0) {
136
+ // roots() 只保证注册顺序,不保证某个元素是「Human 的根会话」;优先挑一个
137
+ // 真正没有父会话、且不是 subagent 出来的根,避免把成员自己的父链当成
138
+ // Human 通道(那会让成员成为彼此的 parent)。
139
+ const rootAgent = roots.find((candidate) => {
140
+ const header = candidate?.session?.header;
141
+ if (header === undefined) return true;
142
+ return header.origin !== 'subagent' && header.parentSession === undefined;
143
+ }) ?? roots[0];
144
+ // 被选中的 Human 根会话若已归档,成员血缘会被 gate 永久拒绝——这条快路径
145
+ // 也必须解归档,否则 boot 期的 sweep 由于没有 hostSessionId 看不到它。
146
+ await unarchiveHost(rootAgent.id);
147
+ return { agent: rootAgent, created: false, sessionId: rootAgent.id, dispose: async () => {} };
148
+ }
149
+
150
+ const selection = typeof options.agentDefaultModel?.currentSelection === 'function'
151
+ ? options.agentDefaultModel.currentSelection()
152
+ : null;
153
+ if (selection === null || typeof selection.provider !== 'string' || typeof selection.model !== 'string') {
154
+ throw new HostAgentError('E_RUNTIME_UNAVAILABLE', 'no default provider/model is configured for the Team Host Agent');
155
+ }
156
+ const sessionId = options.newSessionId?.() ?? `session-team-host-${randomUUID()}`;
157
+ const agentOptions = { provider: selection.provider, model: selection.model };
158
+ if (typeof selection.reasoningEffort === 'string') agentOptions.reasoningEffort = selection.reasoningEffort;
159
+ let handle;
160
+ try {
161
+ handle = await agents.create({
162
+ sessionId,
163
+ meta: { cwd: options.cwd },
164
+ agentOptions,
165
+ });
166
+ } catch (error) {
167
+ throw new HostAgentError('E_HOST_AGENT', `Team Host Agent creation failed: ${error?.message ?? error}`, {
168
+ cause: error?.code ?? null,
169
+ });
170
+ }
171
+ persistSelection(sessionId, selection);
172
+ const host = handle.agent;
173
+ await unarchiveHost(sessionId);
174
+ return {
175
+ agent: host,
176
+ created: true,
177
+ sessionId,
178
+ dispose: async () => {
179
+ try { await handle.dispose?.(); } catch { /* teardown already started */ }
180
+ },
181
+ };
182
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@suifei/dsh-ai-team",
3
- "version": "0.4.79",
3
+ "version": "0.4.82",
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",