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/chief-state.js CHANGED
@@ -99,6 +99,264 @@ export const DEFAULT_MANAGED_IDLE_TIMEOUT_MS = 15 * 60 * 1000
99
99
 
100
100
  export const CHIEF_THINKING_EFFORTS = ['auto', 'off', 'low', 'medium', 'high', 'xhigh']
101
101
 
102
+ export const ALERT_EVENTS_CAP = 20
103
+
104
+ export const LLM_LEDGER_RECENT_CAP = 20
105
+
106
+ export const DEFAULT_MANAGED_BUDGET_MAX_CALLS = 30
107
+
108
+ export const DEFAULT_MANAGED_BUDGET_MAX_TOKENS = 300_000
109
+
110
+ export const CHIEF_UI_LANGS = ['auto', 'zh', 'en']
111
+
112
+ export const CHIEF_SCENARIO_PRESETS = {
113
+ observer: {
114
+ id: 'observer',
115
+ permissionMode: 'advisor',
116
+ runMode: 'off',
117
+ thinkingEffort: 'low',
118
+ tacticalModes: {
119
+ intervention: false,
120
+ autoCompact: false,
121
+ smartCompact: false,
122
+ redlineSentinel: false,
123
+ },
124
+ notifyEnabled: true,
125
+ },
126
+ collab: {
127
+ id: 'collab',
128
+ permissionMode: 'strategist',
129
+ runMode: 'patrol',
130
+ thinkingEffort: 'auto',
131
+ tacticalModes: {
132
+ intervention: false,
133
+ redlineSentinel: true,
134
+ },
135
+ notifyEnabled: true,
136
+ },
137
+ away: {
138
+ id: 'away',
139
+ permissionMode: 'chief',
140
+ runMode: 'managed',
141
+ thinkingEffort: 'auto',
142
+ tacticalModes: {
143
+ autoCompact: true,
144
+ compactThresholdMode: 'pct',
145
+ compactThresholdPct: 80,
146
+ redlineSentinel: true,
147
+ },
148
+ notifyEnabled: true,
149
+ managedBudgetMaxCalls: DEFAULT_MANAGED_BUDGET_MAX_CALLS,
150
+ managedBudgetMaxTokens: DEFAULT_MANAGED_BUDGET_MAX_TOKENS,
151
+ },
152
+ }
153
+
154
+ export function normalizeUiLang(raw) {
155
+ const s = typeof raw === 'string' ? raw.trim().toLowerCase() : ''
156
+ if (s === 'zh' || s === 'zh-cn' || s === 'zh-hans') return 'zh'
157
+ if (s === 'en' || s === 'en-us' || s === 'en-gb') return 'en'
158
+ return 'auto'
159
+ }
160
+
161
+ export function normalizeManagedBudgetCalls(raw) {
162
+ if (raw === 0 || raw === '0') return 0
163
+ const n = Number(raw)
164
+ if (!Number.isFinite(n)) return DEFAULT_MANAGED_BUDGET_MAX_CALLS
165
+ if (n <= 0) return 0
166
+ return Math.min(500, Math.max(3, Math.round(n)))
167
+ }
168
+
169
+ export function normalizeManagedBudgetTokens(raw) {
170
+ if (raw === 0 || raw === '0') return 0
171
+ const n = Number(raw)
172
+ if (!Number.isFinite(n)) return DEFAULT_MANAGED_BUDGET_MAX_TOKENS
173
+ if (n <= 0) return 0
174
+ return Math.min(5_000_000, Math.max(10_000, Math.round(n)))
175
+ }
176
+
177
+ export function classifyChiefLlmCategory(reasonKind = '') {
178
+ const rk = String(reasonKind || '').trim().toLowerCase()
179
+ if (!rk) return 'chat'
180
+ if (
181
+ rk === 'dream_roam'
182
+ || rk === 'precipitate'
183
+ || rk === 'distill'
184
+ || rk.startsWith('archive_')
185
+ ) {
186
+ return 'dream'
187
+ }
188
+ if (
189
+ rk === 'turn_review'
190
+ || rk === 'auto_summary'
191
+ || rk === 'chat_summary'
192
+ || rk === 'wall_blocked'
193
+ || rk === 'strong_intervention'
194
+ || rk === 'hazard_diagnosis'
195
+ || rk === 'idle_watchdog'
196
+ || rk === 'config_activated'
197
+ ) {
198
+ return 'review'
199
+ }
200
+ if (
201
+ rk === 'ask_chief'
202
+ || rk === 'consult_chief'
203
+ || rk === 'blank_explore'
204
+ || rk === 'craft_wall'
205
+ || rk === 'extract_bounds'
206
+ || rk === 'consolidate_bounds'
207
+ || rk === 'suggest_objective'
208
+ || rk === 'recommend_compact'
209
+ ) {
210
+ return 'chat'
211
+ }
212
+ return 'other'
213
+ }
214
+
215
+ const LLM_LEDGER_CALLS_MAX = 1_000_000
216
+ const LLM_LEDGER_TOKENS_MAX = 1_000_000_000
217
+
218
+ export function emptyLlmLedger() {
219
+ return {
220
+ totalCalls: 0,
221
+ totalInputTokens: 0,
222
+ totalOutputTokens: 0,
223
+ totalTokens: 0,
224
+ byCategory: {
225
+ chat: { calls: 0, tokens: 0 },
226
+ review: { calls: 0, tokens: 0 },
227
+ dream: { calls: 0, tokens: 0 },
228
+ other: { calls: 0, tokens: 0 },
229
+ },
230
+ managedRun: {
231
+ startedAt: 0,
232
+ calls: 0,
233
+ tokens: 0,
234
+ tripped: false,
235
+ trippedAt: 0,
236
+ trippedReason: '',
237
+ },
238
+ recent: [],
239
+ }
240
+ }
241
+
242
+ export function normalizeLlmLedger(raw) {
243
+ const base = emptyLlmLedger()
244
+ if (!raw || typeof raw !== 'object') return base
245
+ const nonNegTs = v => Math.max(0, Math.round(Number(v) || 0))
246
+ const clampCalls = v => Math.min(LLM_LEDGER_CALLS_MAX, Math.max(0, Math.round(Number(v) || 0)))
247
+ const clampTokens = v => Math.min(LLM_LEDGER_TOKENS_MAX, Math.max(0, Math.round(Number(v) || 0)))
248
+ base.totalCalls = clampCalls(raw.totalCalls)
249
+ base.totalInputTokens = clampTokens(raw.totalInputTokens)
250
+ base.totalOutputTokens = clampTokens(raw.totalOutputTokens)
251
+ base.totalTokens = clampTokens(raw.totalTokens) || clampTokens(base.totalInputTokens + base.totalOutputTokens)
252
+ const rawCats = raw.byCategory && typeof raw.byCategory === 'object' ? raw.byCategory : {}
253
+ for (const k of ['chat', 'review', 'dream', 'other']) {
254
+ const c = rawCats[k] && typeof rawCats[k] === 'object' ? rawCats[k] : {}
255
+ base.byCategory[k] = { calls: clampCalls(c.calls), tokens: clampTokens(c.tokens) }
256
+ }
257
+ const mr = raw.managedRun && typeof raw.managedRun === 'object' ? raw.managedRun : {}
258
+ base.managedRun = {
259
+ startedAt: nonNegTs(mr.startedAt),
260
+ calls: clampCalls(mr.calls),
261
+ tokens: clampTokens(mr.tokens),
262
+ tripped: Boolean(mr.tripped),
263
+ trippedAt: nonNegTs(mr.trippedAt),
264
+ trippedReason: clamp(mr.trippedReason || '', 220),
265
+ }
266
+ base.recent = (Array.isArray(raw.recent) ? raw.recent : [])
267
+ .filter(r => r && typeof r === 'object')
268
+ .slice(-LLM_LEDGER_RECENT_CAP)
269
+ .map(r => {
270
+ const inTok = clampTokens(r.inputTokens)
271
+ const outTok = clampTokens(r.outputTokens)
272
+ return {
273
+ id: typeof r.id === 'string' && r.id ? r.id : nextId('llm'),
274
+ at: nonNegTs(r.at) || Date.now(),
275
+ category: ['chat', 'review', 'dream', 'other'].includes(r.category) ? r.category : 'other',
276
+ reasonKind: clamp(r.reasonKind || '', 40),
277
+ modelRef: clamp(r.modelRef || '', 80),
278
+ inputTokens: inTok,
279
+ outputTokens: outTok,
280
+ totalTokens: clampTokens(r.totalTokens) || clampTokens(inTok + outTok),
281
+ estimated: Boolean(r.estimated),
282
+ ok: r.ok !== false,
283
+ }
284
+ })
285
+ return base
286
+ }
287
+
288
+ export function summarizeLlmLedger(rawLedger, cfg = null) {
289
+ const ledger = normalizeLlmLedger(rawLedger)
290
+ const maxCalls = cfg && cfg.managedBudgetMaxCalls !== undefined
291
+ ? normalizeManagedBudgetCalls(cfg.managedBudgetMaxCalls)
292
+ : DEFAULT_MANAGED_BUDGET_MAX_CALLS
293
+ const maxTokens = cfg && cfg.managedBudgetMaxTokens !== undefined
294
+ ? normalizeManagedBudgetTokens(cfg.managedBudgetMaxTokens)
295
+ : DEFAULT_MANAGED_BUDGET_MAX_TOKENS
296
+ return {
297
+ totalCalls: ledger.totalCalls,
298
+ totalInputTokens: ledger.totalInputTokens,
299
+ totalOutputTokens: ledger.totalOutputTokens,
300
+ totalTokens: ledger.totalTokens,
301
+ byCategory: {
302
+ chat: { ...ledger.byCategory.chat },
303
+ review: { ...ledger.byCategory.review },
304
+ dream: { ...ledger.byCategory.dream },
305
+ other: { ...ledger.byCategory.other },
306
+ },
307
+ managedRun: { ...ledger.managedRun },
308
+ budget: {
309
+ maxCalls,
310
+ maxTokens,
311
+ },
312
+ recent: ledger.recent.slice(-8),
313
+ }
314
+ }
315
+
316
+ export function normalizeAlertEvent(raw) {
317
+ if (!raw || typeof raw !== 'object') return null
318
+ const title = clamp(raw.title || '', 100)
319
+ if (!title) return null
320
+ const validKinds = [
321
+ 'pending_approval',
322
+ 'pending_elevation',
323
+ 'guard_wall_blocked',
324
+ 'auto_continue_rescue',
325
+ 'managed_auto_sleep',
326
+ 'budget_circuit_break',
327
+ 'hazard_halt',
328
+ ]
329
+ const kind = validKinds.includes(raw.kind) ? raw.kind : 'pending_approval'
330
+ const level = ['info', 'warn', 'danger', 'success'].includes(raw.level) ? raw.level : 'info'
331
+ return {
332
+ id: typeof raw.id === 'string' && raw.id ? raw.id : nextId('alt'),
333
+ kind,
334
+ level,
335
+ title,
336
+ body: clamp(raw.body || '', 220),
337
+ dedupeKey: clamp(raw.dedupeKey || '', 100),
338
+ at: Number(raw.at) || Date.now(),
339
+ }
340
+ }
341
+
342
+ export function pushAlertEventToWs(ws, spec = {}) {
343
+ if (!ws || typeof ws !== 'object') return null
344
+ if (!Array.isArray(ws.alertEvents)) ws.alertEvents = []
345
+ const norm = normalizeAlertEvent(spec)
346
+ if (!norm) return null
347
+ if (norm.dedupeKey) {
348
+ const dup = ws.alertEvents.find(
349
+ a => a && a.dedupeKey === norm.dedupeKey && Math.abs(norm.at - (Number(a.at) || 0)) < 5_000,
350
+ )
351
+ if (dup) return dup
352
+ }
353
+ ws.alertEvents.push(norm)
354
+ if (ws.alertEvents.length > ALERT_EVENTS_CAP) {
355
+ ws.alertEvents = ws.alertEvents.slice(-ALERT_EVENTS_CAP)
356
+ }
357
+ return norm
358
+ }
359
+
102
360
  export function normalizeRunMode(raw, fallbackCfg = null) {
103
361
  const s = typeof raw === 'string' ? raw.trim().toLowerCase() : ''
104
362
  if (s === 'off' || s === 'patrol' || s === 'managed') return s
@@ -753,6 +1011,8 @@ function emptyWorkspace() {
753
1011
  lastAutoArchiveOrgAt: 0,
754
1012
  },
755
1013
  flippedPrecipitatedIds: [],
1014
+ llmLedger: emptyLlmLedger(),
1015
+ alertEvents: [],
756
1016
  }
