dsh-chief 1.3.0 → 1.4.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.
package/chief-network.js CHANGED
@@ -9,6 +9,8 @@ import {
9
9
  MAIL_CAP,
10
10
  CHIEF_UPDATE_SOURCE,
11
11
  CHIEF_RELAY_SOURCE,
12
+ CHIEF_INQUIRY_SOURCE,
13
+ CHIEF_EXEC_REQ_SOURCE,
12
14
  persistChiefImagesToWorkspace,
13
15
  admitChiefImages,
14
16
  nextId,
@@ -17,6 +19,7 @@ import {
17
19
  normalizeMail,
18
20
  loadChiefState,
19
21
  mutateChiefState,
22
+ answerChiefInquiry,
20
23
  getLinkedCluster,
21
24
  ensureWorkspace,
22
25
  clusterView,
@@ -25,6 +28,12 @@ import {
25
28
  } from './chief-state.js'
26
29
  import { loadDshLlm } from './chief-models.js'
27
30
 
31
+ let chiefDirectRequestHook = null
32
+
33
+ export function registerChiefDirectRequestHook(fn) {
34
+ chiefDirectRequestHook = typeof fn === 'function' ? fn : null
35
+ }
36
+
28
37
  export async function buildMessageEnvelope(text, sourceKind = CHIEF_RELAY_SOURCE, extraSource = {}, imageBlocks = []) {
29
38
  const dshLlm = await loadDshLlm()
30
39
  const safeImages = Array.isArray(imageBlocks) ? imageBlocks : []
@@ -244,6 +253,9 @@ export async function deliverCrossMessage(deps, {
244
253
  text = '',
245
254
  subject = '',
246
255
  mode = 'steer',
256
+ envelopeKind = 'relay',
257
+ taskId = '',
258
+ inquiryId = '',
247
259
  images = [],
248
260
  imageBlocks: preAdmittedBlocks = null,
249
261
  savedImagePaths: preSavedPaths = null,
@@ -280,9 +292,100 @@ export async function deliverCrossMessage(deps, {
280
292
  const imgTag = totalImgCount > 0 ? ` [附图 ×${totalImgCount}]` : ''
281
293
 
282
294
  const rootId = (deps.resolveRootSessionId && deps.resolveRootSessionId(fromSession)) || String(fromSession || directoryRootFallback(fromSession))
295
+ const rawTargetPre = String(target || 'lead').trim().replace(/^@/, '')
296
+ if (/^(?:chief|dsh-chief|参谋长|参谋)$/i.test(rawTargetPre)) {
297
+ const cleanChiefBody = cleanMultiline(text, 2400)
298
+ if (envelopeKind === 'inquiry_reply') {
299
+ if (!cleanChiefBody) return { ok: false, error: 'inquiry.reply 必须提供非空答复文本 (text)' }
300
+ const effInqId = String(inquiryId || taskId || '').trim()
301
+ const ansRes = answerChiefInquiry(rootId || 'global', {
302
+ inquiryId: effInqId,
303
+ answer: cleanChiefBody,
304
+ by: fromLabel,
305
+ })
306
+ if (recordBoardLog && rootId && typeof deps.appendBoardLog === 'function' && ansRes && ansRes.ok && ansRes.inquiry) {
307
+ deps.appendBoardLog(rootId, `⚡ ${fromLabel} 已原路回传问询 #${ansRes.inquiry.inquiryId}`, fromLabel)
308
+ }
309
+ return {
310
+ ok: Boolean(ansRes && ansRes.ok),
311
+ target: 'DSH 参谋长',
312
+ targetId: 'chief',
313
+ deliveryMode: 'inquiry-reply',
314
+ inquiryAnswered: ansRes && ansRes.inquiry ? ansRes.inquiry : null,
315
+ continueOwnWork: true,
316
+ ...(ansRes && !ansRes.ok ? { error: ansRes.error } : {}),
317
+ }
318
+ }
319
+ if (!cleanChiefBody) return { ok: false, error: '传话给参谋长的内容不能为空' }
320
+ const chiefMail = normalizeMail({
321
+ id: nextId('mail'),
322
+ from: fromLabel,
323
+ fromSession,
324
+ fromRootId: rootId,
325
+ to: 'chief',
326
+ toSession: 'chief',
327
+ toRootId: rootId,
328
+ participantRoots: rootId ? [rootId] : [],
329
+ channelType: 'internal',
330
+ subject: subject || '主对话求助与协同请求',
331
+ text: cleanChiefBody,
332
+ mode: mode || 'followup',
333
+ deliveredPhysical: true,
334
+ readBy: ['chief'],
335
+ at: Date.now(),
336
+ })
337
+ mutateChiefState((state) => {
338
+ const ws = ensureWorkspace(state, rootId || 'global')
339
+ if (chiefMail) {
340
+ ws.mailbox.push(chiefMail)
341
+ if (ws.mailbox.length > MAIL_CAP) ws.mailbox = ws.mailbox.slice(-MAIL_CAP)
342
+ }
343
+ })
344
+ if (recordBoardLog && rootId && typeof deps.appendBoardLog === 'function') {
345
+ deps.appendBoardLog(rootId, `📨 ${fromLabel} → @参谋长:${clamp(cleanChiefBody, 56)}`, fromLabel)
346
+ }
347
+ if (chiefDirectRequestHook) {
348
+ try {
349
+ const hookRes = await chiefDirectRequestHook(deps, {
350
+ fromSession: rootId || fromSession,
351
+ fromLabel,
352
+ subject,
353
+ text: cleanChiefBody,
354
+ mail: chiefMail,
355
+ })
356
+ if (hookRes && typeof hookRes === 'object') {
357
+ return {
358
+ ok: hookRes.ok !== false,
359
+ target: 'DSH 参谋长',
360
+ targetId: 'chief',
361
+ deliveryMode: 'chief-direct-request',
362
+ deliveredPhysical: true,
363
+ mail: chiefMail,
364
+ ...hookRes,
365
+ }
366
+ }
367
+ } catch (err) {
368
+ return {
369
+ ok: false,
370
+ target: 'DSH 参谋长',
371
+ mail: chiefMail,
372
+ error: String(err && err.message ? err.message : err),
373
+ }
374
+ }
375
+ }
376
+ return {
377
+ ok: true,
378
+ target: 'DSH 参谋长',
379
+ targetId: 'chief',
380
+ deliveryMode: 'chief-mailbox',
381
+ deliveredPhysical: true,
382
+ mail: chiefMail,
383
+ }
384
+ }
385
+
283
386
  const directory = await listPeerDirectory(deps, rootId || fromSession)
284
387
  const senderRootId = rootId || directory.rootId || ''
285
- const rawTarget = String(target || 'lead').trim().replace(/^@/, '')
388
+ const rawTarget = rawTargetPre
286
389
 
287
390
  // Broadcast support: 'all' / '全体' / 'team' (deduplicated single mailbox record for clean drawer UI)
288
391
  if (['all', 'team', '全体', '所有人'].includes(rawTarget.toLowerCase())) {
@@ -430,6 +533,8 @@ export async function deliverCrossMessage(deps, {
430
533
  text: effectiveText,
431
534
  subject,
432
535
  mode,
536
+ envelopeKind,
537
+ taskId,
433
538
  imageBlocks: admittedBlocks,
434
539
  savedImagePaths: savedPaths,
435
540
  recordBoardLog,
@@ -448,6 +553,8 @@ async function deliverSinglePeer(deps, directory, peer, {
448
553
  text,
449
554
  subject,
450
555
  mode,
556
+ envelopeKind = 'relay',
557
+ taskId = '',
451
558
  imageBlocks = [],
452
559
  savedImagePaths = [],
453
560
  recordBoardLog,
@@ -462,10 +569,17 @@ async function deliverSinglePeer(deps, directory, peer, {
462
569
  const imgSuffix = imgCount > 0 ? ` [附图 ×${imgCount}]` : ''
463
570
  const imgNoticeBlock = buildSavedImageNotice(safePaths)
464
571
  const textWithImagePaths = imgNoticeBlock ? `${text}\n${imgNoticeBlock}` : text
465
- const headerTag = mode === 'steer'
466
- ? `[DSH 参谋长插话 · 来自 ${fromLabel}]`
467
- : `[DSH 参谋长递话 · 来自 ${fromLabel}]`
468
- const formatted = `${headerTag}${subject ? ' ' + subject : ''}\n${textWithImagePaths}\n\n(如需回信或同步进展,可调用参谋看板 chief_board({ action: "mail.send", target: "${fromLabel === 'DSH 参谋长' ? 'lead' : fromLabel}", text: "…" }))`
572
+ const headerTag = envelopeKind === 'execution_request'
573
+ ? `[EXECUTION_REQUEST${taskId ? ' #' + taskId : ''} · 来自 ${fromLabel}]`
574
+ : (envelopeKind === 'inquiry'
575
+ ? `[INQUIRY${taskId ? ' #' + taskId : ''} · DSH 参谋长优先问询]`
576
+ : (mode === 'steer'
577
+ ? `[DSH 参谋长插话 · 来自 ${fromLabel}]`
578
+ : `[DSH 参谋长递话 · 来自 ${fromLabel}]`))
579
+ const footerGuide = envelopeKind === 'inquiry'
580
+ ? '(请顺手调用 chief_board({ action: "inquiry.reply", text: "…" }) 原路作答,无需中断手头当前任务!)'
581
+ : `(如遇到需要参谋长协调、建议、或提权执行的需求,可调用 chief_board({ action: "chief.request", text: "…" }) 或 mail.send({ target: "chief", text: "…" }))`
582
+ const formatted = `${headerTag}${subject ? ' ' + subject : ''}\n${textWithImagePaths}\n\n${footerGuide}`
469
583
 
470
584
  let deliveredPhysical = false
471
585
  let deliveryMode = 'mailbox-queued'
@@ -507,10 +621,16 @@ async function deliverSinglePeer(deps, directory, peer, {
507
621
  } catch {}
508
622
  }
509
623
  if (targetAgent) {
510
- const envelope = await buildMessageEnvelope(formatted, CHIEF_RELAY_SOURCE, {
624
+ const envelopeSourceKind = envelopeKind === 'execution_request'
625
+ ? CHIEF_EXEC_REQ_SOURCE
626
+ : (envelopeKind === 'inquiry' ? CHIEF_INQUIRY_SOURCE : CHIEF_RELAY_SOURCE)
627
+ const envelope = await buildMessageEnvelope(formatted, envelopeSourceKind, {
511
628
  senderName: fromLabel,
512
629
  senderSessionId: fromSession || undefined,
513
- role: mode === 'steer' ? 'steer' : 'relay',
630
+ role: envelopeKind === 'execution_request'
631
+ ? 'execution_request'
632
+ : (envelopeKind === 'inquiry' ? 'inquiry' : (mode === 'steer' ? 'steer' : 'relay')),
633
+ ...(taskId ? { taskId } : {}),
514
634
  }, safeBlocks)
515
635
  try {
516
636
  if (mode === 'steer' && targetAgent.status === 'running' && typeof targetAgent.steer === 'function') {
@@ -618,10 +738,35 @@ export async function consumePreStepDelta(deps, agent) {
618
738
  )
619
739
 
620
740
  const deltaLines = []
741
+ let hasPriorityInquiry = false
621
742
  mutateChiefState((state) => {
622
743
  const view = clusterView(state, rootId)
623
744
  const ownWs = ensureWorkspace(state, rootId)
624
745
 
746
+ // 0. Highest priority: DSH Chief Inquiry Channel (answer without interrupting own task!)
747
+ if (Array.isArray(ownWs.inquiries)) {
748
+ const nowInq = Date.now()
749
+ for (const inq of ownWs.inquiries) {
750
+ if (!inq || inq.status !== 'pending') continue
751
+ if (inq.expiresAt && nowInq > inq.expiresAt) {
752
+ inq.status = 'expired'
753
+ continue
754
+ }
755
+ const tLower = String(inq.target || 'lead').toLowerCase()
756
+ const matchesMe = myHandles.has(tLower) || (!identity?.isChild && tLower === 'lead')
757
+ if (!matchesMe) continue
758
+ inq.status = 'delivered'
759
+ inq.deliveredAt = nowInq
760
+ hasPriorityInquiry = true
761
+ deltaLines.push(
762
+ `⚡ [INQUIRY #${inq.inquiryId}${inq.taskId ? ' / ' + inq.taskId : ''} · DSH 参谋长优先问询 · 答复后继续原动作勿中断]`
763
+ + `\n 问题:${inq.question}`
764
+ + (inq.context ? `\n 背景:${inq.context}` : '')
765
+ + `\n ↳ 请在当前回合顺手调用 chief_board({ action: "inquiry.reply", inquiryId: "${inq.inquiryId}", text: "基于真实代码与状态的准确答复" }) 原路回传,然后立即继续你刚才的工作,切勿打断当前计划!`,
766
+ )
767
+ }
768
+ }
769
+
625
770
  // 1. Unread mailbox messages addressed to this session/handle (STRICT cluster isolation: ignore detached external peers!)
626
771
  for (const mail of view.mailbox) {
627
772
  if (mail.detachedFromCluster) continue
@@ -675,7 +820,11 @@ export async function consumePreStepDelta(deps, agent) {
675
820
  ...deltaLines,
676
821
  ].join('\n')
677
822
 
678
- return buildMessageEnvelope(text, CHIEF_UPDATE_SOURCE, { form: 'snapshot' })
823
+ return buildMessageEnvelope(
824
+ text,
825
+ hasPriorityInquiry ? CHIEF_INQUIRY_SOURCE : CHIEF_UPDATE_SOURCE,
826
+ { form: hasPriorityInquiry ? 'priority_inquiry' : 'snapshot' },
827
+ )
679
828
  }
680
829
 
681
830
  /* -------------------------------------------------------------------------- */
package/chief-review.js CHANGED
@@ -30,6 +30,9 @@ import {
30
30
  clusterView,
31
31
  isInternalCheckpointNoise,
32
32
  extractJsonObject,
33
+ beginChiefActiveWork,
34
+ updateChiefActiveWork,
35
+ endChiefActiveWork,
33
36
  } from './chief-state.js'
34
37
  import { listChiefModels, callChiefLlm } from './chief-models.js'
35
38
  import { listPeerDirectory, deliverCrossMessage } from './chief-network.js'
@@ -332,6 +335,13 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
332
335
  }
333
336
 
334
337
  lastReviewAtByRoot.set(rootId, now)
338
+ const isAutoPilotActiveNow = Boolean(paceMode === 'auto' && effCfgBefore.autoPilot && !effCfgBefore.stopped)
339
+ const reviewWorkId = beginChiefActiveWork(rootId, {
340
+ tone: 'neon',
341
+ tab: '',
342
+ label: isAutoPilotActiveNow ? '参谋长正在自动托管巡检中...' : '参谋长正在后台巡检研判中...',
343
+ })
344
+ try {
335
345
  const speaker = identity && identity.isChild ? `子代理 @${identity.self}` : '主对话 (@lead)'
336
346
  const view = clusterView(stateBefore, rootId)
337
347
  const numberedFacts = view.facts.slice()
@@ -406,7 +416,10 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
406
416
  parsedBoardOps.unshift({ op: 'plan.resetForGoal' })
407
417
  }
408
418
  const executedOps = permRankNow >= 1 && parsedBoardOps.length > 0 && deps.runAction
409
- ? applyBoardOps(deps, rootId, parsedBoardOps, { forceSessionOnly: autoPilot })
419
+ ? (() => {
420
+ updateChiefActiveWork(rootId, reviewWorkId, { tone: 'tasks', tab: 'tasks', label: '参谋长正在自动同步看板与计划中...' })
421
+ return applyBoardOps(deps, rootId, parsedBoardOps, { forceSessionOnly: autoPilot })
422
+ })()
410
423
  : []
411
424
 
412
425
  const unmetMustDo = Array.isArray(parsed.unmetMustDo)
@@ -763,6 +776,11 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
763
776
  const totalTokens = Number(liveUsage && liveUsage.totalTokens) || 0
764
777
  const seq = Math.max(0, Math.round(Number(liveUsage && liveUsage.seq) || digest.stamp || 0))
765
778
  const ratioPct = totalTokens > 0 ? (totalTokens / contextWindow) * 100 : 0
779
+ updateChiefActiveWork(rootId, reviewWorkId, {
780
+ tone: 'archive',
781
+ tab: 'archive',
782
+ label: '参谋长正在自动抢救归档与压缩中...',
783
+ })
766
784
  const cRes = await executeHarvestAndCompact(deps, {
767
785
  sid,
768
786
  rootId,
@@ -834,6 +852,12 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
834
852
  }
835
853
 
836
854
  if (permRankNow >= 1 && autoBoundUpdates.length > 0 && deps.runAction) {
855
+ updateChiefActiveWork(rootId, reviewWorkId, {
856
+ tone: 'bounds',
857
+ tab: 'boundaries',
858
+ boundSubTab: 'rules',
859
+ label: '参谋长正在自动维护本局边界中...',
860
+ })
837
861
  for (const b of autoBoundUpdates) {
838
862
  deps.runAction({
839
863
  action: 'bounds.add',
@@ -855,6 +879,11 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
855
879
  it => it.folder === 'inbox' || it.organizedBy !== 'chief' || (it.points || []).length <= 1,
856
880
  ).length
857
881
  if (unorgCount >= 3) {
882
+ updateChiefActiveWork(rootId, reviewWorkId, {
883
+ tone: 'archive',
884
+ tab: 'archive',
885
+ label: '参谋长正在自动整理本局档案中...',
886
+ })
858
887
  mutateChiefState((s) => {
859
888
  const ws = ensureWorkspace(s, rootId)
860
889
  ws.runtimeGuard.lastAutoArchiveOrgAt = Date.now()
@@ -928,6 +957,9 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
928
957
  circuitReason,
929
958
  ...(autoPilotStopRes ? { autoPilotStopped: Boolean(autoPilotStopRes.stopped) } : {}),
930
959
  }
960
+ } finally {
961
+ endChiefActiveWork(rootId, reviewWorkId)
962
+ }
931
963
  }
932
964
 
933
965
  /**