dsh-chief 1.4.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
@@ -12,6 +12,7 @@ import { threadId } from 'node:worker_threads'
12
12
  import {
13
13
  resolveProjectKey,
14
14
  loadArchiveStore,
15
+ loadGlobalVaultRaw,
15
16
  getChiefMountedGlobalForSession,
16
17
  getTakenOutGlobalForSession,
17
18
  collectSealedWatchSummary,
@@ -92,6 +93,346 @@ export const CHIEF_EXEC_REQ_SOURCE = 'dsh-chief-execution-request'
92
93
 
93
94
  export const CHAT_OPPORTUNISTIC_SUMMARY_COOLDOWN_MS = 60_000
94
95
 
96
+ export const CHIEF_RUN_MODES = ['off', 'patrol', 'managed']
97
+
98
+ export const DEFAULT_MANAGED_IDLE_TIMEOUT_MS = 15 * 60 * 1000
99
+
100
+ export const CHIEF_THINKING_EFFORTS = ['auto', 'off', 'low', 'medium', 'high', 'xhigh']
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
+
360
+ export function normalizeRunMode(raw, fallbackCfg = null) {
361
+ const s = typeof raw === 'string' ? raw.trim().toLowerCase() : ''
362
+ if (s === 'off' || s === 'patrol' || s === 'managed') return s
363
+ if (s === 'stopped' || s === 'manual') return 'off'
364
+ if (s === 'smart') return 'patrol'
365
+ if (s === 'auto' || s === 'autopilot') return 'managed'
366
+ if (fallbackCfg && typeof fallbackCfg === 'object') {
367
+ if (fallbackCfg.stopped || fallbackCfg.paceMode === 'stopped') return 'off'
368
+ if (fallbackCfg.autoPilot || fallbackCfg.paceMode === 'auto') return 'managed'
369
+ if (fallbackCfg.paceMode === 'smart') return 'patrol'
370
+ }
371
+ return 'off'
372
+ }
373
+
374
+ export function normalizeThinkingEffort(raw) {
375
+ const s = typeof raw === 'string' ? raw.trim().toLowerCase() : ''
376
+ if (CHIEF_THINKING_EFFORTS.includes(s)) return s
377
+ return 'auto'
378
+ }
379
+
380
+ function normalizeTeamEffortMode(raw) {
381
+ return String(raw || '').trim().toLowerCase() === 'manual' ? 'manual' : 'auto'
382
+ }
383
+
384
+ export function normalizeLockedModelEfforts(raw) {
385
+ const out = {}
386
+ if (!raw || typeof raw !== 'object') return out
387
+ for (const [k, v] of Object.entries(raw)) {
388
+ const cleanKey = String(k || '').trim().slice(0, 64)
389
+ if (!cleanKey) continue
390
+ if (v === true) out[cleanKey] = true
391
+ }
392
+ return out
393
+ }
394
+
395
+ const EFFORT_ORDER_LADDER = ['off', 'low', 'medium', 'high', 'xhigh']
396
+
397
+ export function resolveAlignedModelEffort(desiredEffort, supportedEfforts = []) {
398
+ const list = Array.isArray(supportedEfforts)
399
+ ? supportedEfforts.map(e => (typeof e === 'string' ? e : (e && e.id ? String(e.id) : ''))).filter(Boolean)
400
+ : []
401
+ if (!list.length) return undefined
402
+ const want = String(desiredEffort || '').trim().toLowerCase()
403
+ if (!want || want === 'auto') {
404
+ if (list.includes('medium')) return 'medium'
405
+ return list[Math.floor(list.length / 2)] || list[0]
406
+ }
407
+ if (list.includes(want)) return want
408
+ const wantIdx = EFFORT_ORDER_LADDER.indexOf(want)
409
+ if (wantIdx < 0) return list[0]
410
+ for (let d = 1; d < EFFORT_ORDER_LADDER.length; d += 1) {
411
+ if (wantIdx - d >= 0 && list.includes(EFFORT_ORDER_LADDER[wantIdx - d])) {
412
+ return EFFORT_ORDER_LADDER[wantIdx - d]
413
+ }
414
+ if (wantIdx + d < EFFORT_ORDER_LADDER.length && list.includes(EFFORT_ORDER_LADDER[wantIdx + d])) {
415
+ return EFFORT_ORDER_LADDER[wantIdx + d]
416
+ }
417
+ }
418
+ return list[0]
419
+ }
420
+
421
+ export function touchWorkspaceActivity(sessionId) {
422
+ const sid = String(sessionId || '').trim()
423
+ if (!sid || sid === 'global') return false
424
+ try {
425
+ mutateChiefState((state) => {
426
+ const ws = ensureWorkspace(state, sid)
427
+ if (!ws.runtimeGuard || typeof ws.runtimeGuard !== 'object') ws.runtimeGuard = {}
428
+ ws.runtimeGuard.lastActivityAt = Date.now()
429
+ })
430
+ return true
431
+ } catch {
432
+ return false
433
+ }
434
+ }
435
+
95
436
  const SECRET_PATTERN = /(?:sk-[a-zA-Z0-9_-]{16,}|ghp_[a-zA-Z0-9]{20,}|AKIA[0-9A-Z]{16}|AIza[0-9A-Za-z_-]{30,}|Bearer\s+[A-Za-z0-9._~+/=-]{20,}|-----BEGIN [A-Z ]*PRIVATE KEY-----)/
96
437
 
97
438
  let dshAttachmentModulePromise = null
@@ -164,10 +505,12 @@ export function archiveTargetForRoot(deps, rootId, extra = '') {
164
505
  }
165
506
 
166
507
  /**
167
- * Chief-of-Staff visibility matrix (0-Token Global Cold Vault):
168
- * - Sees current session's Working Cabinet (`session`), if bound to a concrete rootSessionId
169
- * - Sees ONLY System Global Cold Vault entries explicitly mounted for Chief in THIS session (`chiefMountedSessions`) — 0 Token by default!
170
- * - Sees Precipitated Vault entries ONLY when explicitly `flippedOut` (`ws.flippedPrecipitatedIds`) for this session!
508
+ * Chief-of-Staff visibility matrix (Three-Tier Hook Architecture):
509
+ * - Session Working Cabinet: Chief can always read session items + `recentlyUnpinnedWatch`.
510
+ * - Global Vault: Unorganized global items (without hooks) are 0-token invisible to Chief!
511
+ * Organized global items expose ONLY lightweight `globalHookIndex` (`hasHook: true`),
512
+ * until Chief explicitly pulls/mounts them (`chiefMountedSessions` / `chiefPulledSessions`).
513
+ * - Precipitated Cold Vault: 100% invisible to Chief (0 disk read, 0 hook leak) unless User explicitly `flippedOut`!
171
514
  */
172
515
  export function collectChiefVisibleArchives(deps, rootId, stateSnapshot = null) {
173
516
  const sid = rootId && rootId !== 'global' ? String(rootId).trim() : ''
@@ -180,6 +523,9 @@ export function collectChiefVisibleArchives(deps, rootId, stateSnapshot = null)
180
523
  let deskGlobalItems = []
181
524
  let deskFlippedItems = []
182
525
  let mountedGlobalItems = []
526
+ let sessionItems = []
527
+ let recentlyUnpinnedWatch = []
528
+ let globalHookIndex = []
183
529
  let sealedWatch = { sessionSealed: [], globalSealed: [], precipSealed: [] }
184
530
 
185
531
  try {
@@ -187,13 +533,54 @@ export function collectChiefVisibleArchives(deps, rootId, stateSnapshot = null)
187
533
  const stSess = loadArchiveStore(sessionTarget)
188
534
  const allSess = Array.isArray(stSess.items) ? stSess.items : []
189
535
  deskSessionItems = allSess.filter(it => Array.isArray(it.takenOutSessions) && it.takenOutSessions.includes(sid)).slice(0, 6)
536
+ sessionItems = allSess.slice(0, 16).map(it => ({
537
+ id: it.id,
538
+ title: it.title,
539
+ folder: it.folder,
540
+ summary: it.summary,
541
+ paperclip: it.paperclip,
542
+ hasHook: Boolean(it.hasHook),
543
+ hookKeywords: Array.isArray(it.hookKeywords) ? it.hookKeywords : [],
544
+ hookCue: it.hookCue || '',
545
+ takenOut: Array.isArray(it.takenOutSessions) && it.takenOutSessions.includes(sid),
546
+ points: Array.isArray(it.points) ? it.points.slice(0, 3) : [],
547
+ }))
548
+ recentlyUnpinnedWatch = Array.isArray(stSess.recentlyUnpinnedWatch) ? stSess.recentlyUnpinnedWatch.slice() : []
190
549
  }
191
550
  } catch {}
192
551
  try {
552
+ const gStore = loadGlobalVaultRaw(globalTarget)
553
+ const gAll = Array.isArray(gStore && gStore.items) ? gStore.items : []
193
554
  if (sid) {
194
555
  deskGlobalItems = getTakenOutGlobalForSession(sid, globalTarget).slice(0, 6)
195
556
  mountedGlobalItems = getChiefMountedGlobalForSession(sid, globalTarget).slice(0, 6)
557
+ // Also include entries Chief pulled in this session
558
+ const pulledSet = new Set(mountedGlobalItems.map(x => x.id))
559
+ for (const g of gAll) {
560
+ if (g && Array.isArray(g.chiefPulledSessions) && g.chiefPulledSessions.includes(sid) && !pulledSet.has(g.id)) {
561
+ mountedGlobalItems.push(g)
562
+ pulledSet.add(g.id)
563
+ if (mountedGlobalItems.length >= 6) break
564
+ }
565
+ }
196
566
  }
567
+ globalHookIndex = gAll
568
+ .filter(it =>
569
+ it
570
+ && it.hasHook === true
571
+ && (!sid || (!Array.isArray(it.takenOutSessions) || !it.takenOutSessions.includes(sid)))
572
+ && (!sid || (!Array.isArray(it.chiefMountedSessions) || !it.chiefMountedSessions.includes(sid)))
573
+ && (!sid || (!Array.isArray(it.chiefPulledSessions) || !it.chiefPulledSessions.includes(sid)))
574
+ )
575
+ .slice(0, 12)
576
+ .map(it => ({
577
+ id: it.id,
578
+ title: it.title,
579
+ folder: it.folder,
580
+ paperclip: it.paperclip,
581
+ hookKeywords: Array.isArray(it.hookKeywords) ? it.hookKeywords : [],
582
+ hookCue: it.hookCue || '',
583
+ }))
197
584
  } catch {}
198
585
  try {
199
586
  if (sid) {
@@ -214,6 +601,9 @@ export function collectChiefVisibleArchives(deps, rootId, stateSnapshot = null)
214
601
  deskGlobalItems,
215
602
  deskFlippedItems,
216
603
  mountedGlobalItems,
604
+ sessionItems,
605
+ recentlyUnpinnedWatch,
606
+ globalHookIndex,
217
607
  sealedWatch,
218
608
  sessionTarget,
219
609
  globalTarget,
@@ -382,7 +772,7 @@ function normalizePendingApproval(raw) {
382
772
  if (!opLabel) return null
383
773
  const validStatuses = ['pending', 'approved', 'rejected', 'executed', 'failed', 'expired']
384
774
  const status = validStatuses.includes(raw.status) ? raw.status : 'pending'
385
- const validKinds = ['tool', 'relay', 'compact', 'auto_continue']
775
+ const validKinds = ['tool', 'relay', 'compact', 'auto_continue', 'archive_op', 'model_effort']
386
776
  const kind = validKinds.includes(raw.kind) ? raw.kind : 'tool'
387
777
  const validCategories = ['workspace_file', 'system_command', 'main_workflow', 'subagent_workflow']
388
778
  const category = validCategories.includes(raw.category) ? raw.category : 'workspace_file'
@@ -615,9 +1005,14 @@ function emptyWorkspace() {
615
1005
  lastGoalAchievedSig: '',
616
1006
  autoPilotStartedAt: 0,
617
1007
  autoPilotHadTurn: false,
1008
+ managedStartedAt: 0,
1009
+ lastActivityAt: 0,
1010
+ lastDreamRoamAt: 0,
618
1011
  lastAutoArchiveOrgAt: 0,
619
1012
  },
620
1013
  flippedPrecipitatedIds: [],
1014
+ llmLedger: emptyLlmLedger(),
1015
+ alertEvents: [],
621
1016
  }
622
1017
  }
623
1018
 
@@ -648,12 +1043,19 @@ export function normalizeSuggestion(raw) {
648
1043
  if (!raw || typeof raw !== 'object') return null
649
1044
  const title = clamp(raw.title, 90)
650
1045
  if (!title) return null
651
- const kind = ['bound', 'board', 'goal_approval', 'relay', 'advice', 'guard_wall'].includes(raw.kind) ? raw.kind : 'relay'
1046
+ const kind = ['bound', 'board', 'goal_approval', 'relay', 'advice', 'guard_wall', 'wall_removal', 'archive_op', 'model_effort'].includes(raw.kind) ? raw.kind : 'relay'
652
1047
  const boundField = ['forbidden', 'allowed', 'notes'].includes(raw.boundField) ? raw.boundField : 'forbidden'
653
1048
  const replaces = Array.isArray(raw.replaces)
654
1049
  ? raw.replaces.map(x => String(x || '').trim()).filter(Boolean).slice(0, 20)
655
1050
  : []
656
1051
  const wallSpec = raw.wallSpec && typeof raw.wallSpec === 'object' ? { ...raw.wallSpec } : null
1052
+ const wallRemovalSpec = raw.wallRemovalSpec && typeof raw.wallRemovalSpec === 'object' ? { ...raw.wallRemovalSpec } : null
1053
+ const archiveSpec = (raw.archiveSpec && typeof raw.archiveSpec === 'object')
1054
+ ? { ...raw.archiveSpec }
1055
+ : ((raw.archiveOp && typeof raw.archiveOp === 'object') ? { ...raw.archiveOp } : null)
1056
+ const effortSpec = (raw.effortSpec && typeof raw.effortSpec === 'object')
1057
+ ? { ...raw.effortSpec }
1058
+ : ((raw.effortOp && typeof raw.effortOp === 'object') ? { ...raw.effortOp } : null)
657
1059
  return {
658
1060
  id: typeof raw.id === 'string' && raw.id ? raw.id : nextId('sug'),
659
1061
  kind,
@@ -661,18 +1063,21 @@ export function normalizeSuggestion(raw) {
661
1063
  replaces,
662
1064
  pinGlobal: Boolean(raw.pinGlobal),
663
1065
  ...(wallSpec ? { wallSpec } : {}),
1066
+ ...(wallRemovalSpec ? { wallRemovalSpec } : {}),
1067
+ ...(archiveSpec ? { archiveSpec } : {}),
1068
+ ...(effortSpec ? { effortSpec } : {}),
664
1069
  fromAgent: clamp(raw.fromAgent || '', 48),
665
1070
  title,
666
1071
  reason: clamp(raw.reason || '', 220),
667
- target: clamp(raw.target || (kind === 'bound' ? 'bounds' : kind === 'guard_wall' ? 'guard_walls' : kind === 'goal_approval' ? 'board' : 'lead'), 64),
668
- targetLabel: clamp(raw.targetLabel || raw.target || (kind === 'bound' ? '工作边界' : kind === 'guard_wall' ? '物理驻墙' : kind === 'goal_approval' ? '目标结项批示' : kind === 'advice' ? '参谋进言' : '主对话'), 40),
1072
+ target: clamp(raw.target || (kind === 'bound' ? 'bounds' : (kind === 'guard_wall' || kind === 'wall_removal') ? 'guard_walls' : kind === 'goal_approval' ? 'board' : kind === 'archive_op' ? 'archive' : kind === 'model_effort' ? 'lead' : 'lead'), 64),
1073
+ targetLabel: clamp(raw.targetLabel || raw.target || (kind === 'bound' ? '工作边界' : kind === 'guard_wall' ? '物理驻墙' : kind === 'wall_removal' ? '物理驻墙拆墙申请' : kind === 'goal_approval' ? '目标结项批示' : kind === 'advice' ? '参谋进言' : kind === 'archive_op' ? '档案与桌面调配' : kind === 'model_effort' ? '模型思考强度调节' : '主对话'), 40),
669
1074
  mode: ['steer', 'followup', 'silent'].includes(raw.mode) ? raw.mode : (kind === 'advice' ? 'followup' : 'steer'),
670
1075
  draftText: cleanMultiline(raw.draftText || '', 600),
671
1076
  evidence: cleanMultiline(raw.evidence || '', 600),
672
1077
  missing: clamp(raw.missing || '', 300),
673
1078
  boardOp: raw.boardOp && typeof raw.boardOp === 'object' ? raw.boardOp : null,
674
- popup: Boolean(raw.popup || kind === 'advice'),
675
- urgency: ['normal', 'high'].includes(raw.urgency) ? raw.urgency : 'normal',
1079
+ popup: Boolean(raw.popup || kind === 'advice' || kind === 'wall_removal'),
1080
+ urgency: ['normal', 'high'].includes(raw.urgency) ? raw.urgency : (kind === 'wall_removal' ? 'high' : 'normal'),
676
1081
  status: ['pending', 'applied', 'dismissed'].includes(raw.status) ? raw.status : 'pending',
677
1082
  createdAt: Number(raw.createdAt) || Date.now(),
678
1083
  }
@@ -763,6 +1168,8 @@ function normalizeWorkspace(raw) {
763
1168
  const imageCount = Math.max(0, Math.round(Number(item.imageCount) || 0))
764
1169
  const kind = item.kind === 'receipt' ? 'receipt' : (item.kind === 'qa' ? 'qa' : '')
765
1170
  const resumeTaskId = item.resumeTaskId ? String(item.resumeTaskId) : ''
1171
+ const thinkingEffort = typeof item.thinkingEffort === 'string' && item.thinkingEffort ? item.thinkingEffort : ''
1172
+ const thinkingEffortMode = item.thinkingEffortMode === 'auto' || item.thinkingEffortMode === 'manual' ? item.thinkingEffortMode : ''
766
1173
  return {
767
1174
  id: String(item.id || nextId('chat')),
768
1175
  role: item.role === 'user' ? 'user' : 'chief',
@@ -770,6 +1177,9 @@ function normalizeWorkspace(raw) {
770
1177
  target: item.target ? String(item.target) : '',
771
1178
  ...(kind ? { kind } : {}),
772
1179
  ...(resumeTaskId ? { resumeTaskId } : {}),
1180
+ ...(thinkingEffort ? { thinkingEffort } : {}),
1181
+ ...(thinkingEffortMode ? { thinkingEffortMode } : {}),
1182
+ ...(item.isOneStopReport ? { isOneStopReport: true } : {}),
773
1183
  ...(imageCount > 0 ? { imageCount } : {}),
774
1184
  actions: Array.isArray(item.actions) ? item.actions.slice(0, 8) : [],
775
1185
  at: Number(item.at) || Date.now(),
@@ -810,6 +1220,9 @@ function normalizeWorkspace(raw) {
810
1220
  lastGoalAchievedSig: String(rg.lastGoalAchievedSig || ''),
811
1221
  autoPilotStartedAt: Math.max(0, Number(rg.autoPilotStartedAt) || 0),
812
1222
  autoPilotHadTurn: Boolean(rg.autoPilotHadTurn),
1223
+ managedStartedAt: Math.max(0, Number(rg.managedStartedAt) || Number(rg.autoPilotStartedAt) || 0),
1224
+ lastActivityAt: Math.max(0, Number(rg.lastActivityAt) || 0),
1225
+ lastDreamRoamAt: Math.max(0, Number(rg.lastDreamRoamAt) || 0),
813
1226
  lastAutoArchiveOrgAt: Math.max(0, Number(rg.lastAutoArchiveOrgAt) || 0),
814
1227
  }
815
1228
  base.chiefRiskAck = normalizeChiefRiskAck(src.chiefRiskAck)
@@ -836,14 +1249,29 @@ function normalizeWorkspace(raw) {
836
1249
  const validPaces = ['manual', 'smart', 'auto', 'stopped']
837
1250
  const pm = validPaces.includes(src.config.paceMode) ? src.config.paceMode : undefined
838
1251
  const rawStopped = typeof src.config.stopped === 'boolean' ? src.config.stopped : (pm === 'stopped')
1252
+ const rm = normalizeRunMode(src.config.runMode, { ...src.config, stopped: rawStopped, paceMode: pm })
839
1253
  const rawPerm = typeof src.config.permissionMode === 'string'
840
1254
  ? normalizePermissionMode(src.config.permissionMode, { requireAck: true, hasChiefRiskAck: ackOk })
841
1255
  : DEFAULT_CHIEF_PERMISSION_MODE
842
1256
  const plugCheck = validatePolicyPluginList(src.config.policyPlugins)
843
1257
  const policyPlugins = plugCheck.ok ? plugCheck.plugins : []
1258
+ const lockedModelEfforts = normalizeLockedModelEfforts(src.config.lockedModelEfforts)
1259
+ const managedIdleTimeoutMs = Number.isFinite(Number(src.config.managedIdleTimeoutMs)) && Number(src.config.managedIdleTimeoutMs) >= 50
1260
+ ? Math.min(2 * 60 * 60 * 1000, Math.round(Number(src.config.managedIdleTimeoutMs)))
1261
+ : DEFAULT_MANAGED_IDLE_TIMEOUT_MS
844
1262
  base.config = {
845
1263
  ...(typeof src.config.modelRef === 'string' ? { modelRef: src.config.modelRef.trim() } : {}),
846
1264
  permissionMode: rawPerm,
1265
+ runMode: rm,
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) } : {}),
1272
+ ...(typeof src.config.thinkingEffort === 'string' ? { thinkingEffort: normalizeThinkingEffort(src.config.thinkingEffort) } : {}),
1273
+ ...(typeof src.config.teamEffortMode === 'string' ? { teamEffortMode: normalizeTeamEffortMode(src.config.teamEffortMode) } : {}),
1274
+ ...(Object.keys(lockedModelEfforts).length ? { lockedModelEfforts } : {}),
847
1275
  ...(typeof src.config.stopped === 'boolean' || pm === 'stopped' ? { stopped: rawStopped } : {}),
848
1276
  ...(pm ? { paceMode: pm, autoPilot: !rawStopped && pm === 'auto', autoReview: !rawStopped && pm !== 'manual' } : {}),
849
1277
  ...(policyPlugins.length > 0 ? { policyPlugins } : {}),
@@ -855,6 +1283,11 @@ function normalizeWorkspace(raw) {
855
1283
  base.flippedPrecipitatedIds = Array.isArray(src.flippedPrecipitatedIds)
856
1284
  ? [...new Set(src.flippedPrecipitatedIds.map(x => String(x || '').trim()).filter(Boolean))].slice(0, 20)
857
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)
858
1291
  return base
859
1292
  }
860
1293
 
@@ -955,16 +1388,68 @@ export function resolveWorkspaceConfig(state, sessionId = '') {
955
1388
  })
956
1389
  const permissionMode = resolvedRoleCaps.role
957
1390
  const chiefRiskVerified = permissionMode === 'chief' ? ackOk : false
1391
+ const runMode = stopped
1392
+ ? 'off'
1393
+ : (wsCfg && typeof wsCfg.runMode === 'string' && CHIEF_RUN_MODES.includes(wsCfg.runMode)
1394
+ ? wsCfg.runMode
1395
+ : normalizeRunMode(undefined, { stopped, paceMode, autoPilot: paceMode === 'auto' }))
1396
+ const thinkingEffort = normalizeThinkingEffort(
1397
+ (wsCfg && typeof wsCfg.thinkingEffort === 'string' && wsCfg.thinkingEffort)
1398
+ || (typeof base.thinkingEffort === 'string' && base.thinkingEffort)
1399
+ || 'auto',
1400
+ )
1401
+ const teamEffortMode = normalizeTeamEffortMode(
1402
+ (wsCfg && typeof wsCfg.teamEffortMode === 'string' && wsCfg.teamEffortMode)
1403
+ || (typeof base.teamEffortMode === 'string' && base.teamEffortMode)
1404
+ || 'auto',
1405
+ )
1406
+ const lockedModelEfforts = normalizeLockedModelEfforts(wsCfg && wsCfg.lockedModelEfforts)
1407
+ const managedIdleTimeoutMs = wsCfg && Number.isFinite(Number(wsCfg.managedIdleTimeoutMs)) && Number(wsCfg.managedIdleTimeoutMs) >= 50
1408
+ ? Math.min(2 * 60 * 60 * 1000, Math.round(Number(wsCfg.managedIdleTimeoutMs)))
1409
+ : (Number.isFinite(Number(base.managedIdleTimeoutMs)) && Number(base.managedIdleTimeoutMs) >= 50
1410
+ ? Math.min(2 * 60 * 60 * 1000, Math.round(Number(base.managedIdleTimeoutMs)))
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)
958
1433
  return {
959
1434
  modelRef,
960
1435
  paceMode,
1436
+ runMode,
1437
+ managedIdleTimeoutMs,
1438
+ notifyEnabled,
1439
+ notifySound,
1440
+ uiLang,
1441
+ managedBudgetMaxCalls,
1442
+ managedBudgetMaxTokens,
1443
+ thinkingEffort,
1444
+ teamEffortMode,
1445
+ lockedModelEfforts,
961
1446
  stopped,
962
1447
  permissionMode,
963
1448
  capabilities: resolvedRoleCaps.capabilities,
964
1449
  policyPlugins,
965
1450
  chiefRiskVerified,
966
- autoPilot: !stopped && paceMode === 'auto',
967
- autoReview: !stopped && paceMode !== 'manual',
1451
+ autoPilot: !stopped && runMode === 'managed',
1452
+ autoReview: !stopped && runMode === 'managed',
968
1453
  tacticalModes: mergedTactical,
969
1454
  }
970
1455
  }
@@ -1041,6 +1526,17 @@ function normalizeState(raw) {
1041
1526
  config: {
1042
1527
  modelRef: typeof cfg.modelRef === 'string' ? cfg.modelRef.trim() : '',
1043
1528
  paceMode,
1529
+ runMode: stopped ? 'off' : normalizeRunMode(cfg.runMode, { stopped, paceMode }),
1530
+ managedIdleTimeoutMs: Number.isFinite(Number(cfg.managedIdleTimeoutMs)) && Number(cfg.managedIdleTimeoutMs) >= 50
1531
+ ? Math.min(2 * 60 * 60 * 1000, Math.round(Number(cfg.managedIdleTimeoutMs)))
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),
1538
+ thinkingEffort: normalizeThinkingEffort(cfg.thinkingEffort),
1539
+ teamEffortMode: normalizeTeamEffortMode(cfg.teamEffortMode),
1044
1540
  stopped,
1045
1541
  permissionMode: DEFAULT_CHIEF_PERMISSION_MODE,
1046
1542
  autoPilot: !stopped && paceMode === 'auto',
@@ -1084,6 +1580,14 @@ export function enqueueApprovalToWs(ws, item = {}) {
1084
1580
  if (ws.pendingApprovals.length > APPROVALS_CAP) {
1085
1581
  ws.pendingApprovals = ws.pendingApprovals.slice(-APPROVALS_CAP)
1086
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
+ })
1087
1591
  return norm
1088
1592
  }
1089
1593
 
@@ -1125,6 +1629,14 @@ export function enqueueElevationToWs(ws, req = {}) {
1125
1629
  outcome: 'pending',
1126
1630
  by: norm.by,
1127
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
+ })
1128
1640
  return norm
1129
1641
  }
1130
1642
 
@@ -1205,9 +1717,32 @@ export function answerChiefInquiry(sessionId = 'global', { inquiryId = '', answe
1205
1717
  }
1206
1718
  }
1207
1719
  if (idx < 0) return { ok: false, error: `未找到待回复问询:${inquiryId || '最近未答问询'}` }
1720
+ const existing = ws.inquiries[idx]
1721
+ if (!existing || existing.status === 'answered' || (existing.status !== 'pending' && existing.status !== 'delivered')) {
1722
+ const prevId = (existing && existing.inquiryId) || inquiryId
1723
+ const prevStatus = (existing && existing.status) || 'unknown'
1724
+ pushAuditToWs(ws, {
1725
+ mode: resolveWorkspaceConfig(state, rootId).permissionMode,
1726
+ stage: 'inquiry_channel',
1727
+ rule: 'inquiry_reply_replay_rejected',
1728
+ decision: 'rejected',
1729
+ operation: '拦截重复问询答复',
1730
+ target: prevId,
1731
+ reason: `问询 #${prevId} 已结案 (status=${prevStatus}),拒绝重放覆写`,
1732
+ outcome: 'rejected',
1733
+ by: clamp(by || 'lead', 40),
1734
+ }, rootId)
1735
+ return {
1736
+ ok: false,
1737
+ alreadyAnswered: true,
1738
+ code: 'inquiry_already_answered',
1739
+ error: `问询 #${prevId} 已回复结案,拒绝重复应答`,
1740
+ inquiry: existing,
1741
+ }
1742
+ }
1208
1743
  const now = Date.now()
1209
1744
  const item = {
1210
- ...ws.inquiries[idx],
1745
+ ...existing,
1211
1746
  status: 'answered',
1212
1747
  answer: cleanAns,
1213
1748
  answeredBy: clamp(by || 'lead', 40),
@@ -1670,14 +2205,18 @@ export function deployChiefWorkspaceState(deps, {
1670
2205
  })
1671
2206
  if (toWs.chat.length > CHAT_CAP) toWs.chat = toWs.chat.slice(-CHAT_CAP)
1672
2207
 
1673
- // Clone safe workspace chief config (model, pace, tactical preferences), ALWAYS forcing intervention=false & L0 advisor!
2208
+ // Clone safe workspace chief config (model, effort, tactical preferences), ALWAYS forcing intervention=false, runMode='off' & L0 advisor!
1674
2209
  const fromCfg = resolveWorkspaceConfig(state, fromKey)
1675
2210
  toWs.config = {
1676
2211
  modelRef: fromCfg.modelRef || '',
1677
- paceMode: fromCfg.paceMode || 'manual',
2212
+ paceMode: 'manual',
2213
+ runMode: 'off',
2214
+ thinkingEffort: fromCfg.thinkingEffort || 'auto',
2215
+ teamEffortMode: fromCfg.teamEffortMode || 'auto',
2216
+ managedIdleTimeoutMs: fromCfg.managedIdleTimeoutMs || DEFAULT_MANAGED_IDLE_TIMEOUT_MS,
1678
2217
  permissionMode: DEFAULT_CHIEF_PERMISSION_MODE,
1679
- autoPilot: Boolean(fromCfg.autoPilot),
1680
- autoReview: Boolean(fromCfg.autoReview),
2218
+ autoPilot: false,
2219
+ autoReview: false,
1681
2220
  tacticalModes: {
1682
2221
  ...normalizeTacticalModes(fromCfg.tacticalModes),
1683
2222
  intervention: false,
@@ -1719,7 +2258,19 @@ export function deployChiefWorkspaceState(deps, {
1719
2258
  /* -------------------------------------------------------------------------- */
1720
2259
 
1721
2260
  export function updateChiefConfig(patch) {
1722
- 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
1723
2274
  const sid = String(safePatch.sessionId || safePatch.session || '').trim() || 'global'
1724
2275
  return mutateChiefState((state) => {
1725
2276
  const ws = ensureWorkspace(state, sid)
@@ -1764,6 +2315,60 @@ export function updateChiefConfig(patch) {
1764
2315
  }
1765
2316
  }
1766
2317
 
2318
+ // Hard gate on model thinking effort lock mutations (human UI / explicit byUser only)
2319
+ const callerBy = typeof safePatch.by === 'string' ? safePatch.by.trim() : ''
2320
+ const isHumanBy = !callerBy || /^(?:user|human|operator|ui_panel)$/i.test(callerBy)
2321
+ const isHumanLockCaller = safePatch._fromUiPanel === true
2322
+ || (safePatch.byUser === true && isHumanBy)
2323
+ const wantsLockMutation = safePatch.lockedModelEfforts !== undefined
2324
+ || safePatch.toggleLockAgentEffort !== undefined
2325
+ || safePatch.teamEffortMode !== undefined
2326
+ if (wantsLockMutation && !isHumanLockCaller) {
2327
+ pushAuditToWs(ws, {
2328
+ mode: effBefore.permissionMode,
2329
+ stage: 'model_effort_lock',
2330
+ rule: 'effort_lock_human_only',
2331
+ decision: 'blocked',
2332
+ operation: '修改模型思考强度锁挡',
2333
+ target: sid,
2334
+ reason: `未授权来源 (${callerBy || 'unknown'}) 试图修改 lockedModelEfforts,仅允许人类面板显式操作`,
2335
+ outcome: 'rejected',
2336
+ by: clamp(callerBy || 'unknown', 40),
2337
+ }, sid)
2338
+ return {
2339
+ ok: false,
2340
+ blocked: true,
2341
+ lockedByUser: true,
2342
+ code: 'effort_lock_human_only',
2343
+ error: '思考强度锁挡 (lockedModelEfforts) 仅允许人类通过面板或显式 byUser 授权修改,已拦截越权变更',
2344
+ }
2345
+ }
2346
+ if (
2347
+ typeof safePatch.thinkingEffort === 'string'
2348
+ && effBefore.lockedModelEfforts
2349
+ && effBefore.lockedModelEfforts.chief === true
2350
+ && !isHumanLockCaller
2351
+ ) {
2352
+ pushAuditToWs(ws, {
2353
+ mode: effBefore.permissionMode,
2354
+ stage: 'model_effort_lock',
2355
+ rule: 'effort_lock_human_only',
2356
+ decision: 'blocked',
2357
+ operation: '修改参谋长思考强度',
2358
+ target: sid,
2359
+ reason: `参谋长思考强度已被用户锁定 (lockedModelEfforts.chief),拒绝非人类来源 (${callerBy || 'unknown'}) 修改`,
2360
+ outcome: 'rejected',
2361
+ by: clamp(callerBy || 'unknown', 40),
2362
+ }, sid)
2363
+ return {
2364
+ ok: false,
2365
+ blocked: true,
2366
+ lockedByUser: true,
2367
+ code: 'effort_lock_human_only',
2368
+ error: '参谋长思考强度已被用户锁定 (lockedModelEfforts.chief),仅允许人类显式修改',
2369
+ }
2370
+ }
2371
+
1767
2372
  // Check explicit Policy Plugin list (restrict-only) BEFORE applying any changes
1768
2373
  let validatedPlugins = null
1769
2374
  if (safePatch.policyPlugins !== undefined) {
@@ -1845,19 +2450,51 @@ export function updateChiefConfig(patch) {
1845
2450
  }
1846
2451
 
1847
2452
  const wantsAutoPilot = Boolean(
1848
- safePatch.paceMode === 'auto'
1849
- || (typeof safePatch.paceMode !== 'string' && safePatch.stopped !== true && safePatch.autoPilot === true)
2453
+ safePatch.runMode === 'managed'
2454
+ || safePatch.paceMode === 'auto'
2455
+ || (typeof safePatch.paceMode !== 'string' && typeof safePatch.runMode !== 'string' && safePatch.stopped !== true && safePatch.autoPilot === true)
1850
2456
  )
1851
- if (wantsAutoPilot && effBefore.paceMode !== 'auto' && safePatch.confirmedAutoPilot !== true) {
2457
+ if (wantsAutoPilot && effBefore.runMode !== 'managed' && effBefore.paceMode !== 'auto' && safePatch.confirmedAutoPilot !== true) {
1852
2458
  return {
1853
2459
  ok: false,
1854
2460
  requireAutoPilotConfirm: true,
1855
- error: '开启「⚡ 全自动托管」需先确认本会话自治范围与防空转退出弹窗(confirmedAutoPilot: true)',
2461
+ error: '开启「🤖 托管模式」需先确认本会话自治范围与 5 条件自动休眠保护(confirmedAutoPilot: true)',
1856
2462
  }
1857
2463
  }
1858
- if (ws && wantsAutoPilot && effBefore.paceMode !== 'auto') {
1859
- ws.runtimeGuard.autoPilotStartedAt = Date.now()
2464
+ if (ws && wantsAutoPilot && (effBefore.runMode !== 'managed' || effBefore.paceMode !== 'auto')) {
2465
+ const now = Date.now()
2466
+ ws.runtimeGuard.autoPilotStartedAt = now
2467
+ ws.runtimeGuard.managedStartedAt = now
2468
+ ws.runtimeGuard.lastActivityAt = now
1860
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()
1861
2498
  }
1862
2499
 
1863
2500
  let compactLowWarning = ''
@@ -1878,46 +2515,100 @@ export function updateChiefConfig(patch) {
1878
2515
  }
1879
2516
  }
1880
2517
 
1881
- const applyPatchTo = (targetCfg, allowIntervention, allowAutoPilot = allowIntervention, allowPermSync = false) => {
2518
+ const applyPatchTo = (targetCfg, allowIntervention, allowAutoPilot = allowIntervention, allowPermSync = false, allowLocks = false) => {
1882
2519
  if (typeof safePatch.modelRef === 'string') targetCfg.modelRef = safePatch.modelRef.trim()
2520
+ if (typeof safePatch.thinkingEffort === 'string') {
2521
+ targetCfg.thinkingEffort = normalizeThinkingEffort(safePatch.thinkingEffort)
2522
+ }
2523
+ if (allowLocks && typeof safePatch.teamEffortMode === 'string') {
2524
+ targetCfg.teamEffortMode = normalizeTeamEffortMode(safePatch.teamEffortMode)
2525
+ }
2526
+ if (Number.isFinite(Number(safePatch.managedIdleTimeoutMs)) && Number(safePatch.managedIdleTimeoutMs) >= 50) {
2527
+ targetCfg.managedIdleTimeoutMs = Math.min(2 * 60 * 60 * 1000, Math.round(Number(safePatch.managedIdleTimeoutMs)))
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
+ }
2538
+ if (allowLocks && (
2539
+ (safePatch.lockedModelEfforts && typeof safePatch.lockedModelEfforts === 'object')
2540
+ || (safePatch.toggleLockAgentEffort && typeof safePatch.toggleLockAgentEffort === 'object')
2541
+ )) {
2542
+ const curLocks = { ...(targetCfg.lockedModelEfforts || {}) }
2543
+ if (safePatch.lockedModelEfforts && typeof safePatch.lockedModelEfforts === 'object') {
2544
+ for (const [lk, lv] of Object.entries(safePatch.lockedModelEfforts)) {
2545
+ const ck = String(lk || '').trim().slice(0, 64)
2546
+ if (!ck) continue
2547
+ if (lv === true) curLocks[ck] = true
2548
+ else delete curLocks[ck]
2549
+ }
2550
+ }
2551
+ if (safePatch.toggleLockAgentEffort && typeof safePatch.toggleLockAgentEffort === 'object') {
2552
+ const lk = String(safePatch.toggleLockAgentEffort.target || 'lead').trim().slice(0, 64)
2553
+ if (lk) {
2554
+ if (safePatch.toggleLockAgentEffort.locked === true) curLocks[lk] = true
2555
+ else delete curLocks[lk]
2556
+ }
2557
+ }
2558
+ targetCfg.lockedModelEfforts = curLocks
2559
+ }
1883
2560
  if (allowPermSync && normalizedReqPerm) {
1884
2561
  targetCfg.permissionMode = normalizedReqPerm
1885
2562
  }
1886
- if (typeof safePatch.paceMode === 'string' && ['manual', 'smart', 'auto', 'stopped'].includes(safePatch.paceMode)) {
2563
+ if (typeof safePatch.runMode === 'string' && CHIEF_RUN_MODES.includes(safePatch.runMode)) {
2564
+ const nextRun = (!allowAutoPilot && safePatch.runMode === 'managed') ? 'off' : safePatch.runMode
2565
+ targetCfg.runMode = nextRun
2566
+ targetCfg.stopped = false
2567
+ targetCfg.paceMode = nextRun === 'managed' ? 'auto' : (nextRun === 'patrol' ? 'smart' : 'manual')
2568
+ targetCfg.autoPilot = nextRun === 'managed' && allowAutoPilot
2569
+ targetCfg.autoReview = nextRun === 'managed' && allowAutoPilot
2570
+ } else if (typeof safePatch.paceMode === 'string' && ['manual', 'smart', 'auto', 'stopped'].includes(safePatch.paceMode)) {
1887
2571
  const nextPace = (!allowAutoPilot && safePatch.paceMode === 'auto') ? 'manual' : safePatch.paceMode
1888
2572
  targetCfg.paceMode = nextPace
1889
2573
  const isStopped = nextPace === 'stopped'
1890
2574
  targetCfg.stopped = isStopped
2575
+ targetCfg.runMode = isStopped ? 'off' : (nextPace === 'auto' ? 'managed' : (nextPace === 'smart' ? 'patrol' : 'off'))
1891
2576
  targetCfg.autoPilot = !isStopped && nextPace === 'auto' && allowAutoPilot
1892
- targetCfg.autoReview = !isStopped && nextPace !== 'manual'
2577
+ targetCfg.autoReview = !isStopped && nextPace === 'auto' && allowAutoPilot
1893
2578
  } else if (typeof safePatch.stopped === 'boolean') {
1894
2579
  targetCfg.stopped = safePatch.stopped
1895
2580
  if (safePatch.stopped) {
1896
2581
  targetCfg.paceMode = 'stopped'
2582
+ targetCfg.runMode = 'off'
1897
2583
  targetCfg.autoPilot = false
1898
2584
  targetCfg.autoReview = false
1899
2585
  } else {
1900
2586
  if (targetCfg.paceMode === 'stopped') targetCfg.paceMode = 'manual'
1901
2587
  if (!allowAutoPilot && targetCfg.paceMode === 'auto') targetCfg.paceMode = 'manual'
2588
+ targetCfg.runMode = normalizeRunMode(targetCfg.runMode, targetCfg)
1902
2589
  targetCfg.autoPilot = targetCfg.paceMode === 'auto' && allowAutoPilot
1903
- targetCfg.autoReview = targetCfg.paceMode !== 'manual'
2590
+ targetCfg.autoReview = targetCfg.paceMode === 'auto' && allowAutoPilot
1904
2591
  }
1905
2592
  } else if (typeof safePatch.autoPilot === 'boolean') {
1906
2593
  const nextAuto = Boolean(safePatch.autoPilot && allowAutoPilot)
1907
2594
  targetCfg.stopped = false
1908
2595
  targetCfg.paceMode = nextAuto ? 'auto' : 'manual'
2596
+ targetCfg.runMode = nextAuto ? 'managed' : 'off'
1909
2597
  targetCfg.autoPilot = nextAuto
1910
2598
  targetCfg.autoReview = nextAuto
1911
2599
  }
1912
- if (!allowAutoPilot && targetCfg.paceMode === 'auto') {
2600
+ if (!allowAutoPilot && (targetCfg.paceMode === 'auto' || targetCfg.runMode === 'managed')) {
1913
2601
  targetCfg.paceMode = 'manual'
2602
+ targetCfg.runMode = 'off'
1914
2603
  targetCfg.autoPilot = false
2604
+ targetCfg.autoReview = false
1915
2605
  }
1916
- if (typeof safePatch.autoReview === 'boolean' && typeof safePatch.paceMode !== 'string' && typeof safePatch.stopped !== 'boolean') {
2606
+ if (typeof safePatch.autoReview === 'boolean' && typeof safePatch.paceMode !== 'string' && typeof safePatch.runMode !== 'string' && typeof safePatch.stopped !== 'boolean') {
1917
2607
  targetCfg.autoReview = safePatch.autoReview
1918
2608
  if (!safePatch.autoReview) {
1919
2609
  targetCfg.stopped = false
1920
2610
  targetCfg.paceMode = 'manual'
2611
+ targetCfg.runMode = 'off'
1921
2612
  }
1922
2613
  }
1923
2614
  if (incomingTactical) {
@@ -1936,11 +2627,21 @@ export function updateChiefConfig(patch) {
1936
2627
  ws.config = {
1937
2628
  modelRef: effBefore.modelRef || '',
1938
2629
  paceMode: effBefore.paceMode || 'manual',
2630
+ runMode: effBefore.runMode || 'off',
2631
+ thinkingEffort: effBefore.thinkingEffort || 'auto',
2632
+ teamEffortMode: effBefore.teamEffortMode || 'auto',
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,
2639
+ lockedModelEfforts: { ...(effBefore.lockedModelEfforts || {}) },
1939
2640
  permissionMode: effBefore.permissionMode || DEFAULT_CHIEF_PERMISSION_MODE,
1940
2641
  tacticalModes: { ...effBefore.tacticalModes },
1941
2642
  }
1942
2643
  }
1943
- applyPatchTo(ws.config, true, true, true)
2644
+ applyPatchTo(ws.config, true, true, true, isHumanLockCaller)
1944
2645
  if (validatedPlugins !== null) {
1945
2646
  if (safePatch.policyPluginsScope === 'global') {
1946
2647
  state.config.policyPlugins = validatedPlugins
@@ -1959,9 +2660,9 @@ export function updateChiefConfig(patch) {
1959
2660
  by: clamp(safePatch.by || 'operator', 40),
1960
2661
  }, sid)
1961
2662
  }
1962
- // Session permissionMode, intervention, and autoPilot NEVER leak globally across new sessions!
2663
+ // Session permissionMode, intervention, lockedModelEfforts, and autoPilot NEVER leak globally across new sessions!
1963
2664
  state.config.permissionMode = DEFAULT_CHIEF_PERMISSION_MODE
1964
- applyPatchTo(state.config, false, false, false)
2665
+ applyPatchTo(state.config, false, false, false, false)
1965
2666
 
1966
2667
  if (normalizedReqPerm) {
1967
2668
  if (normalizedReqPerm === 'chief' && safePatch.confirmedChiefRisk === true) {
@@ -1999,8 +2700,10 @@ export function updateChiefConfig(patch) {
1999
2700
  }
2000
2701
  return {
2001
2702
  ok: true,
2703
+ ...(presetSpec ? { appliedPreset: presetSpec.id } : {}),
2002
2704
  ...(compactLowWarning ? { compactLowWarning } : {}),
2003
2705
  config: { ...finalCfg, tacticalModes: { ...finalCfg.tacticalModes } },
2706
+ llmLedger: summarizeLlmLedger(ws.llmLedger, finalCfg),
2004
2707
  }
2005
2708
  })
2006
2709
  }
@@ -2191,3 +2894,185 @@ export function getChiefActiveWork(rootSessionId) {
2191
2894
  }
2192
2895
  return { ...cur }
2193
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
+ }