757
1017
  }
758
1018
 
@@ -1004,6 +1264,11 @@ function normalizeWorkspace(raw) {
1004
1264
  permissionMode: rawPerm,
1005
1265
  runMode: rm,
1006
1266
  managedIdleTimeoutMs,
1267
+ ...(typeof src.config.notifyEnabled === 'boolean' ? { notifyEnabled: src.config.notifyEnabled } : {}),
1268
+ ...(typeof src.config.notifySound === 'boolean' ? { notifySound: src.config.notifySound } : {}),
1269
+ ...(typeof src.config.uiLang === 'string' ? { uiLang: normalizeUiLang(src.config.uiLang) } : {}),
1270
+ ...(src.config.managedBudgetMaxCalls !== undefined ? { managedBudgetMaxCalls: normalizeManagedBudgetCalls(src.config.managedBudgetMaxCalls) } : {}),
1271
+ ...(src.config.managedBudgetMaxTokens !== undefined ? { managedBudgetMaxTokens: normalizeManagedBudgetTokens(src.config.managedBudgetMaxTokens) } : {}),
1007
1272
  ...(typeof src.config.thinkingEffort === 'string' ? { thinkingEffort: normalizeThinkingEffort(src.config.thinkingEffort) } : {}),
1008
1273
  ...(typeof src.config.teamEffortMode === 'string' ? { teamEffortMode: normalizeTeamEffortMode(src.config.teamEffortMode) } : {}),
1009
1274
  ...(Object.keys(lockedModelEfforts).length ? { lockedModelEfforts } : {}),
@@ -1018,6 +1283,11 @@ function normalizeWorkspace(raw) {
1018
1283
  base.flippedPrecipitatedIds = Array.isArray(src.flippedPrecipitatedIds)
1019
1284
  ? [...new Set(src.flippedPrecipitatedIds.map(x => String(x || '').trim()).filter(Boolean))].slice(0, 20)
1020
1285
  : []
1286
+ base.llmLedger = normalizeLlmLedger(src.llmLedger)
1287
+ base.alertEvents = (Array.isArray(src.alertEvents) ? src.alertEvents : [])
1288
+ .map(normalizeAlertEvent)
1289
+ .filter(Boolean)
1290
+ .slice(-ALERT_EVENTS_CAP)
1021
1291
  return base
1022
1292
  }
1023
1293
 
@@ -1139,11 +1409,37 @@ export function resolveWorkspaceConfig(state, sessionId = '') {
1139
1409
  : (Number.isFinite(Number(base.managedIdleTimeoutMs)) && Number(base.managedIdleTimeoutMs) >= 50
1140
1410
  ? Math.min(2 * 60 * 60 * 1000, Math.round(Number(base.managedIdleTimeoutMs)))
1141
1411
  : DEFAULT_MANAGED_IDLE_TIMEOUT_MS)
1412
+ const notifyEnabled = typeof (wsCfg && wsCfg.notifyEnabled) === 'boolean'
1413
+ ? wsCfg.notifyEnabled
1414
+ : (typeof base.notifyEnabled === 'boolean' ? base.notifyEnabled : true)
1415
+ const notifySound = typeof (wsCfg && wsCfg.notifySound) === 'boolean'
1416
+ ? wsCfg.notifySound
1417
+ : (typeof base.notifySound === 'boolean' ? base.notifySound : false)
1418
+ const uiLang = normalizeUiLang(
1419
+ (wsCfg && typeof wsCfg.uiLang === 'string' && wsCfg.uiLang)
1420
+ || (typeof base.uiLang === 'string' && base.uiLang)
1421
+ || 'auto',
1422
+ )
1423
+ const managedBudgetMaxCalls = (wsCfg && wsCfg.managedBudgetMaxCalls !== undefined)
1424
+ ? normalizeManagedBudgetCalls(wsCfg.managedBudgetMaxCalls)
1425
+ : (base.managedBudgetMaxCalls !== undefined
1426
+ ? normalizeManagedBudgetCalls(base.managedBudgetMaxCalls)
1427
+ : DEFAULT_MANAGED_BUDGET_MAX_CALLS)
1428
+ const managedBudgetMaxTokens = (wsCfg && wsCfg.managedBudgetMaxTokens !== undefined)
1429
+ ? normalizeManagedBudgetTokens(wsCfg.managedBudgetMaxTokens)
1430
+ : (base.managedBudgetMaxTokens !== undefined
1431
+ ? normalizeManagedBudgetTokens(base.managedBudgetMaxTokens)
1432
+ : DEFAULT_MANAGED_BUDGET_MAX_TOKENS)
1142
1433
  return {
1143
1434
  modelRef,
1144
1435
  paceMode,
1145
1436
  runMode,
1146
1437
  managedIdleTimeoutMs,
1438
+ notifyEnabled,
1439
+ notifySound,
1440
+ uiLang,
1441
+ managedBudgetMaxCalls,
1442
+ managedBudgetMaxTokens,
1147
1443
  thinkingEffort,
1148
1444
  teamEffortMode,
1149
1445
  lockedModelEfforts,
@@ -1234,6 +1530,11 @@ function normalizeState(raw) {
1234
1530
  managedIdleTimeoutMs: Number.isFinite(Number(cfg.managedIdleTimeoutMs)) && Number(cfg.managedIdleTimeoutMs) >= 50
1235
1531
  ? Math.min(2 * 60 * 60 * 1000, Math.round(Number(cfg.managedIdleTimeoutMs)))
1236
1532
  : DEFAULT_MANAGED_IDLE_TIMEOUT_MS,
1533
+ notifyEnabled: typeof cfg.notifyEnabled === 'boolean' ? cfg.notifyEnabled : true,
1534
+ notifySound: typeof cfg.notifySound === 'boolean' ? cfg.notifySound : false,
1535
+ uiLang: normalizeUiLang(cfg.uiLang),
1536
+ managedBudgetMaxCalls: normalizeManagedBudgetCalls(cfg.managedBudgetMaxCalls),
1537
+ managedBudgetMaxTokens: normalizeManagedBudgetTokens(cfg.managedBudgetMaxTokens),
1237
1538
  thinkingEffort: normalizeThinkingEffort(cfg.thinkingEffort),
1238
1539
  teamEffortMode: normalizeTeamEffortMode(cfg.teamEffortMode),
1239
1540
  stopped,
@@ -1279,6 +1580,14 @@ export function enqueueApprovalToWs(ws, item = {}) {
1279
1580
  if (ws.pendingApprovals.length > APPROVALS_CAP) {
1280
1581
  ws.pendingApprovals = ws.pendingApprovals.slice(-APPROVALS_CAP)
1281
1582
  }
1583
+ pushAlertEventToWs(ws, {
1584
+ kind: 'pending_approval',
1585
+ level: 'warn',
1586
+ title: '🔐 等待人类逐项审批',
1587
+ body: clamp(`${norm.operationLabel}${norm.targetLabel ? ' · ' + norm.targetLabel : ''}`, 180),
1588
+ dedupeKey: 'apr:' + norm.id,
1589
+ at: now,
1590
+ })
1282
1591
  return norm
1283
1592
  }
1284
1593
 
@@ -1320,6 +1629,14 @@ export function enqueueElevationToWs(ws, req = {}) {
1320
1629
  outcome: 'pending',
1321
1630
  by: norm.by,
1322
1631
  }, req.sessionId || '')
1632
+ pushAlertEventToWs(ws, {
1633
+ kind: 'pending_elevation',
1634
+ level: 'warn',
1635
+ title: '⬆️ 参谋申请提权',
1636
+ body: clamp(`${CHIEF_PERMISSION_META[currentMode].level} -> ${CHIEF_PERMISSION_META[targetMode].level}:${norm.reason}`, 180),
1637
+ dedupeKey: 'elv:' + norm.id,
1638
+ at: now,
1639
+ })
1323
1640
  return norm
1324
1641
  }
1325
1642
 
@@ -1941,7 +2258,19 @@ export function deployChiefWorkspaceState(deps, {
1941
2258
  /* -------------------------------------------------------------------------- */
1942
2259
 
1943
2260
  export function updateChiefConfig(patch) {
1944
- const safePatch = patch && typeof patch === 'object' ? patch : {}
2261
+ const rawInput = patch && typeof patch === 'object' ? patch : {}
2262
+ const rawPreset = typeof rawInput.preset === 'string' ? rawInput.preset.trim().toLowerCase() : ''
2263
+ const presetSpec = CHIEF_SCENARIO_PRESETS[rawPreset] || null
2264
+ const safePatch = presetSpec
2265
+ ? {
2266
+ ...presetSpec,
2267
+ ...rawInput,
2268
+ tacticalModes: {
2269
+ ...(presetSpec.tacticalModes || {}),
2270
+ ...(rawInput.tacticalModes && typeof rawInput.tacticalModes === 'object' ? rawInput.tacticalModes : {}),
2271
+ },
2272
+ }
2273
+ : rawInput
1945
2274
  const sid = String(safePatch.sessionId || safePatch.session || '').trim() || 'global'
1946
2275
  return mutateChiefState((state) => {
1947
2276
  const ws = ensureWorkspace(state, sid)
@@ -2138,6 +2467,34 @@ export function updateChiefConfig(patch) {
2138
2467
  ws.runtimeGuard.managedStartedAt = now
2139
2468
  ws.runtimeGuard.lastActivityAt = now
2140
2469
  ws.runtimeGuard.autoPilotHadTurn = false
2470
+ ws.llmLedger = normalizeLlmLedger(ws.llmLedger)
2471
+ ws.llmLedger.managedRun = {
2472
+ startedAt: now,
2473
+ calls: 0,
2474
+ tokens: 0,
2475
+ tripped: false,
2476
+ trippedAt: 0,
2477
+ trippedReason: '',
2478
+ }
2479
+ }
2480
+ if (ws && !wantsAutoPilot && safePatch.runMode === 'patrol' && ws.llmLedger && ws.llmLedger.managedRun && ws.llmLedger.managedRun.tripped) {
2481
+ ws.llmLedger.managedRun.tripped = false
2482
+ ws.llmLedger.managedRun.trippedAt = 0
2483
+ ws.llmLedger.managedRun.trippedReason = ''
2484
+ }
2485
+ if (ws && safePatch.resetManagedBudget === true) {
2486
+ ws.llmLedger = normalizeLlmLedger(ws.llmLedger)
2487
+ ws.llmLedger.managedRun = {
2488
+ startedAt: Date.now(),
2489
+ calls: 0,
2490
+ tokens: 0,
2491
+ tripped: false,
2492
+ trippedAt: 0,
2493
+ trippedReason: '',
2494
+ }
2495
+ }
2496
+ if (ws && safePatch.resetLlmLedger === true) {
2497
+ ws.llmLedger = emptyLlmLedger()
2141
2498
  }
2142
2499
 
2143
2500
  let compactLowWarning = ''
@@ -2169,6 +2526,15 @@ export function updateChiefConfig(patch) {
2169
2526
  if (Number.isFinite(Number(safePatch.managedIdleTimeoutMs)) && Number(safePatch.managedIdleTimeoutMs) >= 50) {
2170
2527
  targetCfg.managedIdleTimeoutMs = Math.min(2 * 60 * 60 * 1000, Math.round(Number(safePatch.managedIdleTimeoutMs)))
2171
2528
  }
2529
+ if (typeof safePatch.notifyEnabled === 'boolean') targetCfg.notifyEnabled = safePatch.notifyEnabled
2530
+ if (typeof safePatch.notifySound === 'boolean') targetCfg.notifySound = safePatch.notifySound
2531
+ if (typeof safePatch.uiLang === 'string') targetCfg.uiLang = normalizeUiLang(safePatch.uiLang)
2532
+ if (safePatch.managedBudgetMaxCalls !== undefined) {
2533
+ targetCfg.managedBudgetMaxCalls = normalizeManagedBudgetCalls(safePatch.managedBudgetMaxCalls)
2534
+ }
2535
+ if (safePatch.managedBudgetMaxTokens !== undefined) {
2536
+ targetCfg.managedBudgetMaxTokens = normalizeManagedBudgetTokens(safePatch.managedBudgetMaxTokens)
2537
+ }
2172
2538
  if (allowLocks && (
2173
2539
  (safePatch.lockedModelEfforts && typeof safePatch.lockedModelEfforts === 'object')
2174
2540
  || (safePatch.toggleLockAgentEffort && typeof safePatch.toggleLockAgentEffort === 'object')
@@ -2265,6 +2631,11 @@ export function updateChiefConfig(patch) {
2265
2631
  thinkingEffort: effBefore.thinkingEffort || 'auto',
2266
2632
  teamEffortMode: effBefore.teamEffortMode || 'auto',
2267
2633
  managedIdleTimeoutMs: effBefore.managedIdleTimeoutMs || DEFAULT_MANAGED_IDLE_TIMEOUT_MS,
2634
+ notifyEnabled: effBefore.notifyEnabled !== false,
2635
+ notifySound: Boolean(effBefore.notifySound),
2636
+ uiLang: effBefore.uiLang || 'auto',
2637
+ managedBudgetMaxCalls: effBefore.managedBudgetMaxCalls ?? DEFAULT_MANAGED_BUDGET_MAX_CALLS,
2638
+ managedBudgetMaxTokens: effBefore.managedBudgetMaxTokens ?? DEFAULT_MANAGED_BUDGET_MAX_TOKENS,
2268
2639
  lockedModelEfforts: { ...(effBefore.lockedModelEfforts || {}) },
2269
2640
  permissionMode: effBefore.permissionMode || DEFAULT_CHIEF_PERMISSION_MODE,
2270
2641
  tacticalModes: { ...effBefore.tacticalModes },
@@ -2329,8 +2700,10 @@ export function updateChiefConfig(patch) {
2329
2700
  }
2330
2701
  return {
2331
2702
  ok: true,
2703
+ ...(presetSpec ? { appliedPreset: presetSpec.id } : {}),
2332
2704
  ...(compactLowWarning ? { compactLowWarning } : {}),
2333
2705
  config: { ...finalCfg, tacticalModes: { ...finalCfg.tacticalModes } },
2706
+ llmLedger: summarizeLlmLedger(ws.llmLedger, finalCfg),
2334
2707
  }
2335
2708
  })
2336
2709
  }
@@ -2521,3 +2894,185 @@ export function getChiefActiveWork(rootSessionId) {
2521
2894
  }
2522
2895
  return { ...cur }
2523
2896
  }
2897
+
2898
+ /** Persist a critical alert event onto a workspace so UI can fire desktop notifications / gentle chimes without replay storms. */
2899
+ export function recordWorkspaceAlertEvent(rootSessionId, spec = {}) {
2900
+ const key = String(rootSessionId || 'global').trim() || 'global'
2901
+ try {
2902
+ return mutateChiefState((state) => {
2903
+ const ws = ensureWorkspace(state, key)
2904
+ return pushAlertEventToWs(ws, spec)
2905
+ })
2906
+ } catch {
2907
+ return null
2908
+ }
2909
+ }
2910
+
2911
+ function tripManagedBudgetCircuit(state, ws, rootId, reason) {
2912
+ const now = Date.now()
2913
+ const effNow = resolveWorkspaceConfig(state, rootId)
2914
+ if (!ws.config || typeof ws.config !== 'object') ws.config = { ...effNow }
2915
+ ws.config.runMode = 'off'
2916
+ ws.config.paceMode = 'manual'
2917
+ ws.config.autoPilot = false
2918
+ ws.config.autoReview = false
2919
+ ws.config.tacticalModes = { ...normalizeTacticalModes(ws.config.tacticalModes), intervention: false }
2920
+ if (state.config && (state.config.runMode === 'managed' || state.config.paceMode === 'auto')) {
2921
+ state.config.runMode = 'off'
2922
+ state.config.paceMode = 'manual'
2923
+ state.config.autoPilot = false
2924
+ state.config.autoReview = false
2925
+ }
2926
+ ws.llmLedger = normalizeLlmLedger(ws.llmLedger)
2927
+ ws.llmLedger.managedRun.tripped = true
2928
+ ws.llmLedger.managedRun.trippedAt = now
2929
+ ws.llmLedger.managedRun.trippedReason = clamp(reason || '已触及托管硬预算上限,自动熔断休眠', 200)
2930
+ ws.chat.push({
2931
+ id: nextId('chat'),
2932
+ role: 'chief',
2933
+ kind: 'receipt',
2934
+ text: `- 【🛑 托管硬预算熔断】${ws.llmLedger.managedRun.trippedReason}\n- 已自动将运行模式退回「⏸ 关停」(人工问答仍可随时使用),保护 Token 费用。`,
2935
+ actions: ['🛑 硬预算熔断'],
2936
+ at: now,
2937
+ })
2938
+ if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
2939
+ pushAuditToWs(ws, {
2940
+ mode: effNow.permissionMode,
2941
+ stage: 'budget_guard',
2942
+ rule: 'managed_budget_exceeded',
2943
+ decision: 'tripped',
2944
+ operation: '托管硬预算上限熔断',
2945
+ target: rootId,
2946
+ reason: ws.llmLedger.managedRun.trippedReason,
2947
+ outcome: 'blocked',
2948
+ by: 'chief',
2949
+ }, rootId)
2950
+ pushAlertEventToWs(ws, {
2951
+ kind: 'budget_circuit_break',
2952
+ level: 'danger',
2953
+ title: '🛑 托管已达预算上限并熔断',
2954
+ body: ws.llmLedger.managedRun.trippedReason,
2955
+ dedupeKey: `budget:${rootId}:${ws.llmLedger.managedRun.startedAt || 0}`,
2956
+ at: now,
2957
+ })
2958
+ return ws.llmLedger.managedRun.trippedReason
2959
+ }
2960
+
2961
+ /** Check before background Managed LLM calls; never blocks human-initiated chat or consultation. */
2962
+ export function checkManagedBudgetBeforeCall(rootSessionId, reasonKind = '') {
2963
+ const rootId = String(rootSessionId || 'global').trim() || 'global'
2964
+ const category = classifyChiefLlmCategory(reasonKind)
2965
+ if (category !== 'review' && category !== 'dream') {
2966
+ return { allowed: true, category }
2967
+ }
2968
+ const st = loadChiefState()
2969
+ const effCfg = resolveWorkspaceConfig(st, rootId)
2970
+ const wsSnap = st.workspaces && st.workspaces[rootId] ? st.workspaces[rootId] : null
2971
+ const ledger = normalizeLlmLedger(wsSnap && wsSnap.llmLedger)
2972
+ const mr = ledger.managedRun
2973
+ if (mr.tripped && !effCfg.stopped && effCfg.runMode !== 'patrol') {
2974
+ return {
2975
+ allowed: false,
2976
+ tripped: true,
2977
+ category,
2978
+ reason: mr.trippedReason || '本轮托管硬预算已触发熔断,请重置计数后再继续',
2979
+ }
2980
+ }
2981
+ if (effCfg.stopped || effCfg.runMode !== 'managed') {
2982
+ return { allowed: true, category }
2983
+ }
2984
+ const maxCalls = normalizeManagedBudgetCalls(effCfg.managedBudgetMaxCalls)
2985
+ const maxTokens = normalizeManagedBudgetTokens(effCfg.managedBudgetMaxTokens)
2986
+ let exceedReason = ''
2987
+ if (mr.tripped) {
2988
+ exceedReason = mr.trippedReason || '本轮托管硬预算已触发熔断,请重置计数后再继续'
2989
+ } else if (maxCalls > 0 && mr.calls >= maxCalls) {
2990
+ exceedReason = `托管后台 LLM 调用已达上限 ${mr.calls}/${maxCalls} 次`
2991
+ } else if (maxTokens > 0 && mr.tokens >= maxTokens) {
2992
+ exceedReason = `托管后台 Token 消耗已达上限 ${formatCompactTokenShort(mr.tokens)}/${formatCompactTokenShort(maxTokens)}`
2993
+ }
2994
+ if (!exceedReason) {
2995
+ return { allowed: true, category }
2996
+ }
2997
+ const trippedReason = mutateChiefState((state) => {
2998
+ const ws = ensureWorkspace(state, rootId)
2999
+ return tripManagedBudgetCircuit(state, ws, rootId, exceedReason)
3000
+ })
3001
+ return { allowed: false, tripped: true, category, reason: trippedReason }
3002
+ }
3003
+
3004
+ /** Record every Chief LLM call usage and enforce Managed-mode hard budget cap immediately when reached. */
3005
+ export function recordChiefLlmUsage(rootSessionId, {
3006
+ reasonKind = '',
3007
+ modelRef = '',
3008
+ inputTokens = 0,
3009
+ outputTokens = 0,
3010
+ estimated = false,
3011
+ ok = true,
3012
+ } = {}) {
3013
+ const rootId = String(rootSessionId || 'global').trim() || 'global'
3014
+ const category = classifyChiefLlmCategory(reasonKind)
3015
+ const inTok = Math.min(LLM_LEDGER_TOKENS_MAX, Math.max(0, Math.round(Number(inputTokens) || 0)))
3016
+ const outTok = Math.min(LLM_LEDGER_TOKENS_MAX, Math.max(0, Math.round(Number(outputTokens) || 0)))
3017
+ const totTok = Math.min(LLM_LEDGER_TOKENS_MAX, inTok + outTok)
3018
+ const now = Date.now()
3019
+ return mutateChiefState((state) => {
3020
+ const ws = ensureWorkspace(state, rootId)
3021
+ const effCfg = resolveWorkspaceConfig(state, rootId)
3022
+ ws.llmLedger = normalizeLlmLedger(ws.llmLedger)
3023
+ const ledger = ws.llmLedger
3024
+ ledger.totalCalls = Math.min(LLM_LEDGER_CALLS_MAX, ledger.totalCalls + 1)
3025
+ ledger.totalInputTokens = Math.min(LLM_LEDGER_TOKENS_MAX, ledger.totalInputTokens + inTok)
3026
+ ledger.totalOutputTokens = Math.min(LLM_LEDGER_TOKENS_MAX, ledger.totalOutputTokens + outTok)
3027
+ ledger.totalTokens = Math.min(LLM_LEDGER_TOKENS_MAX, ledger.totalTokens + totTok)
3028
+ if (!ledger.byCategory[category]) ledger.byCategory[category] = { calls: 0, tokens: 0 }
3029
+ ledger.byCategory[category].calls = Math.min(LLM_LEDGER_CALLS_MAX, ledger.byCategory[category].calls + 1)
3030
+ ledger.byCategory[category].tokens = Math.min(LLM_LEDGER_TOKENS_MAX, ledger.byCategory[category].tokens + totTok)
3031
+ ledger.recent.push({
3032
+ id: nextId('llm'),
3033
+ at: now,
3034
+ category,
3035
+ reasonKind: clamp(reasonKind || '', 40),
3036
+ modelRef: clamp(modelRef || '', 80),
3037
+ inputTokens: inTok,
3038
+ outputTokens: outTok,
3039
+ totalTokens: totTok,
3040
+ estimated: Boolean(estimated),
3041
+ ok: ok !== false,
3042
+ })
3043
+ if (ledger.recent.length > LLM_LEDGER_RECENT_CAP) {
3044
+ ledger.recent = ledger.recent.slice(-LLM_LEDGER_RECENT_CAP)
3045
+ }
3046
+
3047
+ let trippedReason = ''
3048
+ if (!effCfg.stopped && effCfg.runMode === 'managed' && (category === 'review' || category === 'dream')) {
3049
+ if (!ledger.managedRun.startedAt) ledger.managedRun.startedAt = now
3050
+ ledger.managedRun.calls = Math.min(LLM_LEDGER_CALLS_MAX, ledger.managedRun.calls + 1)
3051
+ ledger.managedRun.tokens = Math.min(LLM_LEDGER_TOKENS_MAX, ledger.managedRun.tokens + totTok)
3052
+ const maxCalls = normalizeManagedBudgetCalls(effCfg.managedBudgetMaxCalls)
3053
+ const maxTokens = normalizeManagedBudgetTokens(effCfg.managedBudgetMaxTokens)
3054
+ if (maxCalls > 0 && ledger.managedRun.calls >= maxCalls) {
3055
+ trippedReason = tripManagedBudgetCircuit(
3056
+ state,
3057
+ ws,
3058
+ rootId,
3059
+ `托管后台 LLM 调用已达硬预算上限 (${ledger.managedRun.calls}/${maxCalls} 次)`,
3060
+ )
3061
+ } else if (maxTokens > 0 && ledger.managedRun.tokens >= maxTokens) {
3062
+ trippedReason = tripManagedBudgetCircuit(
3063
+ state,
3064
+ ws,
3065
+ rootId,
3066
+ `托管后台 Token 消耗已达硬预算上限 (${formatCompactTokenShort(ledger.managedRun.tokens)}/${formatCompactTokenShort(maxTokens)})`,
3067
+ )
3068
+ }
3069
+ }
3070
+ return {
3071
+ ok: true,
3072
+ category,
3073
+ tripped: Boolean(ws.llmLedger.managedRun.tripped && trippedReason),
3074
+ trippedReason,
3075
+ ledger: summarizeLlmLedger(ws.llmLedger, resolveWorkspaceConfig(state, rootId)),
3076
+ }
3077
+ })
3078
+ }
package/chief-view.js CHANGED
@@ -25,6 +25,7 @@ import {
25
25
  beginChiefActiveWork,
26
26
  endChiefActiveWork,
27
27
  getChiefActiveWork,
28
+ summarizeLlmLedger,
28
29
  } from './chief-state.js'
29
30
  import { listChiefModels, callChiefLlm } from './chief-models.js'
30
31
  import { collectClusterPeerProgress, listPeerDirectory } from './chief-network.js'
@@ -566,6 +567,8 @@ export async function getChiefView(deps, sessionId, { regenerate = false, autoSu
566
567
  inquiries: (Array.isArray(ownWs.inquiries) ? ownWs.inquiries : []).slice(-12).reverse(),
567
568
  guardWalls: listGuardWalls({ cwd: resolveSessionWorkspaceCwd(deps, rootId) }),
568
569
  activeWork: getChiefActiveWork(rootId),
570
+ llmLedger: summarizeLlmLedger(ownWs.llmLedger, effectiveConfig),
571
+ alertEvents: (Array.isArray(ownWs.alertEvents) ? ownWs.alertEvents : []).slice(-12),
569
572
  auditLog: (Array.isArray(ownWs.auditLog) ? ownWs.auditLog : []).slice(-50).reverse(),
570
573
  }
571
574
  }