dsh-chief 1.5.0 → 1.6.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/board-schema.js CHANGED
@@ -8,7 +8,7 @@ import { normalizeMemory } from './memory.js'
8
8
 
9
9
  export const API = '/api/dsh-chief'
10
10
 
11
- export const BACKEND_BUILD = '1.5.0'
11
+ export const BACKEND_BUILD = '1.6.0'
12
12
 
13
13
  export const BOARD_VERSION = 1
14
14
 
@@ -252,6 +252,8 @@ export function normalizeTask(raw) {
252
252
  evidence: str(task.evidence, '').slice(0, 600),
253
253
  blockedBy: Array.isArray(task.blockedBy) ? task.blockedBy.map(item => str(item, '')).filter(Boolean) : [],
254
254
  parentId: str(task.parentId, '').slice(0, 200),
255
+ planStepId: str(task.planStepId, '').slice(0, 120),
256
+ targetPlanStepId: str(task.targetPlanStepId, '').slice(0, 120),
255
257
  assumptions: Array.isArray(task.assumptions) ? task.assumptions.map(a => ({
256
258
  text: str(a && a.text, '').slice(0, CAP_ASSUMPTION),
257
259
  verified: a && a.verified === true,
@@ -458,11 +460,15 @@ export function normalizeBoard(raw) {
458
460
  session: str(board.cursor && board.cursor.session, ''),
459
461
  },
460
462
  plan: plan
461
- .map(step => ({
462
- id: str(step && step.id, newId('s')),
463
- text: str(step && step.text, '').slice(0, 400),
464
- done: step && step.done === true,
465
- }))
463
+ .map(step => {
464
+ const cleanSummary = str(step && step.summary, '').trim().slice(0, 240)
465
+ return {
466
+ id: str(step && step.id, newId('s')),
467
+ text: str(step && step.text, '').slice(0, 400),
468
+ done: step && step.done === true,
469
+ ...(cleanSummary ? { summary: cleanSummary } : {}),
470
+ }
471
+ })
466
472
  .filter(step => step.text !== ''),
467
473
  tasks: tasks.map(normalizeTask).filter(task => task.title !== ''),
468
474
  notes: dedupeNotes(notes.map(normalizeNote).filter(note => note.title !== '' || note.body !== '')),
@@ -493,6 +499,15 @@ export function guardLogText(verdict, turn, remaining) {
493
499
  return '空转拦截:第 ' + turn + ' 轮同一个调用连着做了 ' + (loop.count || 0) + ' 次('
494
500
  + String(loop.name || '?').slice(0, 40) + ')结果没变' + tail
495
501
  }
502
+ if (verdict && verdict.kind === 'premature-promise') {
503
+ return '空转拦截:第 ' + turn + ' 轮口头预告「'
504
+ + String(verdict.promiseCue || '').slice(0, 40) + '」却未执行就收工' + tail
505
+ }
506
+ if (verdict && verdict.kind === 'mid-turn-spin') {
507
+ const spin = verdict.spin || verdict.loop || {}
508
+ return '运行中空转急刹:连续空转/报错 ' + (spin.count || 0) + ' 次('
509
+ + String(spin.name || '?').slice(0, 40) + ')已当场插话纠偏'
510
+ }
496
511
  if (verdict && verdict.kind === 'no-goal') {
497
512
  return '空转拦截:第 ' + turn + ' 轮板子处在 goal 模式却没有目标' + tail
498
513
  }
@@ -538,6 +553,8 @@ export function summary(board, subagents) {
538
553
  preset: task.preset || '',
539
554
  session: task.session,
540
555
  parentId: task.parentId || '',
556
+ planStepId: task.planStepId || '',
557
+ targetPlanStepId: task.targetPlanStepId || '',
541
558
  blockedBy: Array.isArray(task.blockedBy) ? task.blockedBy : [],
542
559
  intent: task.intent || '',
543
560
  evidence: task.evidence || '',
@@ -578,3 +595,311 @@ export function summary(board, subagents) {
578
595
  updatedAt: board.updatedAt,
579
596
  }
580
597
  }
598
+
599
+ /* ------------------------------------------------------ workflow pipeline */
600
+
601
+ /**
602
+ * Resolve which plan step ID is currently active for auto-attaching tasks/subagents.
603
+ * Prefers an open step matching `cursor.step`, then the first incomplete step,
604
+ * and finally the last step when all are done.
605
+ */
606
+ export function resolveActivePlanStepId(board) {
607
+ const plan = board && Array.isArray(board.plan) ? board.plan.filter(s => s && s.text) : []
608
+ if (!plan.length) return ''
609
+ const cursorStep = str(board && board.cursor && board.cursor.step, '').trim().toLowerCase()
610
+ if (cursorStep) {
611
+ const exact = plan.find(s => !s.done && str(s.text, '').trim().toLowerCase() === cursorStep)
612
+ if (exact) return exact.id
613
+ const prefix = plan.find(s => !s.done && (
614
+ str(s.text, '').trim().toLowerCase().startsWith(cursorStep)
615
+ || cursorStep.startsWith(str(s.text, '').trim().toLowerCase().slice(0, 24))
616
+ ))
617
+ if (prefix) return prefix.id
618
+ }
619
+ const firstOpen = plan.find(s => !s.done)
620
+ return firstOpen ? firstOpen.id : plan[plan.length - 1].id
621
+ }
622
+
623
+ function topoSortRootTasks(roots) {
624
+ if (roots.length <= 1) return roots.slice()
625
+ const byId = new Map(roots.map(t => [t.id, t]))
626
+ const inDeg = new Map(roots.map(t => [t.id, 0]))
627
+ const adj = new Map(roots.map(t => [t.id, []]))
628
+ for (const t of roots) {
629
+ const deps = Array.isArray(t.blockedBy) ? t.blockedBy : []
630
+ for (const depId of deps) {
631
+ if (byId.has(depId) && depId !== t.id) {
632
+ inDeg.set(t.id, (inDeg.get(t.id) || 0) + 1)
633
+ adj.get(depId).push(t.id)
634
+ }
635
+ }
636
+ }
637
+ const ready = roots.filter(t => (inDeg.get(t.id) || 0) === 0).sort((a, b) => (a.createdAt || 0) - (b.createdAt || 0))
638
+ const ordered = []
639
+ const placed = new Set()
640
+ while (ready.length) {
641
+ const cur = ready.shift()
642
+ if (!cur || placed.has(cur.id)) continue
643
+ placed.add(cur.id)
644
+ ordered.push(cur)
645
+ for (const nxtId of adj.get(cur.id) || []) {
646
+ const deg = (inDeg.get(nxtId) || 1) - 1
647
+ inDeg.set(nxtId, deg)
648
+ if (deg <= 0) {
649
+ ready.push(byId.get(nxtId))
650
+ ready.sort((a, b) => (a.createdAt || 0) - (b.createdAt || 0))
651
+ }
652
+ }
653
+ }
654
+ for (const t of roots) {
655
+ if (!placed.has(t.id)) ordered.push(t)
656
+ }
657
+ return ordered
658
+ }
659
+
660
+ function isInternalProbeAgentName(name) {
661
+ const raw = String(name || '').trim().replace(/^@/, '')
662
+ if (!raw) return false
663
+ const leaf = raw.split('/').pop() || raw
664
+ return /^mnemon-(?:review|run)(?:[-_]|$)/i.test(leaf)
665
+ }
666
+
667
+ /**
668
+ * Derive sequential workflow stages (`① -> ② -> ③ ...`), attached tasks,
669
+ * sprouted subagent branches, return-edge targets, and unified 4-state colors.
670
+ */
671
+ export function derivePlanFlowProgress(board, subagents = []) {
672
+ const safeBoard = board && typeof board === 'object' ? board : {}
673
+ const plan = Array.isArray(safeBoard.plan) ? safeBoard.plan.filter(s => s && s.text) : []
674
+ const tasks = Array.isArray(safeBoard.tasks) ? safeBoard.tasks.filter(t => t && t.title) : []
675
+ const rawAgents = Array.isArray(subagents) ? subagents.filter(a => a && a.name && a.name !== 'lead') : []
676
+ const visibleAgents = rawAgents.filter(a => !(isInternalProbeAgentName(a.name) && a.status !== 'running'))
677
+
678
+ let mode = 'empty'
679
+ let stages = []
680
+
681
+ if (plan.length > 0) {
682
+ mode = 'plan'
683
+ stages = plan.map((s, idx) => ({
684
+ id: str(s.id, `s-${idx + 1}`),
685
+ index: idx + 1,
686
+ text: str(s.text, ''),
687
+ done: s.done === true,
688
+ summary: str(s.summary, ''),
689
+ source: 'plan',
690
+ rootTaskId: '',
691
+ tasks: [],
692
+ agents: [],
693
+ returnEdges: [],
694
+ status: 'todo',
695
+ }))
696
+ } else if (tasks.length > 0) {
697
+ mode = 'task-root'
698
+ const taskIds = new Set(tasks.map(t => t.id))
699
+ const roots = topoSortRootTasks(tasks.filter(t => !t.parentId || !taskIds.has(t.parentId) || t.parentId === t.id))
700
+ stages = roots.map((t, idx) => ({
701
+ id: 's-' + t.id,
702
+ index: idx + 1,
703
+ text: t.title,
704
+ done: t.status === 'done',
705
+ summary: t.evidence || '',
706
+ source: 'task-root',
707
+ rootTaskId: t.id,
708
+ tasks: [],
709
+ agents: [],
710
+ returnEdges: [],
711
+ status: 'todo',
712
+ }))
713
+ } else if (visibleAgents.length > 0 || str(safeBoard.objective, '').trim()) {
714
+ mode = 'synthetic'
715
+ stages = [{
716
+ id: 'stage-main',
717
+ index: 1,
718
+ text: str(safeBoard.objective, '').trim() || '当前主线任务',
719
+ done: false,
720
+ summary: '',
721
+ source: 'synthetic',
722
+ rootTaskId: '',
723
+ tasks: [],
724
+ agents: [],
725
+ returnEdges: [],
726
+ status: 'todo',
727
+ }]
728
+ }
729
+
730
+ if (!stages.length) {
731
+ return {
732
+ mode: 'empty',
733
+ stages: [],
734
+ activeStageId: '',
735
+ orphanTasks: [],
736
+ stats: {
737
+ totalStages: 0,
738
+ doneStages: 0,
739
+ doingStages: 0,
740
+ blockedStages: 0,
741
+ totalAgents: 0,
742
+ runningAgents: 0,
743
+ doneAgents: 0,
744
+ },
745
+ }
746
+ }
747
+
748
+ const stageById = new Map(stages.map(s => [s.id, s]))
749
+ const taskById = new Map(tasks.map(t => [t.id, t]))
750
+ const activeStepId = resolveActivePlanStepId(safeBoard) || (stages.find(s => !s.done)?.id || stages[stages.length - 1].id)
751
+ const doneStagesRev = [...stages].reverse().find(s => s.done)
752
+ const lastDoneStepId = doneStagesRev ? doneStagesRev.id : activeStepId
753
+
754
+ const taskStageCache = new Map()
755
+ const resolveTaskStageId = (task, seen = new Set()) => {
756
+ if (!task) return ''
757
+ if (taskStageCache.has(task.id)) return taskStageCache.get(task.id)
758
+ let hitId = ''
759
+ if (task.planStepId && stageById.has(task.planStepId)) {
760
+ hitId = task.planStepId
761
+ } else if (stageById.has('s-' + task.id)) {
762
+ hitId = 's-' + task.id
763
+ } else {
764
+ const byPrefix = stages.find(s => s.text && task.title && s.text.startsWith(task.title))
765
+ if (byPrefix) hitId = byPrefix.id
766
+ }
767
+ if (!hitId && task.parentId && taskById.has(task.parentId) && !seen.has(task.id)) {
768
+ seen.add(task.id)
769
+ hitId = resolveTaskStageId(taskById.get(task.parentId), seen)
770
+ }
771
+ if (!hitId) {
772
+ if (task.status === 'done') hitId = lastDoneStepId || activeStepId
773
+ else hitId = activeStepId
774
+ }
775
+ taskStageCache.set(task.id, hitId)
776
+ return hitId
777
+ }
778
+
779
+ const orphanTasks = []
780
+ for (const t of tasks) {
781
+ const sid = resolveTaskStageId(t)
782
+ const st = sid ? stageById.get(sid) : null
783
+ if (st) st.tasks.push(t)
784
+ else orphanTasks.push(t)
785
+ }
786
+
787
+ const matchAgentTasks = agentObj => {
788
+ const aName = str(agentObj && agentObj.name, '').trim().toLowerCase()
789
+ const aLeaf = aName.split('/').pop()
790
+ const aId = str(agentObj && agentObj.id, '').trim()
791
+ const aTaskId = str(agentObj && agentObj.taskId, '').trim()
792
+ const aTaskIds = new Set(Array.isArray(agentObj && agentObj.tasks) ? agentObj.tasks.map(x => str(x && x.id, '').trim()).filter(Boolean) : [])
793
+ if (aTaskId) aTaskIds.add(aTaskId)
794
+ return tasks.filter(t => {
795
+ if (aTaskIds.has(t.id)) return true
796
+ if (aId && t.session && String(t.session) === aId) return true
797
+ const ref = str(t.subagent || t.owner, '').trim().toLowerCase()
798
+ if (!ref || ref === 'lead' || ref === 'agent' || ref === 'operator') return false
799
+ return ref === aName || (aLeaf && ref.split('/').pop() === aLeaf)
800
+ })
801
+ }
802
+
803
+ let runningAgents = 0
804
+ let doneAgents = 0
805
+ for (const agentObj of visibleAgents) {
806
+ const agentTasks = matchAgentTasks(agentObj)
807
+ const rawAgentSt = str(agentObj.status, '').trim().toLowerCase()
808
+ const hasBlockedTask = agentTasks.some(t => t.status === 'blocked')
809
+ const hasDoingTask = agentTasks.some(t => t.status === 'doing')
810
+ const hasOpenTask = agentTasks.some(t => t.status === 'todo' || t.status === 'doing' || t.status === 'blocked')
811
+ const allTasksDone = agentTasks.length > 0 && agentTasks.every(t => t.status === 'done')
812
+ const isAgentFailed = /error|fail|crash|blocked/.test(rawAgentSt)
813
+ const isAgentRunning = rawAgentSt === 'running' || rawAgentSt === 'active' || rawAgentSt === 'working'
814
+ const isAgentEnded = rawAgentSt !== '' && !isAgentRunning && !isAgentFailed && rawAgentSt !== 'todo' && rawAgentSt !== 'queued'
815
+
816
+ let agentStatus = 'todo'
817
+ if (hasBlockedTask || isAgentFailed) agentStatus = 'blocked'
818
+ else if (isAgentRunning || hasDoingTask) agentStatus = 'doing'
819
+ else if (allTasksDone || (isAgentEnded && !hasOpenTask)) agentStatus = 'done'
820
+
821
+ if (agentStatus === 'doing') runningAgents += 1
822
+ else if (agentStatus === 'done') doneAgents += 1
823
+
824
+ const primaryTask = agentTasks.find(t => t.status === 'doing' || t.status === 'blocked')
825
+ || agentTasks.find(t => t.status === 'todo')
826
+ || agentTasks[0]
827
+ || null
828
+
829
+ let fromStepId = primaryTask ? resolveTaskStageId(primaryTask) : ''
830
+ if (!fromStepId || !stageById.has(fromStepId)) {
831
+ fromStepId = agentStatus === 'done' ? (lastDoneStepId || activeStepId) : activeStepId
832
+ }
833
+ const rawTargetId = primaryTask && primaryTask.targetPlanStepId ? primaryTask.targetPlanStepId : ''
834
+ const toStepId = (rawTargetId && stageById.has(rawTargetId)) ? rawTargetId : fromStepId
835
+
836
+ const stage = stageById.get(fromStepId) || stages[0]
837
+ const node = {
838
+ name: str(agentObj.name, ''),
839
+ id: str(agentObj.id, ''),
840
+ parentId: str(agentObj.parentId, ''),
841
+ rawStatus: rawAgentSt,
842
+ agentStatus,
843
+ taskIds: agentTasks.map(t => t.id),
844
+ primaryTaskId: primaryTask ? primaryTask.id : '',
845
+ fromStepId: stage.id,
846
+ toStepId,
847
+ crossStep: toStepId !== stage.id,
848
+ }
849
+ stage.agents.push(node)
850
+ stage.returnEdges.push({
851
+ fromAgent: node.name,
852
+ taskId: node.primaryTaskId,
853
+ fromStepId: stage.id,
854
+ toStepId,
855
+ status: agentStatus,
856
+ crossStep: toStepId !== stage.id,
857
+ })
858
+ }
859
+
860
+ const firstOpenStage = stages.find(s => !s.done) || null
861
+ const hasAnyDone = stages.some(s => s.done)
862
+ const hasCursorStep = Boolean(str(safeBoard.cursor && safeBoard.cursor.step, '').trim())
863
+ const hasAnyActivity = hasAnyDone
864
+ || hasCursorStep
865
+ || tasks.some(t => t.status !== 'todo')
866
+ || visibleAgents.length > 0
867
+
868
+ let doneStages = 0
869
+ let doingStages = 0
870
+ let blockedStages = 0
871
+ for (const stage of stages) {
872
+ if (stage.done) {
873
+ stage.status = 'done'
874
+ doneStages += 1
875
+ } else if (stage.tasks.some(t => t.status === 'blocked') || stage.agents.some(a => a.agentStatus === 'blocked')) {
876
+ stage.status = 'blocked'
877
+ blockedStages += 1
878
+ } else if (
879
+ stage.tasks.some(t => t.status === 'doing')
880
+ || stage.agents.some(a => a.agentStatus === 'doing')
881
+ || (firstOpenStage && firstOpenStage.id === stage.id && hasAnyActivity)
882
+ ) {
883
+ stage.status = 'doing'
884
+ doingStages += 1
885
+ } else {
886
+ stage.status = 'todo'
887
+ }
888
+ }
889
+
890
+ return {
891
+ mode,
892
+ stages,
893
+ activeStageId: activeStepId,
894
+ orphanTasks,
895
+ stats: {
896
+ totalStages: stages.length,
897
+ doneStages,
898
+ doingStages,
899
+ blockedStages,
900
+ totalAgents: visibleAgents.length,
901
+ runningAgents,
902
+ doneAgents,
903
+ },
904
+ }
905
+ }
package/chief-archives.js CHANGED
@@ -420,6 +420,7 @@ export async function harvestTurnDetailsToArchive(deps, {
420
420
  try {
421
421
  const llmRes = await callChiefLlm(deps, {
422
422
  sessionId: rootId,
423
+ reasonKind: 'archive_harvest',
423
424
  system: HARVEST_ARCHIVE_SYSTEM,
424
425
  prompt: `触发模式:${trigger === 'pre-compaction' ? '上下文压缩前自动高保真抢救' : '用户手动抢救当前工作细节入柜'}\n\n${cleanMultiline(bodySource, 5200)}`,
425
426
  maxTokens: SUMMARY_MAX_TOKENS,
package/chief-commands.js CHANGED
@@ -1189,6 +1189,7 @@ export async function consolidateBoundsWithChief(deps, {
1189
1189
 
1190
1190
  const llmRes = await callChiefLlm(deps, {
1191
1191
  sessionId: rootId,
1192
+ reasonKind: 'consolidate_bounds',
1192
1193
  system: CONSOLIDATE_BOUNDS_SYSTEM,
1193
1194
  prompt,
1194
1195
  maxTokens: SUMMARY_MAX_TOKENS,
@@ -3205,6 +3206,7 @@ export async function suggestCoreObjectiveWithChief(deps, {
3205
3206
  try {
3206
3207
  const llmRes = await callChiefLlm(deps, {
3207
3208
  sessionId: rootId,
3209
+ reasonKind: 'suggest_objective',
3208
3210
  system: OBJECTIVE_SUGGEST_SYSTEM,
3209
3211
  prompt: promptLines.join('\n'),
3210
3212
  maxTokens: 320,
@@ -546,6 +546,7 @@ export async function recommendAndSetCompactThreshold(deps, { sessionId = '' } =
546
546
 
547
547
  const llmRes = await callChiefLlm(deps, {
548
548
  sessionId: rootId,
549
+ reasonKind: 'recommend_compact',
549
550
  system: COMPACT_ADVISOR_SYSTEM,
550
551
  prompt: advisorPrompt,
551
552
  maxTokens: 320,
package/chief-models.js CHANGED
@@ -15,6 +15,8 @@ import {
15
15
  resolveWorkspaceConfig,
16
16
  loadChiefState,
17
17
  mutateChiefState,
18
+ checkManagedBudgetBeforeCall,
19
+ recordChiefLlmUsage,
18
20
  } from './chief-state.js'
19
21
 
20
22
  let dshLlmModulePromise = null
@@ -480,6 +482,36 @@ function pickRouteFromItems(items, selectedRef, followRef, deps, sessionId, regi
480
482
  return queue[0] || null
481
483
  }
482
484
 
485
+ export function estimateTokensRough(text = '') {
486
+ const s = String(text || '')
487
+ if (!s) return 0
488
+ let cjk = 0
489
+ for (let i = 0; i < s.length; i += 1) {
490
+ const code = s.charCodeAt(i)
491
+ if (code >= 0x4E00 && code <= 0x9FFF) cjk += 1
492
+ }
493
+ const rest = s.length - cjk
494
+ return Math.max(1, Math.round(cjk * 0.72 + rest * 0.28))
495
+ }
496
+
497
+ function extractUsageMetrics(rawUsage, promptText = '', outputText = '') {
498
+ const u = rawUsage && typeof rawUsage === 'object' ? rawUsage : null
499
+ const inRaw = u ? Number(u.inputTokens ?? u.promptTokens ?? u.prompt_tokens ?? u.input_tokens ?? 0) : 0
500
+ const outRaw = u ? Number(u.outputTokens ?? u.completionTokens ?? u.completion_tokens ?? u.output_tokens ?? 0) : 0
501
+ if (Number.isFinite(inRaw) && Number.isFinite(outRaw) && (inRaw > 0 || outRaw > 0)) {
502
+ return {
503
+ inputTokens: Math.max(0, Math.round(inRaw)),
504
+ outputTokens: Math.max(0, Math.round(outRaw)),
505
+ estimated: false,
506
+ }
507
+ }
508
+ return {
509
+ inputTokens: estimateTokensRough(promptText),
510
+ outputTokens: estimateTokensRough(outputText),
511
+ estimated: true,
512
+ }
513
+ }
514
+
483
515
  async function callOneRoute(llm, route, system, userText, maxTokens = SUMMARY_MAX_TOKENS, sessionId = '', imageBlocks = [], desiredEffort = 'medium') {
484
516
  const caps = await resolveRouteCapabilities(llm, route.provider, route.model)
485
517
  const modelDefaultMaxTokens = caps.defaultMaxTokens || 0
@@ -491,6 +523,7 @@ async function callOneRoute(llm, route, system, userText, maxTokens = SUMMARY_MA
491
523
  const retryBudget = firstBudget < targetBudget ? targetBudget : SUMMARY_RETRY_MAX_TOKENS
492
524
  const budgets = retryBudget > firstBudget ? [firstBudget, retryBudget] : [firstBudget]
493
525
  const safeImages = Array.isArray(imageBlocks) ? imageBlocks : []
526
+ const promptBasis = `${system || ''}\n${userText || ''}`
494
527
 
495
528
  const runOnce = async (budget) => {
496
529
  const userContent = [...safeImages, { type: 'text', text: userText || '请查看附图并回答。' }]
@@ -508,8 +541,12 @@ async function callOneRoute(llm, route, system, userText, maxTokens = SUMMARY_MA
508
541
  const dshLlm = await loadDshLlm()
509
542
  if (dshLlm && typeof dshLlm.BlockAssembler === 'function') {
510
543
  const assembler = new dshLlm.BlockAssembler()
544
+ let streamUsage = null
511
545
  for await (const chunk of llm.stream(request)) {
512
546
  assembler.push(chunk)
547
+ if (chunk && typeof chunk === 'object' && (chunk.usage || chunk.type === 'usage')) {
548
+ streamUsage = chunk.usage || chunk
549
+ }
513
550
  }
514
551
  const finish = assembler.finish
515
552
  if (finish && (finish.kind === 'error' || finish.kind === 'aborted')) {
@@ -523,14 +560,19 @@ async function callOneRoute(llm, route, system, userText, maxTokens = SUMMARY_MA
523
560
  .map(b => b.text)
524
561
  .join('\n')
525
562
  .trim()
526
- return { text, finishKind: finish?.kind || '', modelRef: route.ref, thinkingEffort: effort || 'none' }
563
+ const usage = extractUsageMetrics(assembler.usage || finish?.usage || finish?.reason?.usage || streamUsage, promptBasis, text)
564
+ return { text, finishKind: finish?.kind || '', modelRef: route.ref, thinkingEffort: effort || 'none', usage }
527
565
  }
528
566
 
529
567
  // Pure standalone fallback stream reader (for unit tests / lightweight hosts)
530
568
  const parts = []
531
569
  let finishKind = ''
570
+ let streamUsage = null
532
571
  for await (const chunk of llm.stream(request)) {
533
572
  if (!chunk || typeof chunk !== 'object') continue
573
+ if (chunk.usage || chunk.type === 'usage') {
574
+ streamUsage = chunk.usage || chunk
575
+ }
534
576
  if (chunk.type === 'text-delta' || chunk.type === 'text_delta') {
535
577
  if (typeof chunk.text === 'string') parts.push(chunk.text)
536
578
  else if (typeof chunk.delta === 'string') parts.push(chunk.delta)
@@ -538,6 +580,7 @@ async function callOneRoute(llm, route, system, userText, maxTokens = SUMMARY_MA
538
580
  else if (typeof chunk.content === 'string') parts.push(chunk.content)
539
581
  else if (chunk.type === 'finish') {
540
582
  finishKind = chunk.reason?.kind || chunk.finishReason || ''
583
+ if (chunk.reason?.usage) streamUsage = chunk.reason.usage
541
584
  if (finishKind === 'error') {
542
585
  const err = new Error(chunk.reason?.failure?.message || 'LLM stream error')
543
586
  err.failure = chunk.reason?.failure
@@ -545,18 +588,26 @@ async function callOneRoute(llm, route, system, userText, maxTokens = SUMMARY_MA
545
588
  }
546
589
  }
547
590
  }
548
- return { text: parts.join('').trim(), finishKind, modelRef: route.ref, thinkingEffort: effort || 'none' }
591
+ const text = parts.join('').trim()
592
+ const usage = extractUsageMetrics(streamUsage, promptBasis, text)
593
+ return { text, finishKind, modelRef: route.ref, thinkingEffort: effort || 'none', usage }
549
594
  }
550
595
 
551
- let lastRes = { text: '', finishKind: '', modelRef: route.ref, thinkingEffort: effort || 'none' }
596
+ let lastRes = {
597
+ text: '',
598
+ finishKind: '',
599
+ modelRef: route.ref,
600
+ thinkingEffort: effort || 'none',
601
+ usage: extractUsageMetrics(null, promptBasis, ''),
602
+ }
552
603
  for (let i = 0; i < budgets.length; i += 1) {
553
604
  const res = await runOnce(budgets[i])
554
605
  lastRes = res
555
606
  if (res.text && res.finishKind !== 'max-tokens') {
556
- return { text: res.text, modelRef: res.modelRef, thinkingEffort: res.thinkingEffort }
607
+ return { text: res.text, modelRef: res.modelRef, thinkingEffort: res.thinkingEffort, usage: res.usage }
557
608
  }
558
609
  }
559
- return { text: lastRes.text, modelRef: lastRes.modelRef, thinkingEffort: lastRes.thinkingEffort }
610
+ return { text: lastRes.text, modelRef: lastRes.modelRef, thinkingEffort: lastRes.thinkingEffort, usage: lastRes.usage }
560
611
  }
561
612
 
562
613
  async function filterVisionRoutes(llm, queue) {
@@ -609,6 +660,20 @@ export async function callChiefLlm(deps, {
609
660
  })
610
661
  : cfgEffort
611
662
 
663
+ const budgetCheck = checkManagedBudgetBeforeCall(rootSid, reasonKind)
664
+ if (budgetCheck && !budgetCheck.allowed) {
665
+ return {
666
+ ok: false,
667
+ budgetExceeded: true,
668
+ budgetTripped: true,
669
+ error: budgetCheck.reason || '已触发托管硬预算熔断',
670
+ thinkingEffort: desiredEffort,
671
+ thinkingEffortMode,
672
+ }
673
+ }
674
+
675
+ const promptBasis = `${system || ''}\n${prompt || ''}`
676
+
612
677
  if (deps && typeof deps.callLlmOverride === 'function') {
613
678
  const overrideRes = await deps.callLlmOverride({
614
679
  sessionId,
@@ -622,9 +687,20 @@ export async function callChiefLlm(deps, {
622
687
  thinkingEffortMode,
623
688
  })
624
689
  if (overrideRes && typeof overrideRes === 'object') {
690
+ const usage = extractUsageMetrics(overrideRes.usage, promptBasis, overrideRes.text || '')
691
+ const ledgerRec = recordChiefLlmUsage(rootSid, {
692
+ reasonKind,
693
+ modelRef: overrideRes.modelRef || 'override',
694
+ inputTokens: usage.inputTokens,
695
+ outputTokens: usage.outputTokens,
696
+ estimated: usage.estimated,
697
+ ok: overrideRes.ok !== false,
698
+ })
625
699
  return {
626
700
  thinkingEffort: overrideRes.thinkingEffort || desiredEffort,
627
701
  thinkingEffortMode: overrideRes.thinkingEffortMode || thinkingEffortMode,
702
+ usage,
703
+ ...(ledgerRec && ledgerRec.tripped ? { budgetTripped: true } : {}),
628
704
  ...overrideRes,
629
705
  }
630
706
  }
@@ -669,6 +745,15 @@ export async function callChiefLlm(deps, {
669
745
  try {
670
746
  const res = await callOneRoute(llm, route, system, prompt, maxTokens, sessionId, sendImages, desiredEffort)
671
747
  if (res.text) {
748
+ const usage = res.usage || extractUsageMetrics(null, promptBasis, res.text)
749
+ const ledgerRec = recordChiefLlmUsage(rootSid, {
750
+ reasonKind,
751
+ modelRef: res.modelRef,
752
+ inputTokens: usage.inputTokens,
753
+ outputTokens: usage.outputTokens,
754
+ estimated: usage.estimated,
755
+ ok: true,
756
+ })
672
757
  return {
673
758
  ok: true,
674
759
  text: res.text,
@@ -676,6 +761,8 @@ export async function callChiefLlm(deps, {
676
761
  degradedToTextOnly,
677
762
  thinkingEffort: res.thinkingEffort || desiredEffort,
678
763
  thinkingEffortMode,
764
+ usage,
765
+ ...(ledgerRec && ledgerRec.tripped ? { budgetTripped: true } : {}),
679
766
  }
680
767
  }
681
768
  lastError = `${route.ref} 返回内容为空`
@@ -686,6 +773,15 @@ export async function callChiefLlm(deps, {
686
773
  try {
687
774
  const textRes = await callOneRoute(llm, route, system, prompt, maxTokens, sessionId, [], desiredEffort)
688
775
  if (textRes.text) {
776
+ const usage = textRes.usage || extractUsageMetrics(null, promptBasis, textRes.text)
777
+ const ledgerRec = recordChiefLlmUsage(rootSid, {
778
+ reasonKind,
779
+ modelRef: textRes.modelRef,
780
+ inputTokens: usage.inputTokens,
781
+ outputTokens: usage.outputTokens,
782
+ estimated: usage.estimated,
783
+ ok: true,
784
+ })
689
785
  return {
690
786
  ok: true,
691
787
  text: textRes.text,
@@ -693,6 +789,8 @@ export async function callChiefLlm(deps, {
693
789
  degradedToTextOnly: true,
694
790
  thinkingEffort: textRes.thinkingEffort || desiredEffort,
695
791
  thinkingEffortMode,
792
+ usage,
793
+ ...(ledgerRec && ledgerRec.tripped ? { budgetTripped: true } : {}),
696
794
  }
697
795
  }
698
796
  } catch {}
@@ -700,6 +798,15 @@ export async function callChiefLlm(deps, {
700
798
  markRouteFailure(route, err)
701
799
  }
702
800
  }
801
+ const failUsage = extractUsageMetrics(null, promptBasis, '')
802
+ recordChiefLlmUsage(rootSid, {
803
+ reasonKind,
804
+ modelRef: queue[0] ? queue[0].ref : '',
805
+ inputTokens: failUsage.inputTokens,
806
+ outputTokens: 0,
807
+ estimated: true,
808
+ ok: false,
809
+ })
703
810
  return { ok: false, error: lastError, degradedToTextOnly, thinkingEffort: desiredEffort, thinkingEffortMode }
704
811
  }
705
812