dsh-chief 1.3.0 → 1.5.0

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.
@@ -10,10 +10,13 @@ import os from 'node:os'
10
10
  import { answerMemory } from './memory.js'
11
11
  import {
12
12
  loadChiefState,
13
+ resolveWorkspaceConfig,
14
+ appendChiefAuditLog,
13
15
  getLinkedCluster,
14
16
  collectClusterPeerProgress,
15
17
  deliverCrossMessage,
16
18
  } from './chief.js'
19
+ import { resolveAlignedModelEffort } from './chief-state.js'
17
20
  import {
18
21
  API,
19
22
  newId,
@@ -156,6 +159,25 @@ export function createSubagentRuntime(deps) {
156
159
  return getSubagentRoster(rt, rootId, board)
157
160
  }
158
161
 
162
+ function readAgentReasoningEffort(ag) {
163
+ if (!ag || typeof ag !== 'object') return ''
164
+ try {
165
+ if (ag.model && typeof ag.model.current === 'function') {
166
+ const cur = ag.model.current()
167
+ if (cur && typeof cur.reasoningEffort === 'string' && cur.reasoningEffort) return cur.reasoningEffort
168
+ }
169
+ if (ag.session && typeof ag.session.requestHeader === 'function') {
170
+ const h = ag.session.requestHeader()
171
+ if (h && h.config && typeof h.config.reasoningEffort === 'string') return h.config.reasoningEffort
172
+ }
173
+ if (ag.session && ag.session.modelSelection && typeof ag.session.modelSelection.reasoningEffort === 'string') {
174
+ return ag.session.modelSelection.reasoningEffort
175
+ }
176
+ if (ag.config && typeof ag.config.reasoningEffort === 'string') return ag.config.reasoningEffort
177
+ } catch {}
178
+ return ''
179
+ }
180
+
159
181
  /** Synchronous roster combining cached subagent tree + live agent status + board task assignments. */
160
182
  function getSubagentRoster(runtime, sessionId, board) {
161
183
  const rt = runtime || deps.hostState.activeRuntime
@@ -163,6 +185,11 @@ export function createSubagentRuntime(deps) {
163
185
  const agents = rt ? rt.get('agents') : null
164
186
  const cached = deps.hostState.subagentTreeCache.get(rootId) || []
165
187
  const byName = new Map()
188
+ let locks = {}
189
+ try {
190
+ const cfg = resolveWorkspaceConfig(loadChiefState(), rootId)
191
+ locks = (cfg && cfg.lockedModelEfforts) || {}
192
+ } catch {}
166
193
 
167
194
  const liveStatus = (id, fallback) => {
168
195
  try {
@@ -173,11 +200,22 @@ export function createSubagentRuntime(deps) {
173
200
  } catch {}
174
201
  return fallback || 'inactive'
175
202
  }
203
+ const liveEffort = (id) => {
204
+ try {
205
+ if (agents && typeof agents.get === 'function' && id) {
206
+ return readAgentReasoningEffort(agents.get(id))
207
+ }
208
+ } catch {}
209
+ return ''
210
+ }
176
211
 
177
212
  for (const row of cached) {
213
+ const short = String(row.name || '').split('/').pop()
178
214
  byName.set(row.name, {
179
215
  ...row,
180
216
  status: liveStatus(row.id, row.status),
217
+ reasoningEffort: liveEffort(row.id) || row.reasoningEffort || '',
218
+ effortLocked: Boolean(locks[row.name] || locks[short] || locks[row.id]),
181
219
  tasks: [],
182
220
  })
183
221
  }
@@ -187,6 +225,8 @@ export function createSubagentRuntime(deps) {
187
225
  id: rootId,
188
226
  name: 'lead',
189
227
  status: liveStatus(rootId, 'inactive'),
228
+ reasoningEffort: liveEffort(rootId),
229
+ effortLocked: Boolean(locks.lead || locks[rootId]),
190
230
  description: '主代理 (Root Coordinator)',
191
231
  mode: 'continuable',
192
232
  tasks: [],
@@ -198,10 +238,13 @@ export function createSubagentRuntime(deps) {
198
238
  const ownerRaw = String(t.subagent || t.owner || '').trim()
199
239
  if (!ownerRaw || ownerRaw === 'agent' || ownerRaw === 'operator' || ownerRaw === 'user') continue
200
240
  if (!byName.has(ownerRaw)) {
241
+ const short = ownerRaw.split('/').pop()
201
242
  byName.set(ownerRaw, {
202
243
  id: String(t.session || ''),
203
244
  name: ownerRaw,
204
245
  status: t.status === 'doing' ? liveStatus(t.session, 'running') : 'inactive',
246
+ reasoningEffort: liveEffort(t.session),
247
+ effortLocked: Boolean(locks[ownerRaw] || locks[short] || (t.session && locks[t.session])),
205
248
  description: t.title || '',
206
249
  mode: 'continuable',
207
250
  tasks: [],
@@ -417,12 +460,19 @@ export function createSubagentRuntime(deps) {
417
460
  const dir = path.join(root, bucket)
418
461
  const names = safe(() => fs.readdirSync(dir), [])
419
462
  for (const name of names) {
420
- const file = path.join(dir, name, 'session.v4.jsonl.zstd')
463
+ const dirPath = path.join(dir, name)
464
+ const file = path.join(dirPath, 'session.v4.jsonl.zstd')
421
465
  let at = 0
422
466
  try {
423
467
  at = fs.statSync(file).mtimeMs
424
468
  } catch {
425
- continue
469
+ const entries = safe(() => fs.readdirSync(dirPath), [])
470
+ for (const entName of entries) {
471
+ if (!/^session(?:\.v\d+)?\.jsonl(?:\.zstd)?$/.test(entName)) continue
472
+ const mst = safe(() => fs.statSync(path.join(dirPath, entName)).mtimeMs, 0)
473
+ if (mst > at) at = mst
474
+ }
475
+ if (!at) continue
426
476
  }
427
477
  const key = name.indexOf('session-') === 0 ? name : 'session-' + name
428
478
  const previous = found.get(key) || 0
@@ -754,6 +804,11 @@ export function createSubagentRuntime(deps) {
754
804
  const otherTokens = Math.max(0, usedTokens - overheadTokens - messageTokens)
755
805
  const pct = contextWindow > 0 ? Math.min(100, Math.round((usedTokens / contextWindow) * 100)) : 0
756
806
 
807
+ let effortLocked = false
808
+ try {
809
+ const cfg = resolveWorkspaceConfig(loadChiefState(), rootSid || sid)
810
+ effortLocked = Boolean(cfg && cfg.lockedModelEfforts && cfg.lockedModelEfforts.lead)
811
+ } catch {}
757
812
  return {
758
813
  totalTokens: usedTokens,
759
814
  usedTokens,
@@ -765,6 +820,8 @@ export function createSubagentRuntime(deps) {
765
820
  otherTokens,
766
821
  overheadTokens,
767
822
  modelRef,
823
+ reasoningEffort: readAgentReasoningEffort(ag),
824
+ effortLocked,
768
825
  seq,
769
826
  source,
770
827
  }
@@ -900,12 +957,195 @@ export function createSubagentRuntime(deps) {
900
957
  })
901
958
  },
902
959
  executeSubagentAction: (input, callerAgent, signal) => executeSubagentAction(rt, input, callerAgent, signal),
903
- async controlMainAgent({ rootId = '', sessionId = '', op = 'steer', modelRef = '', reasoningEffort = '', message = '', reason = '' } = {}) {
960
+ async controlMainAgent({ rootId = '', sessionId = '', op = 'steer', target = '', modelRef = '', reasoningEffort = '', message = '', reason = '', byUser = false } = {}) {
904
961
  const targetSid = String(sessionId || rootId || '').trim()
905
962
  if (!targetSid || targetSid === 'global') {
906
963
  return { ok: false, error: '当前为空白未绑定会话,无法直接控制主对话代理' }
907
964
  }
908
965
  const ctrl = rt ? rt.get('sessionController') : null
966
+ if (op === 'set_effort') {
967
+ const wantRaw = String(reasoningEffort || '').trim().toLowerCase()
968
+ const validEff = ['off', 'low', 'medium', 'high', 'xhigh'].includes(wantRaw) ? wantRaw : 'medium'
969
+ const fallbackTarget = !target && modelRef && !String(modelRef).includes('/') ? String(modelRef) : ''
970
+ const rawTarget = String(target || fallbackTarget || '').trim().replace(/^@/, '')
971
+ const isLead = !rawTarget || rawTarget === 'lead' || rawTarget === 'main' || rawTarget === targetSid
972
+ const targetKey = isLead ? 'lead' : rawTarget
973
+ const rootKey = String(rootId || resolveRootSessionId(targetSid) || targetSid).trim()
974
+ const effCfg = resolveWorkspaceConfig(loadChiefState(), rootKey)
975
+ const locks = (effCfg && effCfg.lockedModelEfforts) || {}
976
+
977
+ const agents = rt ? rt.get('agents') : null
978
+ const subagents = rt ? rt.get('subagents') : null
979
+ let resolvedAgentId = isLead ? targetSid : ''
980
+ let targetAgent = isLead && agents && typeof agents.get === 'function' ? agents.get(targetSid) : null
981
+
982
+ if (!isLead) {
983
+ const leadAg = agents && typeof agents.get === 'function' ? agents.get(targetSid) : null
984
+ if (subagents && typeof subagents.resolveName === 'function' && leadAg) {
985
+ try {
986
+ resolvedAgentId = await subagents.resolveName(leadAg, targetKey, new AbortController().signal)
987
+ } catch {}
988
+ }
989
+ if (!resolvedAgentId) {
990
+ const board = loadBoard(boardFileFor(rootKey))
991
+ const roster = getSubagentRoster(rt, rootKey, board)
992
+ const matched = roster.find(r => r.name === targetKey || r.name.endsWith('/' + targetKey) || r.id === targetKey)
993
+ if (matched && matched.id) resolvedAgentId = matched.id
994
+ }
995
+ if (!resolvedAgentId && agents && typeof agents.get === 'function' && agents.get(targetKey)) {
996
+ resolvedAgentId = targetKey
997
+ }
998
+ if (resolvedAgentId && agents && typeof agents.get === 'function') {
999
+ targetAgent = agents.get(resolvedAgentId)
1000
+ }
1001
+ }
1002
+
1003
+ if (!targetAgent && resolvedAgentId && ctrl && typeof ctrl.resolveAgent === 'function') {
1004
+ try {
1005
+ const resolved = await ctrl.resolveAgent(resolvedAgentId)
1006
+ if (resolved && resolved.agent) targetAgent = resolved.agent
1007
+ } catch {}
1008
+ }
1009
+
1010
+ const shortTarget = targetKey.split('/').pop()
1011
+ const isManualTeamEffort = Boolean(effCfg && effCfg.teamEffortMode === 'manual')
1012
+ if (!byUser && isManualTeamEffort) {
1013
+ appendChiefAuditLog(rootKey, {
1014
+ mode: effCfg.permissionMode,
1015
+ stage: 'model_effort_lock',
1016
+ decision: 'blocked',
1017
+ operation: '调节模型思考强度',
1018
+ target: targetKey,
1019
+ reason: `团队思考强度处于「手动」模式,阻止参谋将 ${targetKey} 调为 ${validEff}`,
1020
+ outcome: 'blocked',
1021
+ by: 'chief',
1022
+ })
1023
+ return {
1024
+ ok: false,
1025
+ lockedByUser: true,
1026
+ manualMode: true,
1027
+ target: targetKey,
1028
+ error: '当前团队思考强度已设为「手动」模式,参谋不会自动调节主/子代理思考强度',
1029
+ badge: '✋ 团队调挡已设为手动',
1030
+ }
1031
+ }
1032
+ const isLocked = Boolean(
1033
+ locks[targetKey] === true
1034
+ || locks[shortTarget] === true
1035
+ || (resolvedAgentId && locks[resolvedAgentId] === true)
1036
+ )
1037
+ if (!byUser && isLocked) {
1038
+ appendChiefAuditLog(rootKey, {
1039
+ mode: effCfg.permissionMode,
1040
+ stage: 'model_effort_lock',
1041
+ decision: 'blocked',
1042
+ operation: '调节模型思考强度',
1043
+ target: targetKey,
1044
+ reason: `用户已开启「🔒 锁挡」,阻止参谋将 ${targetKey} 调为 ${validEff}`,
1045
+ outcome: 'blocked',
1046
+ by: 'chief',
1047
+ })
1048
+ return {
1049
+ ok: false,
1050
+ lockedByUser: true,
1051
+ target: targetKey,
1052
+ error: `用户已锁定 ${isLead ? '主对话 (@lead)' : '@' + targetKey} 的思考强度(🔒),参谋无权覆盖`,
1053
+ badge: '🔒 用户已锁挡',
1054
+ }
1055
+ }
1056
+
1057
+ let curModel = null
1058
+ try {
1059
+ if (targetAgent && targetAgent.model && typeof targetAgent.model.current === 'function') {
1060
+ curModel = targetAgent.model.current()
1061
+ }
1062
+ } catch {}
1063
+ let provider = String((curModel && curModel.provider) || '').trim()
1064
+ let model = String((curModel && curModel.model) || '').trim()
1065
+ if ((!provider || !model) && modelRef && modelRef.includes('/')) {
1066
+ const idx = modelRef.indexOf('/')
1067
+ provider = modelRef.slice(0, idx).trim()
1068
+ model = modelRef.slice(idx + 1).trim()
1069
+ }
1070
+ if ((!provider || !model) && isLead) {
1071
+ const bd = getSessionContextBreakdown(rt, targetSid, targetAgent)
1072
+ if (bd && bd.modelRef && bd.modelRef.includes('/')) {
1073
+ const idx = bd.modelRef.indexOf('/')
1074
+ provider = bd.modelRef.slice(0, idx).trim()
1075
+ model = bd.modelRef.slice(idx + 1).trim()
1076
+ }
1077
+ }
1078
+
1079
+ let finalEffort = validEff
1080
+ const llm = deps.hostState.activeLlm || (rt ? rt.get('llm') : null)
1081
+ if (llm && typeof llm.resolveModelInfo === 'function' && provider && model) {
1082
+ try {
1083
+ const info = await llm.resolveModelInfo(provider, model)
1084
+ if (info && info.reasoning && Array.isArray(info.reasoning.efforts)) {
1085
+ if (info.reasoning.efforts.length === 0) {
1086
+ return {
1087
+ ok: false,
1088
+ nonReasoningModel: true,
1089
+ error: `当前模型 ${provider}/${model} 不支持思考强度调节`,
1090
+ }
1091
+ }
1092
+ finalEffort = resolveAlignedModelEffort(validEff, info.reasoning.efforts) || validEff
1093
+ }
1094
+ } catch {}
1095
+ }
1096
+
1097
+ let applied = false
1098
+ try {
1099
+ if (targetAgent && targetAgent.model && typeof targetAgent.model.select === 'function') {
1100
+ await targetAgent.model.select({
1101
+ ...(curModel && typeof curModel === 'object' ? curModel : {}),
1102
+ ...(provider ? { provider } : {}),
1103
+ ...(model ? { model } : {}),
1104
+ reasoningEffort: finalEffort,
1105
+ })
1106
+ applied = true
1107
+ } else if (isLead && ctrl && typeof ctrl.selectModel === 'function' && model) {
1108
+ await ctrl.selectModel({
1109
+ sessionId: resolvedAgentId,
1110
+ ...(provider ? { provider } : {}),
1111
+ model,
1112
+ reasoningEffort: finalEffort,
1113
+ })
1114
+ applied = true
1115
+ } else if (targetAgent && typeof targetAgent.setModel === 'function') {
1116
+ targetAgent.setModel({
1117
+ ...(provider ? { provider } : {}),
1118
+ ...(model ? { model } : {}),
1119
+ reasoningEffort: finalEffort,
1120
+ })
1121
+ applied = true
1122
+ }
1123
+ } catch (err) {
1124
+ return { ok: false, error: '调节思考强度失败:' + ((err && err.message) || String(err || 'unknown')) }
1125
+ }
1126
+
1127
+ if (!applied) {
1128
+ return { ok: false, error: `未找到在线代理 ${targetKey} 或当前宿主未提供热调挡接口` }
1129
+ }
1130
+
1131
+ appendChiefAuditLog(rootKey, {
1132
+ mode: effCfg.permissionMode,
1133
+ stage: 'model_effort',
1134
+ decision: byUser ? 'user_changed' : 'executed',
1135
+ operation: '调节模型思考强度',
1136
+ target: targetKey,
1137
+ reason: reason || `${byUser ? '人类用户' : '参谋长'}将 ${targetKey} 思考强度设为 ${finalEffort}`,
1138
+ outcome: 'ok',
1139
+ by: byUser ? 'user' : 'chief',
1140
+ })
1141
+ return {
1142
+ ok: true,
1143
+ target: targetKey,
1144
+ targetId: resolvedAgentId,
1145
+ reasoningEffort: finalEffort,
1146
+ badge: `🧠 ${isLead ? '主对话' : '@' + targetKey} 思考强度 → ${finalEffort}`,
1147
+ }
1148
+ }
909
1149
  if (op === 'switch_model') {
910
1150
  const rawRef = String(modelRef || '').trim()
911
1151
  if (!rawRef) return { ok: false, error: 'switch_model 需要 modelRef 参数(如 provider/model)' }
@@ -1072,6 +1312,18 @@ export function createSubagentRuntime(deps) {
1072
1312
  const providerName = str(args.provider, targetTask.preset === 'fork' ? 'fork' : 'spawn') || 'spawn'
1073
1313
  const preset = str(args.preset, targetTask.preset && targetTask.preset !== 'fork' && targetTask.preset !== 'spawn' ? targetTask.preset : '')
1074
1314
  const candidateName = sanitizeSubagentName(requestedTarget, targetTask.id)
1315
+ const reqEffortRaw = str(args.reasoningEffort || args.effort, '').trim().toLowerCase()
1316
+ let allowedEffort = ['off', 'low', 'medium', 'high', 'xhigh'].includes(reqEffortRaw) ? reqEffortRaw : ''
1317
+ if (allowedEffort) {
1318
+ try {
1319
+ const effCfg = resolveWorkspaceConfig(loadChiefState(), rootId)
1320
+ const locks = (effCfg && effCfg.lockedModelEfforts) || {}
1321
+ const isHuman = by === 'operator' || by === 'user'
1322
+ if (!isHuman && (locks[candidateName] || locks[requestedTarget])) {
1323
+ allowedEffort = ''
1324
+ }
1325
+ } catch {}
1326
+ }
1075
1327
 
1076
1328
  let existingTargetId = ''
1077
1329
  if (requestedTarget && requestedTarget !== 'agent' && requestedTarget !== 'operator' && requestedTarget !== 'lead') {
@@ -1085,6 +1337,15 @@ export function createSubagentRuntime(deps) {
1085
1337
  }
1086
1338
 
1087
1339
  if (existingTargetId && existingTargetId !== String(liveCaller.id)) {
1340
+ if (allowedEffort && agents && typeof agents.get === 'function') {
1341
+ try {
1342
+ const exAg = agents.get(existingTargetId)
1343
+ if (exAg && exAg.model && typeof exAg.model.select === 'function') {
1344
+ const cur = typeof exAg.model.current === 'function' ? exAg.model.current() : {}
1345
+ await exAg.model.select({ ...(cur || {}), reasoningEffort: allowedEffort })
1346
+ }
1347
+ } catch {}
1348
+ }
1088
1349
  await subagents.sendMessage(liveCaller, existingTargetId, [{ type: 'text', text: brief }], { signal: sig })
1089
1350
  dispatchedName = requestedTarget || candidateName
1090
1351
  childSessionId = String(existingTargetId)
@@ -1100,6 +1361,7 @@ export function createSubagentRuntime(deps) {
1100
1361
  prompt: [{ type: 'text', text: brief }],
1101
1362
  parent: liveCaller,
1102
1363
  ...(preset ? { agentPreset: preset } : {}),
1364
+ ...(allowedEffort ? { agentReasoningEffort: allowedEffort, reasoningEffort: allowedEffort } : {}),
1103
1365
  signal: sig,
1104
1366
  delivery: 'parent',
1105
1367
  })
@@ -1115,6 +1377,7 @@ export function createSubagentRuntime(deps) {
1115
1377
  prompt: [{ type: 'text', text: brief }],
1116
1378
  parent: liveCaller,
1117
1379
  ...(preset ? { agentPreset: preset } : {}),
1380
+ ...(allowedEffort ? { agentReasoningEffort: allowedEffort, reasoningEffort: allowedEffort } : {}),
1118
1381
  signal: sig,
1119
1382
  delivery: 'parent',
1120
1383
  })