dsh-chief 1.3.0 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +84 -12
- package/README.en.md +156 -113
- package/README.md +149 -140
- package/api-routes.js +183 -4
- package/archive-core.js +136 -8
- package/archive-dossiers.js +450 -20
- package/archive-precipitated.js +115 -36
- package/auto-continue.js +13 -5
- package/board-actions.js +131 -5
- package/board-schema.js +1 -1
- package/chief-approvals.js +415 -90
- package/chief-archives.js +191 -29
- package/chief-commands.js +1178 -207
- package/chief-executor.js +279 -555
- package/chief-models.js +158 -28
- package/chief-network.js +157 -8
- package/chief-review.js +240 -67
- package/chief-state.js +855 -109
- package/chief-view.js +38 -20
- package/client.js +5602 -2618
- package/digest.js +18 -9
- package/model-tools.js +92 -6
- package/package.json +41 -25
- package/runtime-hooks.js +221 -12
- package/safety/audit-log.js +95 -0
- package/safety/command-analyzer.js +339 -0
- package/safety/guard-walls.js +993 -0
- package/safety/index.js +78 -0
- package/safety/invariant-guards.js +280 -0
- package/safety/path-guard.js +227 -0
- package/safety/policy-engine.js +387 -0
- package/safety/policy-plugin.js +391 -0
- package/safety/tool-gate.js +278 -0
- package/subagent-runtime.js +266 -3
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,
|
|
@@ -22,7 +23,13 @@ import {
|
|
|
22
23
|
CHIEF_PERMISSION_META,
|
|
23
24
|
normalizePermissionMode,
|
|
24
25
|
permissionRank,
|
|
25
|
-
|
|
26
|
+
auditJsonlPath as safetyAuditJsonlPath,
|
|
27
|
+
normalizeAuditRecord,
|
|
28
|
+
appendAuditJsonlRecord,
|
|
29
|
+
resolveRoleCapabilities,
|
|
30
|
+
buildCapabilityScope,
|
|
31
|
+
validatePolicyPluginList,
|
|
32
|
+
} from './safety/index.js'
|
|
26
33
|
|
|
27
34
|
const APPROVALS_CAP = 30
|
|
28
35
|
|
|
@@ -30,10 +37,24 @@ const AUDIT_LOG_CAP = 80
|
|
|
30
37
|
|
|
31
38
|
const RESUME_TASKS_CAP = 20
|
|
32
39
|
|
|
40
|
+
const TASK_LEDGER_CAP = 30
|
|
41
|
+
|
|
33
42
|
const DEFAULT_RESUME_TTL_MS = 30 * 60 * 1000
|
|
34
43
|
|
|
35
44
|
const STATE_VERSION = 1
|
|
36
45
|
|
|
46
|
+
const activeResumingTaskIds = new Set()
|
|
47
|
+
|
|
48
|
+
export function markTaskResumingActive(taskId) {
|
|
49
|
+
const id = String(taskId || '').trim()
|
|
50
|
+
if (id) activeResumingTaskIds.add(id)
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function unmarkTaskResumingActive(taskId) {
|
|
54
|
+
const id = String(taskId || '').trim()
|
|
55
|
+
if (id) activeResumingTaskIds.delete(id)
|
|
56
|
+
}
|
|
57
|
+
|
|
37
58
|
export const FACTS_CAP = 120
|
|
38
59
|
|
|
39
60
|
export const FACT_TEXT_MAX = 260
|
|
@@ -66,6 +87,94 @@ export const CHIEF_UPDATE_SOURCE = 'dsh-chief-update'
|
|
|
66
87
|
|
|
67
88
|
export const CHIEF_RELAY_SOURCE = 'dsh-chief-relay'
|
|
68
89
|
|
|
90
|
+
export const CHIEF_INQUIRY_SOURCE = 'dsh-chief-inquiry'
|
|
91
|
+
|
|
92
|
+
export const CHIEF_EXEC_REQ_SOURCE = 'dsh-chief-execution-request'
|
|
93
|
+
|
|
94
|
+
export const CHAT_OPPORTUNISTIC_SUMMARY_COOLDOWN_MS = 60_000
|
|
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 function normalizeRunMode(raw, fallbackCfg = null) {
|
|
103
|
+
const s = typeof raw === 'string' ? raw.trim().toLowerCase() : ''
|
|
104
|
+
if (s === 'off' || s === 'patrol' || s === 'managed') return s
|
|
105
|
+
if (s === 'stopped' || s === 'manual') return 'off'
|
|
106
|
+
if (s === 'smart') return 'patrol'
|
|
107
|
+
if (s === 'auto' || s === 'autopilot') return 'managed'
|
|
108
|
+
if (fallbackCfg && typeof fallbackCfg === 'object') {
|
|
109
|
+
if (fallbackCfg.stopped || fallbackCfg.paceMode === 'stopped') return 'off'
|
|
110
|
+
if (fallbackCfg.autoPilot || fallbackCfg.paceMode === 'auto') return 'managed'
|
|
111
|
+
if (fallbackCfg.paceMode === 'smart') return 'patrol'
|
|
112
|
+
}
|
|
113
|
+
return 'off'
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export function normalizeThinkingEffort(raw) {
|
|
117
|
+
const s = typeof raw === 'string' ? raw.trim().toLowerCase() : ''
|
|
118
|
+
if (CHIEF_THINKING_EFFORTS.includes(s)) return s
|
|
119
|
+
return 'auto'
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function normalizeTeamEffortMode(raw) {
|
|
123
|
+
return String(raw || '').trim().toLowerCase() === 'manual' ? 'manual' : 'auto'
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export function normalizeLockedModelEfforts(raw) {
|
|
127
|
+
const out = {}
|
|
128
|
+
if (!raw || typeof raw !== 'object') return out
|
|
129
|
+
for (const [k, v] of Object.entries(raw)) {
|
|
130
|
+
const cleanKey = String(k || '').trim().slice(0, 64)
|
|
131
|
+
if (!cleanKey) continue
|
|
132
|
+
if (v === true) out[cleanKey] = true
|
|
133
|
+
}
|
|
134
|
+
return out
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const EFFORT_ORDER_LADDER = ['off', 'low', 'medium', 'high', 'xhigh']
|
|
138
|
+
|
|
139
|
+
export function resolveAlignedModelEffort(desiredEffort, supportedEfforts = []) {
|
|
140
|
+
const list = Array.isArray(supportedEfforts)
|
|
141
|
+
? supportedEfforts.map(e => (typeof e === 'string' ? e : (e && e.id ? String(e.id) : ''))).filter(Boolean)
|
|
142
|
+
: []
|
|
143
|
+
if (!list.length) return undefined
|
|
144
|
+
const want = String(desiredEffort || '').trim().toLowerCase()
|
|
145
|
+
if (!want || want === 'auto') {
|
|
146
|
+
if (list.includes('medium')) return 'medium'
|
|
147
|
+
return list[Math.floor(list.length / 2)] || list[0]
|
|
148
|
+
}
|
|
149
|
+
if (list.includes(want)) return want
|
|
150
|
+
const wantIdx = EFFORT_ORDER_LADDER.indexOf(want)
|
|
151
|
+
if (wantIdx < 0) return list[0]
|
|
152
|
+
for (let d = 1; d < EFFORT_ORDER_LADDER.length; d += 1) {
|
|
153
|
+
if (wantIdx - d >= 0 && list.includes(EFFORT_ORDER_LADDER[wantIdx - d])) {
|
|
154
|
+
return EFFORT_ORDER_LADDER[wantIdx - d]
|
|
155
|
+
}
|
|
156
|
+
if (wantIdx + d < EFFORT_ORDER_LADDER.length && list.includes(EFFORT_ORDER_LADDER[wantIdx + d])) {
|
|
157
|
+
return EFFORT_ORDER_LADDER[wantIdx + d]
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
return list[0]
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
export function touchWorkspaceActivity(sessionId) {
|
|
164
|
+
const sid = String(sessionId || '').trim()
|
|
165
|
+
if (!sid || sid === 'global') return false
|
|
166
|
+
try {
|
|
167
|
+
mutateChiefState((state) => {
|
|
168
|
+
const ws = ensureWorkspace(state, sid)
|
|
169
|
+
if (!ws.runtimeGuard || typeof ws.runtimeGuard !== 'object') ws.runtimeGuard = {}
|
|
170
|
+
ws.runtimeGuard.lastActivityAt = Date.now()
|
|
171
|
+
})
|
|
172
|
+
return true
|
|
173
|
+
} catch {
|
|
174
|
+
return false
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
69
178
|
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-----)/
|
|
70
179
|
|
|
71
180
|
let dshAttachmentModulePromise = null
|
|
@@ -138,10 +247,12 @@ export function archiveTargetForRoot(deps, rootId, extra = '') {
|
|
|
138
247
|
}
|
|
139
248
|
|
|
140
249
|
/**
|
|
141
|
-
* Chief-of-Staff visibility matrix (
|
|
142
|
-
* -
|
|
143
|
-
* -
|
|
144
|
-
*
|
|
250
|
+
* Chief-of-Staff visibility matrix (Three-Tier Hook Architecture):
|
|
251
|
+
* - Session Working Cabinet: Chief can always read session items + `recentlyUnpinnedWatch`.
|
|
252
|
+
* - Global Vault: Unorganized global items (without hooks) are 0-token invisible to Chief!
|
|
253
|
+
* Organized global items expose ONLY lightweight `globalHookIndex` (`hasHook: true`),
|
|
254
|
+
* until Chief explicitly pulls/mounts them (`chiefMountedSessions` / `chiefPulledSessions`).
|
|
255
|
+
* - Precipitated Cold Vault: 100% invisible to Chief (0 disk read, 0 hook leak) unless User explicitly `flippedOut`!
|
|
145
256
|
*/
|
|
146
257
|
export function collectChiefVisibleArchives(deps, rootId, stateSnapshot = null) {
|
|
147
258
|
const sid = rootId && rootId !== 'global' ? String(rootId).trim() : ''
|
|
@@ -154,6 +265,9 @@ export function collectChiefVisibleArchives(deps, rootId, stateSnapshot = null)
|
|
|
154
265
|
let deskGlobalItems = []
|
|
155
266
|
let deskFlippedItems = []
|
|
156
267
|
let mountedGlobalItems = []
|
|
268
|
+
let sessionItems = []
|
|
269
|
+
let recentlyUnpinnedWatch = []
|
|
270
|
+
let globalHookIndex = []
|
|
157
271
|
let sealedWatch = { sessionSealed: [], globalSealed: [], precipSealed: [] }
|
|
158
272
|
|
|
159
273
|
try {
|
|
@@ -161,13 +275,54 @@ export function collectChiefVisibleArchives(deps, rootId, stateSnapshot = null)
|
|
|
161
275
|
const stSess = loadArchiveStore(sessionTarget)
|
|
162
276
|
const allSess = Array.isArray(stSess.items) ? stSess.items : []
|
|
163
277
|
deskSessionItems = allSess.filter(it => Array.isArray(it.takenOutSessions) && it.takenOutSessions.includes(sid)).slice(0, 6)
|
|
278
|
+
sessionItems = allSess.slice(0, 16).map(it => ({
|
|
279
|
+
id: it.id,
|
|
280
|
+
title: it.title,
|
|
281
|
+
folder: it.folder,
|
|
282
|
+
summary: it.summary,
|
|
283
|
+
paperclip: it.paperclip,
|
|
284
|
+
hasHook: Boolean(it.hasHook),
|
|
285
|
+
hookKeywords: Array.isArray(it.hookKeywords) ? it.hookKeywords : [],
|
|
286
|
+
hookCue: it.hookCue || '',
|
|
287
|
+
takenOut: Array.isArray(it.takenOutSessions) && it.takenOutSessions.includes(sid),
|
|
288
|
+
points: Array.isArray(it.points) ? it.points.slice(0, 3) : [],
|
|
289
|
+
}))
|
|
290
|
+
recentlyUnpinnedWatch = Array.isArray(stSess.recentlyUnpinnedWatch) ? stSess.recentlyUnpinnedWatch.slice() : []
|
|
164
291
|
}
|
|
165
292
|
} catch {}
|
|
166
293
|
try {
|
|
294
|
+
const gStore = loadGlobalVaultRaw(globalTarget)
|
|
295
|
+
const gAll = Array.isArray(gStore && gStore.items) ? gStore.items : []
|
|
167
296
|
if (sid) {
|
|
168
297
|
deskGlobalItems = getTakenOutGlobalForSession(sid, globalTarget).slice(0, 6)
|
|
169
298
|
mountedGlobalItems = getChiefMountedGlobalForSession(sid, globalTarget).slice(0, 6)
|
|
299
|
+
// Also include entries Chief pulled in this session
|
|
300
|
+
const pulledSet = new Set(mountedGlobalItems.map(x => x.id))
|
|
301
|
+
for (const g of gAll) {
|
|
302
|
+
if (g && Array.isArray(g.chiefPulledSessions) && g.chiefPulledSessions.includes(sid) && !pulledSet.has(g.id)) {
|
|
303
|
+
mountedGlobalItems.push(g)
|
|
304
|
+
pulledSet.add(g.id)
|
|
305
|
+
if (mountedGlobalItems.length >= 6) break
|
|
306
|
+
}
|
|
307
|
+
}
|
|
170
308
|
}
|
|
309
|
+
globalHookIndex = gAll
|
|
310
|
+
.filter(it =>
|
|
311
|
+
it
|
|
312
|
+
&& it.hasHook === true
|
|
313
|
+
&& (!sid || (!Array.isArray(it.takenOutSessions) || !it.takenOutSessions.includes(sid)))
|
|
314
|
+
&& (!sid || (!Array.isArray(it.chiefMountedSessions) || !it.chiefMountedSessions.includes(sid)))
|
|
315
|
+
&& (!sid || (!Array.isArray(it.chiefPulledSessions) || !it.chiefPulledSessions.includes(sid)))
|
|
316
|
+
)
|
|
317
|
+
.slice(0, 12)
|
|
318
|
+
.map(it => ({
|
|
319
|
+
id: it.id,
|
|
320
|
+
title: it.title,
|
|
321
|
+
folder: it.folder,
|
|
322
|
+
paperclip: it.paperclip,
|
|
323
|
+
hookKeywords: Array.isArray(it.hookKeywords) ? it.hookKeywords : [],
|
|
324
|
+
hookCue: it.hookCue || '',
|
|
325
|
+
}))
|
|
171
326
|
} catch {}
|
|
172
327
|
try {
|
|
173
328
|
if (sid) {
|
|
@@ -188,6 +343,9 @@ export function collectChiefVisibleArchives(deps, rootId, stateSnapshot = null)
|
|
|
188
343
|
deskGlobalItems,
|
|
189
344
|
deskFlippedItems,
|
|
190
345
|
mountedGlobalItems,
|
|
346
|
+
sessionItems,
|
|
347
|
+
recentlyUnpinnedWatch,
|
|
348
|
+
globalHookIndex,
|
|
191
349
|
sealedWatch,
|
|
192
350
|
sessionTarget,
|
|
193
351
|
globalTarget,
|
|
@@ -309,15 +467,7 @@ function stateFilePath() {
|
|
|
309
467
|
}
|
|
310
468
|
|
|
311
469
|
export function auditJsonlPath() {
|
|
312
|
-
return
|
|
313
|
-
}
|
|
314
|
-
|
|
315
|
-
function appendAuditJsonlLine(record) {
|
|
316
|
-
try {
|
|
317
|
-
const file = auditJsonlPath()
|
|
318
|
-
fs.mkdirSync(path.dirname(file), { recursive: true })
|
|
319
|
-
fs.appendFileSync(file, JSON.stringify(record) + '\n', 'utf8')
|
|
320
|
-
} catch {}
|
|
470
|
+
return safetyAuditJsonlPath()
|
|
321
471
|
}
|
|
322
472
|
|
|
323
473
|
function canonicalSortJsonValue(val) {
|
|
@@ -362,9 +512,9 @@ function normalizePendingApproval(raw) {
|
|
|
362
512
|
if (!raw || typeof raw !== 'object') return null
|
|
363
513
|
const opLabel = clamp(raw.operationLabel || raw.operation || '', 80)
|
|
364
514
|
if (!opLabel) return null
|
|
365
|
-
const validStatuses = ['pending', 'approved', 'rejected', 'executed', 'failed']
|
|
515
|
+
const validStatuses = ['pending', 'approved', 'rejected', 'executed', 'failed', 'expired']
|
|
366
516
|
const status = validStatuses.includes(raw.status) ? raw.status : 'pending'
|
|
367
|
-
const validKinds = ['tool', 'relay', 'compact', 'auto_continue']
|
|
517
|
+
const validKinds = ['tool', 'relay', 'compact', 'auto_continue', 'archive_op', 'model_effort']
|
|
368
518
|
const kind = validKinds.includes(raw.kind) ? raw.kind : 'tool'
|
|
369
519
|
const validCategories = ['workspace_file', 'system_command', 'main_workflow', 'subagent_workflow']
|
|
370
520
|
const category = validCategories.includes(raw.category) ? raw.category : 'workspace_file'
|
|
@@ -372,6 +522,16 @@ function normalizePendingApproval(raw) {
|
|
|
372
522
|
const payloadHash = typeof raw.payloadHash === 'string' && raw.payloadHash.trim()
|
|
373
523
|
? raw.payloadHash.trim()
|
|
374
524
|
: computeApprovalPayloadHash(kind, payload)
|
|
525
|
+
const taskId = clamp(raw.taskId || raw.resumeTaskId || '', 80)
|
|
526
|
+
const capabilityScope = raw.capabilityScope && typeof raw.capabilityScope === 'object'
|
|
527
|
+
? raw.capabilityScope
|
|
528
|
+
: buildCapabilityScope({
|
|
529
|
+
kind,
|
|
530
|
+
tool: payload.tool || kind,
|
|
531
|
+
args: payload.args || {},
|
|
532
|
+
cwd: payload.cwd || '',
|
|
533
|
+
target: payload.target || '',
|
|
534
|
+
})
|
|
375
535
|
return {
|
|
376
536
|
id: typeof raw.id === 'string' && raw.id ? raw.id : nextId('apr'),
|
|
377
537
|
status,
|
|
@@ -384,7 +544,9 @@ function normalizePendingApproval(raw) {
|
|
|
384
544
|
kind,
|
|
385
545
|
payload,
|
|
386
546
|
payloadHash,
|
|
387
|
-
|
|
547
|
+
capabilityScope,
|
|
548
|
+
taskId,
|
|
549
|
+
resumeTaskId: taskId,
|
|
388
550
|
expiresAt: Math.max(0, Number(raw.expiresAt) || 0),
|
|
389
551
|
dedupeKey: clamp(raw.dedupeKey || '', 120),
|
|
390
552
|
by: clamp(raw.by || 'chief', 40),
|
|
@@ -401,6 +563,7 @@ function normalizePendingElevation(raw) {
|
|
|
401
563
|
const targetMode = normalizePermissionMode(raw.targetMode)
|
|
402
564
|
if (targetMode === 'advisor') return null
|
|
403
565
|
const createdAt = Number(raw.createdAt) || Date.now()
|
|
566
|
+
const taskId = clamp(raw.taskId || raw.resumeTaskId || '', 80)
|
|
404
567
|
return {
|
|
405
568
|
id: typeof raw.id === 'string' && raw.id ? raw.id : nextId('elv'),
|
|
406
569
|
status: 'pending',
|
|
@@ -408,65 +571,137 @@ function normalizePendingElevation(raw) {
|
|
|
408
571
|
targetMode,
|
|
409
572
|
reason: clamp(raw.reason || '当前任务需要更高参谋权限才能继续执行', 260),
|
|
410
573
|
requestedActionSummary: clamp(raw.requestedActionSummary || '', 220),
|
|
411
|
-
|
|
574
|
+
requestedCapabilities: Array.isArray(raw.requestedCapabilities)
|
|
575
|
+
? raw.requestedCapabilities.map(c => clamp(c, 60)).filter(Boolean).slice(0, 12)
|
|
576
|
+
: [],
|
|
577
|
+
taskId,
|
|
578
|
+
resumeTaskId: taskId,
|
|
412
579
|
expiresAt: Math.max(0, Number(raw.expiresAt) || (createdAt + DEFAULT_RESUME_TTL_MS)),
|
|
413
580
|
by: clamp(raw.by || 'chief', 40),
|
|
414
581
|
createdAt,
|
|
415
582
|
}
|
|
416
583
|
}
|
|
417
584
|
|
|
418
|
-
|
|
585
|
+
const VALID_TASK_LEDGER_STATUSES = [
|
|
586
|
+
'proposed',
|
|
587
|
+
'awaiting_elevation',
|
|
588
|
+
'awaiting_approval',
|
|
589
|
+
'awaiting_inquiry',
|
|
590
|
+
'dispatched',
|
|
591
|
+
'running',
|
|
592
|
+
'resuming',
|
|
593
|
+
'verifying',
|
|
594
|
+
'completed',
|
|
595
|
+
'interrupted',
|
|
596
|
+
'rejected',
|
|
597
|
+
'cancelled',
|
|
598
|
+
'expired',
|
|
599
|
+
'failed',
|
|
600
|
+
]
|
|
601
|
+
|
|
602
|
+
function normalizeTaskLedgerEntry(raw) {
|
|
419
603
|
if (!raw || typeof raw !== 'object') return null
|
|
420
|
-
const
|
|
604
|
+
const spec = raw.resumeSpec && typeof raw.resumeSpec === 'object' ? raw.resumeSpec : {}
|
|
605
|
+
const originalText = cleanMultiline(spec.originalText || raw.originalText || '', 2000)
|
|
421
606
|
if (!originalText) return null
|
|
422
|
-
const
|
|
423
|
-
const status = validStatuses.includes(raw.status) ? raw.status : 'awaiting_approval'
|
|
607
|
+
const status = VALID_TASK_LEDGER_STATUSES.includes(raw.status) ? raw.status : 'awaiting_approval'
|
|
424
608
|
const createdAt = Number(raw.createdAt) || Date.now()
|
|
609
|
+
const updatedAt = Number(raw.updatedAt) || createdAt
|
|
610
|
+
const taskId = typeof (raw.taskId || raw.id) === 'string' && (raw.taskId || raw.id)
|
|
611
|
+
? String(raw.taskId || raw.id)
|
|
612
|
+
: nextId('rtask')
|
|
613
|
+
const validKinds = ['approval_resume', 'elevation_resume', 'tool_execution', 'inquiry', 'auto_continue']
|
|
614
|
+
const kind = validKinds.includes(raw.kind)
|
|
615
|
+
? raw.kind
|
|
616
|
+
: (raw.elevationId || status === 'awaiting_elevation' ? 'elevation_resume' : 'approval_resume')
|
|
617
|
+
const forcedTarget = clamp(spec.forcedTarget !== undefined ? spec.forcedTarget : (raw.forcedTarget || ''), 64)
|
|
618
|
+
const forcedModeRaw = spec.forcedMode !== undefined ? spec.forcedMode : raw.forcedMode
|
|
619
|
+
const forcedMode = ['steer', 'followup', 'silent'].includes(forcedModeRaw) ? forcedModeRaw : 'steer'
|
|
620
|
+
const rawImages = Array.isArray(spec.savedImagePaths) ? spec.savedImagePaths : raw.savedImagePaths
|
|
621
|
+
const savedImagePaths = Array.isArray(rawImages)
|
|
622
|
+
? rawImages.slice(0, 4).filter(p => p && typeof p.path === 'string').map(p => ({
|
|
623
|
+
index: Number(p.index) || 1,
|
|
624
|
+
path: String(p.path),
|
|
625
|
+
name: clamp(p.name || '', 80),
|
|
626
|
+
mediaType: clamp(p.mediaType || '', 40),
|
|
627
|
+
bytes: Math.max(0, Number(p.bytes) || 0),
|
|
628
|
+
}))
|
|
629
|
+
: []
|
|
630
|
+
const rawCompleted = Array.isArray(spec.completedActions) ? spec.completedActions : raw.completedActions
|
|
631
|
+
const completedActions = Array.isArray(rawCompleted)
|
|
632
|
+
? rawCompleted.map(x => clamp(x, 220)).filter(Boolean).slice(-12)
|
|
633
|
+
: []
|
|
634
|
+
const retryCount = Math.max(0, Math.min(4, Math.round(Number(raw.retryCount !== undefined ? raw.retryCount : raw.resumeDepth) || 0)))
|
|
635
|
+
const capabilityScope = raw.capabilityScope && typeof raw.capabilityScope === 'object' ? raw.capabilityScope : null
|
|
636
|
+
const payloadHash = typeof raw.payloadHash === 'string' ? raw.payloadHash.trim() : ''
|
|
425
637
|
return {
|
|
426
|
-
id:
|
|
638
|
+
id: taskId,
|
|
639
|
+
taskId,
|
|
640
|
+
kind,
|
|
427
641
|
status,
|
|
642
|
+
capabilityScope,
|
|
643
|
+
payloadHash,
|
|
644
|
+
resumeSpec: {
|
|
645
|
+
originalText,
|
|
646
|
+
forcedTarget,
|
|
647
|
+
forcedMode,
|
|
648
|
+
savedImagePaths,
|
|
649
|
+
completedActions,
|
|
650
|
+
},
|
|
428
651
|
originalText,
|
|
429
|
-
forcedTarget
|
|
430
|
-
forcedMode
|
|
431
|
-
savedImagePaths
|
|
432
|
-
|
|
433
|
-
index: Number(p.index) || 1,
|
|
434
|
-
path: String(p.path),
|
|
435
|
-
name: clamp(p.name || '', 80),
|
|
436
|
-
mediaType: clamp(p.mediaType || '', 40),
|
|
437
|
-
bytes: Math.max(0, Number(p.bytes) || 0),
|
|
438
|
-
}))
|
|
439
|
-
: [],
|
|
440
|
-
completedActions: Array.isArray(raw.completedActions)
|
|
441
|
-
? raw.completedActions.map(x => clamp(x, 220)).filter(Boolean).slice(-12)
|
|
442
|
-
: [],
|
|
652
|
+
forcedTarget,
|
|
653
|
+
forcedMode,
|
|
654
|
+
savedImagePaths,
|
|
655
|
+
completedActions,
|
|
443
656
|
pendingApprovalIds: Array.isArray(raw.pendingApprovalIds)
|
|
444
657
|
? [...new Set(raw.pendingApprovalIds.map(x => String(x || '').trim()).filter(Boolean))].slice(0, 12)
|
|
445
658
|
: [],
|
|
446
659
|
elevationId: clamp(raw.elevationId || '', 80),
|
|
447
|
-
|
|
660
|
+
inquiryId: clamp(raw.inquiryId || '', 80),
|
|
661
|
+
lastReceipt: cleanMultiline(raw.lastReceipt || '', 300),
|
|
662
|
+
retryCount,
|
|
663
|
+
resumeDepth: retryCount,
|
|
448
664
|
createdAt,
|
|
665
|
+
updatedAt,
|
|
449
666
|
expiresAt: Math.max(0, Number(raw.expiresAt) || (createdAt + DEFAULT_RESUME_TTL_MS)),
|
|
450
667
|
resolvedAt: Math.max(0, Number(raw.resolvedAt) || 0),
|
|
451
668
|
}
|
|
452
669
|
}
|
|
453
670
|
|
|
671
|
+
export function recoverTaskLedgerEntriesOnDiskLoad(entries, now = Date.now()) {
|
|
672
|
+
if (!Array.isArray(entries)) return []
|
|
673
|
+
return entries.map((entry) => {
|
|
674
|
+
if (!entry || typeof entry !== 'object') return entry
|
|
675
|
+
const tid = entry.taskId || entry.id
|
|
676
|
+
if (
|
|
677
|
+
(entry.status === 'running' || entry.status === 'resuming' || entry.status === 'verifying')
|
|
678
|
+
&& !activeResumingTaskIds.has(tid)
|
|
679
|
+
) {
|
|
680
|
+
return {
|
|
681
|
+
...entry,
|
|
682
|
+
status: 'interrupted',
|
|
683
|
+
updatedAt: now,
|
|
684
|
+
lastReceipt: entry.lastReceipt || '检测到上次运行中断,已安全降级为 interrupted 等待人工确认续跑',
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
if (
|
|
688
|
+
(entry.status === 'proposed' || entry.status === 'awaiting_approval' || entry.status === 'awaiting_elevation' || entry.status === 'awaiting_inquiry')
|
|
689
|
+
&& entry.expiresAt > 0
|
|
690
|
+
&& now > entry.expiresAt
|
|
691
|
+
) {
|
|
692
|
+
return {
|
|
693
|
+
...entry,
|
|
694
|
+
status: 'expired',
|
|
695
|
+
updatedAt: now,
|
|
696
|
+
resolvedAt: entry.resolvedAt || now,
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
return entry
|
|
700
|
+
})
|
|
701
|
+
}
|
|
702
|
+
|
|
454
703
|
function normalizeAuditEntry(raw) {
|
|
455
|
-
|
|
456
|
-
const op = clamp(raw.operation || raw.tool || '', 80)
|
|
457
|
-
if (!op) return null
|
|
458
|
-
return {
|
|
459
|
-
id: typeof raw.id === 'string' && raw.id ? raw.id : nextId('aud'),
|
|
460
|
-
at: Number(raw.at) || Date.now(),
|
|
461
|
-
mode: normalizePermissionMode(raw.mode || DEFAULT_CHIEF_PERMISSION_MODE),
|
|
462
|
-
stage: clamp(raw.stage || 'executor', 40),
|
|
463
|
-
decision: clamp(raw.decision || 'executed', 40),
|
|
464
|
-
operation: op,
|
|
465
|
-
target: clamp(raw.target || '', 140),
|
|
466
|
-
reason: clamp(raw.reason || '', 220),
|
|
467
|
-
outcome: clamp(raw.outcome || 'ok', 40),
|
|
468
|
-
by: clamp(raw.by || 'chief', 40),
|
|
469
|
-
}
|
|
704
|
+
return normalizeAuditRecord(raw, DEFAULT_CHIEF_PERMISSION_MODE)
|
|
470
705
|
}
|
|
471
706
|
|
|
472
707
|
export function pushAuditToWs(ws, entry = {}, sessionId = '') {
|
|
@@ -476,24 +711,24 @@ export function pushAuditToWs(ws, entry = {}, sessionId = '') {
|
|
|
476
711
|
if (!norm) return null
|
|
477
712
|
ws.auditLog.push(norm)
|
|
478
713
|
if (ws.auditLog.length > AUDIT_LOG_CAP) ws.auditLog = ws.auditLog.slice(-AUDIT_LOG_CAP)
|
|
479
|
-
|
|
480
|
-
...(sessionId ? { sessionId: String(sessionId) } : {}),
|
|
481
|
-
...norm,
|
|
482
|
-
})
|
|
714
|
+
appendAuditJsonlRecord(norm, sessionId)
|
|
483
715
|
return norm
|
|
484
716
|
}
|
|
485
717
|
|
|
486
718
|
function emptyWorkspace() {
|
|
719
|
+
const sharedLedger = []
|
|
487
720
|
return {
|
|
488
721
|
config: null,
|
|
489
722
|
chiefRiskAck: null,
|
|
490
723
|
pendingApprovals: [],
|
|
491
724
|
pendingElevation: null,
|
|
492
|
-
|
|
725
|
+
taskLedger: sharedLedger,
|
|
726
|
+
resumeTasks: sharedLedger,
|
|
493
727
|
auditLog: [],
|
|
494
728
|
facts: [],
|
|
495
729
|
narrative: { hash: '', text: '', at: 0, byModel: '', clusterSig: '' },
|
|
496
730
|
suggestions: [],
|
|
731
|
+
inquiries: [],
|
|
497
732
|
chat: [],
|
|
498
733
|
mailbox: [],
|
|
499
734
|
seenMailAt: {},
|
|
@@ -512,6 +747,9 @@ function emptyWorkspace() {
|
|
|
512
747
|
lastGoalAchievedSig: '',
|
|
513
748
|
autoPilotStartedAt: 0,
|
|
514
749
|
autoPilotHadTurn: false,
|
|
750
|
+
managedStartedAt: 0,
|
|
751
|
+
lastActivityAt: 0,
|
|
752
|
+
lastDreamRoamAt: 0,
|
|
515
753
|
lastAutoArchiveOrgAt: 0,
|
|
516
754
|
},
|
|
517
755
|
flippedPrecipitatedIds: [],
|
|
@@ -545,34 +783,72 @@ export function normalizeSuggestion(raw) {
|
|
|
545
783
|
if (!raw || typeof raw !== 'object') return null
|
|
546
784
|
const title = clamp(raw.title, 90)
|
|
547
785
|
if (!title) return null
|
|
548
|
-
const kind = ['bound', 'board', 'goal_approval', 'relay', 'advice'].includes(raw.kind) ? raw.kind : 'relay'
|
|
786
|
+
const kind = ['bound', 'board', 'goal_approval', 'relay', 'advice', 'guard_wall', 'wall_removal', 'archive_op', 'model_effort'].includes(raw.kind) ? raw.kind : 'relay'
|
|
549
787
|
const boundField = ['forbidden', 'allowed', 'notes'].includes(raw.boundField) ? raw.boundField : 'forbidden'
|
|
550
788
|
const replaces = Array.isArray(raw.replaces)
|
|
551
789
|
? raw.replaces.map(x => String(x || '').trim()).filter(Boolean).slice(0, 20)
|
|
552
790
|
: []
|
|
791
|
+
const wallSpec = raw.wallSpec && typeof raw.wallSpec === 'object' ? { ...raw.wallSpec } : null
|
|
792
|
+
const wallRemovalSpec = raw.wallRemovalSpec && typeof raw.wallRemovalSpec === 'object' ? { ...raw.wallRemovalSpec } : null
|
|
793
|
+
const archiveSpec = (raw.archiveSpec && typeof raw.archiveSpec === 'object')
|
|
794
|
+
? { ...raw.archiveSpec }
|
|
795
|
+
: ((raw.archiveOp && typeof raw.archiveOp === 'object') ? { ...raw.archiveOp } : null)
|
|
796
|
+
const effortSpec = (raw.effortSpec && typeof raw.effortSpec === 'object')
|
|
797
|
+
? { ...raw.effortSpec }
|
|
798
|
+
: ((raw.effortOp && typeof raw.effortOp === 'object') ? { ...raw.effortOp } : null)
|
|
553
799
|
return {
|
|
554
800
|
id: typeof raw.id === 'string' && raw.id ? raw.id : nextId('sug'),
|
|
555
801
|
kind,
|
|
556
802
|
boundField,
|
|
557
803
|
replaces,
|
|
558
804
|
pinGlobal: Boolean(raw.pinGlobal),
|
|
805
|
+
...(wallSpec ? { wallSpec } : {}),
|
|
806
|
+
...(wallRemovalSpec ? { wallRemovalSpec } : {}),
|
|
807
|
+
...(archiveSpec ? { archiveSpec } : {}),
|
|
808
|
+
...(effortSpec ? { effortSpec } : {}),
|
|
559
809
|
fromAgent: clamp(raw.fromAgent || '', 48),
|
|
560
810
|
title,
|
|
561
811
|
reason: clamp(raw.reason || '', 220),
|
|
562
|
-
target: clamp(raw.target || (kind === 'bound' ? 'bounds' : kind === 'goal_approval' ? 'board' : 'lead'), 64),
|
|
563
|
-
targetLabel: clamp(raw.targetLabel || raw.target || (kind === 'bound' ? '工作边界' : kind === 'goal_approval' ? '目标结项批示' : kind === 'advice' ? '参谋进言' : '主对话'), 40),
|
|
812
|
+
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),
|
|
813
|
+
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),
|
|
564
814
|
mode: ['steer', 'followup', 'silent'].includes(raw.mode) ? raw.mode : (kind === 'advice' ? 'followup' : 'steer'),
|
|
565
815
|
draftText: cleanMultiline(raw.draftText || '', 600),
|
|
566
816
|
evidence: cleanMultiline(raw.evidence || '', 600),
|
|
567
817
|
missing: clamp(raw.missing || '', 300),
|
|
568
818
|
boardOp: raw.boardOp && typeof raw.boardOp === 'object' ? raw.boardOp : null,
|
|
569
|
-
popup: Boolean(raw.popup || kind === 'advice'),
|
|
570
|
-
urgency: ['normal', 'high'].includes(raw.urgency) ? raw.urgency : 'normal',
|
|
819
|
+
popup: Boolean(raw.popup || kind === 'advice' || kind === 'wall_removal'),
|
|
820
|
+
urgency: ['normal', 'high'].includes(raw.urgency) ? raw.urgency : (kind === 'wall_removal' ? 'high' : 'normal'),
|
|
571
821
|
status: ['pending', 'applied', 'dismissed'].includes(raw.status) ? raw.status : 'pending',
|
|
572
822
|
createdAt: Number(raw.createdAt) || Date.now(),
|
|
573
823
|
}
|
|
574
824
|
}
|
|
575
825
|
|
|
826
|
+
export function normalizeInquiryItem(raw) {
|
|
827
|
+
if (!raw || typeof raw !== 'object') return null
|
|
828
|
+
const question = cleanMultiline(raw.question || raw.text || '', 600)
|
|
829
|
+
if (!question) return null
|
|
830
|
+
const status = ['pending', 'delivered', 'answered', 'expired'].includes(raw.status) ? raw.status : 'pending'
|
|
831
|
+
const inquiryId = typeof (raw.inquiryId || raw.id) === 'string' && (raw.inquiryId || raw.id)
|
|
832
|
+
? String(raw.inquiryId || raw.id)
|
|
833
|
+
: nextId('inq')
|
|
834
|
+
return {
|
|
835
|
+
id: inquiryId,
|
|
836
|
+
inquiryId,
|
|
837
|
+
taskId: clamp(raw.taskId || '', 80),
|
|
838
|
+
target: clamp(raw.target || 'lead', 64),
|
|
839
|
+
question,
|
|
840
|
+
context: clamp(raw.context || '', 220),
|
|
841
|
+
answer: cleanMultiline(raw.answer || '', 1200),
|
|
842
|
+
status,
|
|
843
|
+
by: clamp(raw.by || 'chief', 40),
|
|
844
|
+
answeredBy: clamp(raw.answeredBy || '', 40),
|
|
845
|
+
createdAt: Number(raw.createdAt) || Date.now(),
|
|
846
|
+
deliveredAt: Number(raw.deliveredAt) || 0,
|
|
847
|
+
answeredAt: Number(raw.answeredAt) || 0,
|
|
848
|
+
expiresAt: Number(raw.expiresAt) || ((Number(raw.createdAt) || Date.now()) + DEFAULT_RESUME_TTL_MS),
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
|
|
576
852
|
export function normalizeMail(raw) {
|
|
577
853
|
if (!raw || typeof raw !== 'object') return null
|
|
578
854
|
const imageCount = Math.max(0, Math.round(Number(raw.imageCount) || 0))
|
|
@@ -621,6 +897,10 @@ function normalizeWorkspace(raw) {
|
|
|
621
897
|
.map(normalizeSuggestion)
|
|
622
898
|
.filter(Boolean)
|
|
623
899
|
.slice(-SUGGESTIONS_CAP * 2)
|
|
900
|
+
base.inquiries = (Array.isArray(src.inquiries) ? src.inquiries : [])
|
|
901
|
+
.map(normalizeInquiryItem)
|
|
902
|
+
.filter(Boolean)
|
|
903
|
+
.slice(-24)
|
|
624
904
|
base.chat = (Array.isArray(src.chat) ? src.chat : [])
|
|
625
905
|
.filter(item => item && typeof item === 'object' && typeof item.text === 'string')
|
|
626
906
|
.slice(-CHAT_CAP)
|
|
@@ -628,6 +908,8 @@ function normalizeWorkspace(raw) {
|
|
|
628
908
|
const imageCount = Math.max(0, Math.round(Number(item.imageCount) || 0))
|
|
629
909
|
const kind = item.kind === 'receipt' ? 'receipt' : (item.kind === 'qa' ? 'qa' : '')
|
|
630
910
|
const resumeTaskId = item.resumeTaskId ? String(item.resumeTaskId) : ''
|
|
911
|
+
const thinkingEffort = typeof item.thinkingEffort === 'string' && item.thinkingEffort ? item.thinkingEffort : ''
|
|
912
|
+
const thinkingEffortMode = item.thinkingEffortMode === 'auto' || item.thinkingEffortMode === 'manual' ? item.thinkingEffortMode : ''
|
|
631
913
|
return {
|
|
632
914
|
id: String(item.id || nextId('chat')),
|
|
633
915
|
role: item.role === 'user' ? 'user' : 'chief',
|
|
@@ -635,6 +917,9 @@ function normalizeWorkspace(raw) {
|
|
|
635
917
|
target: item.target ? String(item.target) : '',
|
|
636
918
|
...(kind ? { kind } : {}),
|
|
637
919
|
...(resumeTaskId ? { resumeTaskId } : {}),
|
|
920
|
+
...(thinkingEffort ? { thinkingEffort } : {}),
|
|
921
|
+
...(thinkingEffortMode ? { thinkingEffortMode } : {}),
|
|
922
|
+
...(item.isOneStopReport ? { isOneStopReport: true } : {}),
|
|
638
923
|
...(imageCount > 0 ? { imageCount } : {}),
|
|
639
924
|
actions: Array.isArray(item.actions) ? item.actions.slice(0, 8) : [],
|
|
640
925
|
at: Number(item.at) || Date.now(),
|
|
@@ -675,6 +960,9 @@ function normalizeWorkspace(raw) {
|
|
|
675
960
|
lastGoalAchievedSig: String(rg.lastGoalAchievedSig || ''),
|
|
676
961
|
autoPilotStartedAt: Math.max(0, Number(rg.autoPilotStartedAt) || 0),
|
|
677
962
|
autoPilotHadTurn: Boolean(rg.autoPilotHadTurn),
|
|
963
|
+
managedStartedAt: Math.max(0, Number(rg.managedStartedAt) || Number(rg.autoPilotStartedAt) || 0),
|
|
964
|
+
lastActivityAt: Math.max(0, Number(rg.lastActivityAt) || 0),
|
|
965
|
+
lastDreamRoamAt: Math.max(0, Number(rg.lastDreamRoamAt) || 0),
|
|
678
966
|
lastAutoArchiveOrgAt: Math.max(0, Number(rg.lastAutoArchiveOrgAt) || 0),
|
|
679
967
|
}
|
|
680
968
|
base.chiefRiskAck = normalizeChiefRiskAck(src.chiefRiskAck)
|
|
@@ -683,10 +971,15 @@ function normalizeWorkspace(raw) {
|
|
|
683
971
|
.filter(Boolean)
|
|
684
972
|
.slice(-APPROVALS_CAP)
|
|
685
973
|
base.pendingElevation = normalizePendingElevation(src.pendingElevation)
|
|
686
|
-
|
|
687
|
-
.
|
|
974
|
+
const rawLedgerSrc = Array.isArray(src.taskLedger) && src.taskLedger.length > 0
|
|
975
|
+
? src.taskLedger
|
|
976
|
+
: (Array.isArray(src.resumeTasks) ? src.resumeTasks : [])
|
|
977
|
+
const normalizedLedger = rawLedgerSrc
|
|
978
|
+
.map(normalizeTaskLedgerEntry)
|
|
688
979
|
.filter(Boolean)
|
|
689
|
-
.slice(-
|
|
980
|
+
.slice(-TASK_LEDGER_CAP)
|
|
981
|
+
base.taskLedger = normalizedLedger
|
|
982
|
+
base.resumeTasks = normalizedLedger
|
|
690
983
|
base.auditLog = (Array.isArray(src.auditLog) ? src.auditLog : [])
|
|
691
984
|
.map(normalizeAuditEntry)
|
|
692
985
|
.filter(Boolean)
|
|
@@ -696,14 +989,27 @@ function normalizeWorkspace(raw) {
|
|
|
696
989
|
const validPaces = ['manual', 'smart', 'auto', 'stopped']
|
|
697
990
|
const pm = validPaces.includes(src.config.paceMode) ? src.config.paceMode : undefined
|
|
698
991
|
const rawStopped = typeof src.config.stopped === 'boolean' ? src.config.stopped : (pm === 'stopped')
|
|
992
|
+
const rm = normalizeRunMode(src.config.runMode, { ...src.config, stopped: rawStopped, paceMode: pm })
|
|
699
993
|
const rawPerm = typeof src.config.permissionMode === 'string'
|
|
700
994
|
? normalizePermissionMode(src.config.permissionMode, { requireAck: true, hasChiefRiskAck: ackOk })
|
|
701
995
|
: DEFAULT_CHIEF_PERMISSION_MODE
|
|
996
|
+
const plugCheck = validatePolicyPluginList(src.config.policyPlugins)
|
|
997
|
+
const policyPlugins = plugCheck.ok ? plugCheck.plugins : []
|
|
998
|
+
const lockedModelEfforts = normalizeLockedModelEfforts(src.config.lockedModelEfforts)
|
|
999
|
+
const managedIdleTimeoutMs = Number.isFinite(Number(src.config.managedIdleTimeoutMs)) && Number(src.config.managedIdleTimeoutMs) >= 50
|
|
1000
|
+
? Math.min(2 * 60 * 60 * 1000, Math.round(Number(src.config.managedIdleTimeoutMs)))
|
|
1001
|
+
: DEFAULT_MANAGED_IDLE_TIMEOUT_MS
|
|
702
1002
|
base.config = {
|
|
703
1003
|
...(typeof src.config.modelRef === 'string' ? { modelRef: src.config.modelRef.trim() } : {}),
|
|
704
1004
|
permissionMode: rawPerm,
|
|
1005
|
+
runMode: rm,
|
|
1006
|
+
managedIdleTimeoutMs,
|
|
1007
|
+
...(typeof src.config.thinkingEffort === 'string' ? { thinkingEffort: normalizeThinkingEffort(src.config.thinkingEffort) } : {}),
|
|
1008
|
+
...(typeof src.config.teamEffortMode === 'string' ? { teamEffortMode: normalizeTeamEffortMode(src.config.teamEffortMode) } : {}),
|
|
1009
|
+
...(Object.keys(lockedModelEfforts).length ? { lockedModelEfforts } : {}),
|
|
705
1010
|
...(typeof src.config.stopped === 'boolean' || pm === 'stopped' ? { stopped: rawStopped } : {}),
|
|
706
1011
|
...(pm ? { paceMode: pm, autoPilot: !rawStopped && pm === 'auto', autoReview: !rawStopped && pm !== 'manual' } : {}),
|
|
1012
|
+
...(policyPlugins.length > 0 ? { policyPlugins } : {}),
|
|
707
1013
|
...(src.config.tacticalModes && typeof src.config.tacticalModes === 'object'
|
|
708
1014
|
? { tacticalModes: normalizeTacticalModes(src.config.tacticalModes) }
|
|
709
1015
|
: {}),
|
|
@@ -800,19 +1106,54 @@ export function resolveWorkspaceConfig(state, sessionId = '') {
|
|
|
800
1106
|
const rawPerm = (wsCfg && typeof wsCfg.permissionMode === 'string')
|
|
801
1107
|
? wsCfg.permissionMode
|
|
802
1108
|
: DEFAULT_CHIEF_PERMISSION_MODE
|
|
803
|
-
const
|
|
804
|
-
|
|
1109
|
+
const globalPlugCheck = validatePolicyPluginList(base.policyPlugins)
|
|
1110
|
+
const wsPlugCheck = validatePolicyPluginList(wsCfg && wsCfg.policyPlugins)
|
|
1111
|
+
const policyPlugins = [
|
|
1112
|
+
...(globalPlugCheck.ok ? globalPlugCheck.plugins : []),
|
|
1113
|
+
...(wsPlugCheck.ok ? wsPlugCheck.plugins : []),
|
|
1114
|
+
]
|
|
1115
|
+
const resolvedRoleCaps = resolveRoleCapabilities(rawPerm, {
|
|
805
1116
|
hasChiefRiskAck: ackOk,
|
|
1117
|
+
policyPlugins,
|
|
806
1118
|
})
|
|
1119
|
+
const permissionMode = resolvedRoleCaps.role
|
|
807
1120
|
const chiefRiskVerified = permissionMode === 'chief' ? ackOk : false
|
|
1121
|
+
const runMode = stopped
|
|
1122
|
+
? 'off'
|
|
1123
|
+
: (wsCfg && typeof wsCfg.runMode === 'string' && CHIEF_RUN_MODES.includes(wsCfg.runMode)
|
|
1124
|
+
? wsCfg.runMode
|
|
1125
|
+
: normalizeRunMode(undefined, { stopped, paceMode, autoPilot: paceMode === 'auto' }))
|
|
1126
|
+
const thinkingEffort = normalizeThinkingEffort(
|
|
1127
|
+
(wsCfg && typeof wsCfg.thinkingEffort === 'string' && wsCfg.thinkingEffort)
|
|
1128
|
+
|| (typeof base.thinkingEffort === 'string' && base.thinkingEffort)
|
|
1129
|
+
|| 'auto',
|
|
1130
|
+
)
|
|
1131
|
+
const teamEffortMode = normalizeTeamEffortMode(
|
|
1132
|
+
(wsCfg && typeof wsCfg.teamEffortMode === 'string' && wsCfg.teamEffortMode)
|
|
1133
|
+
|| (typeof base.teamEffortMode === 'string' && base.teamEffortMode)
|
|
1134
|
+
|| 'auto',
|
|
1135
|
+
)
|
|
1136
|
+
const lockedModelEfforts = normalizeLockedModelEfforts(wsCfg && wsCfg.lockedModelEfforts)
|
|
1137
|
+
const managedIdleTimeoutMs = wsCfg && Number.isFinite(Number(wsCfg.managedIdleTimeoutMs)) && Number(wsCfg.managedIdleTimeoutMs) >= 50
|
|
1138
|
+
? Math.min(2 * 60 * 60 * 1000, Math.round(Number(wsCfg.managedIdleTimeoutMs)))
|
|
1139
|
+
: (Number.isFinite(Number(base.managedIdleTimeoutMs)) && Number(base.managedIdleTimeoutMs) >= 50
|
|
1140
|
+
? Math.min(2 * 60 * 60 * 1000, Math.round(Number(base.managedIdleTimeoutMs)))
|
|
1141
|
+
: DEFAULT_MANAGED_IDLE_TIMEOUT_MS)
|
|
808
1142
|
return {
|
|
809
1143
|
modelRef,
|
|
810
1144
|
paceMode,
|
|
1145
|
+
runMode,
|
|
1146
|
+
managedIdleTimeoutMs,
|
|
1147
|
+
thinkingEffort,
|
|
1148
|
+
teamEffortMode,
|
|
1149
|
+
lockedModelEfforts,
|
|
811
1150
|
stopped,
|
|
812
1151
|
permissionMode,
|
|
1152
|
+
capabilities: resolvedRoleCaps.capabilities,
|
|
1153
|
+
policyPlugins,
|
|
813
1154
|
chiefRiskVerified,
|
|
814
|
-
autoPilot: !stopped &&
|
|
815
|
-
autoReview: !stopped &&
|
|
1155
|
+
autoPilot: !stopped && runMode === 'managed',
|
|
1156
|
+
autoReview: !stopped && runMode === 'managed',
|
|
816
1157
|
tacticalModes: mergedTactical,
|
|
817
1158
|
}
|
|
818
1159
|
}
|
|
@@ -883,15 +1224,23 @@ function normalizeState(raw) {
|
|
|
883
1224
|
const rawPace = validPaces.includes(cfg.paceMode) ? cfg.paceMode : 'manual'
|
|
884
1225
|
const stopped = rawPace === 'stopped' || Boolean(cfg.stopped)
|
|
885
1226
|
const paceMode = stopped ? 'stopped' : rawPace
|
|
1227
|
+
const globalPlugRes = validatePolicyPluginList(cfg.policyPlugins)
|
|
886
1228
|
return {
|
|
887
1229
|
version: STATE_VERSION,
|
|
888
1230
|
config: {
|
|
889
1231
|
modelRef: typeof cfg.modelRef === 'string' ? cfg.modelRef.trim() : '',
|
|
890
1232
|
paceMode,
|
|
1233
|
+
runMode: stopped ? 'off' : normalizeRunMode(cfg.runMode, { stopped, paceMode }),
|
|
1234
|
+
managedIdleTimeoutMs: Number.isFinite(Number(cfg.managedIdleTimeoutMs)) && Number(cfg.managedIdleTimeoutMs) >= 50
|
|
1235
|
+
? Math.min(2 * 60 * 60 * 1000, Math.round(Number(cfg.managedIdleTimeoutMs)))
|
|
1236
|
+
: DEFAULT_MANAGED_IDLE_TIMEOUT_MS,
|
|
1237
|
+
thinkingEffort: normalizeThinkingEffort(cfg.thinkingEffort),
|
|
1238
|
+
teamEffortMode: normalizeTeamEffortMode(cfg.teamEffortMode),
|
|
891
1239
|
stopped,
|
|
892
1240
|
permissionMode: DEFAULT_CHIEF_PERMISSION_MODE,
|
|
893
1241
|
autoPilot: !stopped && paceMode === 'auto',
|
|
894
1242
|
autoReview: !stopped && paceMode !== 'manual',
|
|
1243
|
+
...(globalPlugRes.ok && globalPlugRes.plugins.length > 0 ? { policyPlugins: globalPlugRes.plugins } : {}),
|
|
895
1244
|
tacticalModes: normalizeTacticalModes(cfg.tacticalModes),
|
|
896
1245
|
},
|
|
897
1246
|
links,
|
|
@@ -982,32 +1331,141 @@ export function requestChiefElevation(sessionId = 'global', req = {}) {
|
|
|
982
1331
|
})
|
|
983
1332
|
}
|
|
984
1333
|
|
|
985
|
-
export function
|
|
1334
|
+
export function upsertTaskLedgerOnWs(ws, rawTask = {}) {
|
|
986
1335
|
if (!ws || typeof ws !== 'object') return null
|
|
987
|
-
if (!Array.isArray(ws.
|
|
988
|
-
|
|
1336
|
+
if (!Array.isArray(ws.taskLedger)) {
|
|
1337
|
+
ws.taskLedger = Array.isArray(ws.resumeTasks) ? ws.resumeTasks : []
|
|
1338
|
+
}
|
|
1339
|
+
ws.resumeTasks = ws.taskLedger
|
|
1340
|
+
const lookupId = rawTask.taskId || rawTask.id
|
|
1341
|
+
const existingIdx = lookupId ? ws.taskLedger.findIndex(t => t && (t.taskId === lookupId || t.id === lookupId)) : -1
|
|
989
1342
|
if (existingIdx >= 0) {
|
|
990
|
-
const prev = ws.
|
|
991
|
-
const merged =
|
|
1343
|
+
const prev = ws.taskLedger[existingIdx]
|
|
1344
|
+
const merged = normalizeTaskLedgerEntry({
|
|
992
1345
|
...prev,
|
|
993
1346
|
...rawTask,
|
|
1347
|
+
updatedAt: Date.now(),
|
|
994
1348
|
completedActions: rawTask.appendCompletedAction
|
|
995
1349
|
? [...(prev.completedActions || []), rawTask.appendCompletedAction]
|
|
996
1350
|
: (rawTask.completedActions || prev.completedActions),
|
|
997
1351
|
pendingApprovalIds: rawTask.pendingApprovalIds || prev.pendingApprovalIds,
|
|
998
1352
|
})
|
|
999
|
-
if (merged) ws.
|
|
1353
|
+
if (merged) ws.taskLedger[existingIdx] = merged
|
|
1000
1354
|
return merged
|
|
1001
1355
|
}
|
|
1002
|
-
const created =
|
|
1356
|
+
const created = normalizeTaskLedgerEntry(rawTask)
|
|
1003
1357
|
if (!created) return null
|
|
1004
|
-
ws.
|
|
1005
|
-
if (ws.
|
|
1006
|
-
ws.
|
|
1358
|
+
ws.taskLedger.push(created)
|
|
1359
|
+
if (ws.taskLedger.length > TASK_LEDGER_CAP) {
|
|
1360
|
+
ws.taskLedger = ws.taskLedger.slice(-TASK_LEDGER_CAP)
|
|
1361
|
+
ws.resumeTasks = ws.taskLedger
|
|
1007
1362
|
}
|
|
1008
1363
|
return created
|
|
1009
1364
|
}
|
|
1010
1365
|
|
|
1366
|
+
export function upsertResumeTaskOnWs(ws, rawTask = {}) {
|
|
1367
|
+
return upsertTaskLedgerOnWs(ws, rawTask)
|
|
1368
|
+
}
|
|
1369
|
+
|
|
1370
|
+
export function enqueueChiefInquiryOnWs(ws, raw = {}) {
|
|
1371
|
+
if (!ws || typeof ws !== 'object') return null
|
|
1372
|
+
if (!Array.isArray(ws.inquiries)) ws.inquiries = []
|
|
1373
|
+
const norm = normalizeInquiryItem(raw)
|
|
1374
|
+
if (!norm) return null
|
|
1375
|
+
const dup = ws.inquiries.find(
|
|
1376
|
+
q => q && (q.status === 'pending' || q.status === 'delivered') && q.question === norm.question && q.target === norm.target,
|
|
1377
|
+
)
|
|
1378
|
+
if (dup) return dup
|
|
1379
|
+
ws.inquiries.push(norm)
|
|
1380
|
+
if (ws.inquiries.length > 24) ws.inquiries = ws.inquiries.slice(-24)
|
|
1381
|
+
return norm
|
|
1382
|
+
}
|
|
1383
|
+
|
|
1384
|
+
export function answerChiefInquiry(sessionId = 'global', { inquiryId = '', answer = '', by = 'lead' } = {}) {
|
|
1385
|
+
const rootId = String(sessionId || 'global').trim() || 'global'
|
|
1386
|
+
const cleanAns = cleanMultiline(answer || '', 1200)
|
|
1387
|
+
if (!cleanAns) return { ok: false, error: 'inquiry.reply 需要非空答复文本 (text)' }
|
|
1388
|
+
return mutateChiefState((state) => {
|
|
1389
|
+
const ws = ensureWorkspace(state, rootId)
|
|
1390
|
+
if (!Array.isArray(ws.inquiries)) ws.inquiries = []
|
|
1391
|
+
let idx = inquiryId
|
|
1392
|
+
? ws.inquiries.findIndex(q => q && (q.inquiryId === inquiryId || q.id === inquiryId))
|
|
1393
|
+
: -1
|
|
1394
|
+
if (idx < 0 && !inquiryId) {
|
|
1395
|
+
for (let i = ws.inquiries.length - 1; i >= 0; i -= 1) {
|
|
1396
|
+
if (ws.inquiries[i] && (ws.inquiries[i].status === 'pending' || ws.inquiries[i].status === 'delivered')) {
|
|
1397
|
+
idx = i
|
|
1398
|
+
break
|
|
1399
|
+
}
|
|
1400
|
+
}
|
|
1401
|
+
}
|
|
1402
|
+
if (idx < 0) return { ok: false, error: `未找到待回复问询:${inquiryId || '最近未答问询'}` }
|
|
1403
|
+
const existing = ws.inquiries[idx]
|
|
1404
|
+
if (!existing || existing.status === 'answered' || (existing.status !== 'pending' && existing.status !== 'delivered')) {
|
|
1405
|
+
const prevId = (existing && existing.inquiryId) || inquiryId
|
|
1406
|
+
const prevStatus = (existing && existing.status) || 'unknown'
|
|
1407
|
+
pushAuditToWs(ws, {
|
|
1408
|
+
mode: resolveWorkspaceConfig(state, rootId).permissionMode,
|
|
1409
|
+
stage: 'inquiry_channel',
|
|
1410
|
+
rule: 'inquiry_reply_replay_rejected',
|
|
1411
|
+
decision: 'rejected',
|
|
1412
|
+
operation: '拦截重复问询答复',
|
|
1413
|
+
target: prevId,
|
|
1414
|
+
reason: `问询 #${prevId} 已结案 (status=${prevStatus}),拒绝重放覆写`,
|
|
1415
|
+
outcome: 'rejected',
|
|
1416
|
+
by: clamp(by || 'lead', 40),
|
|
1417
|
+
}, rootId)
|
|
1418
|
+
return {
|
|
1419
|
+
ok: false,
|
|
1420
|
+
alreadyAnswered: true,
|
|
1421
|
+
code: 'inquiry_already_answered',
|
|
1422
|
+
error: `问询 #${prevId} 已回复结案,拒绝重复应答`,
|
|
1423
|
+
inquiry: existing,
|
|
1424
|
+
}
|
|
1425
|
+
}
|
|
1426
|
+
const now = Date.now()
|
|
1427
|
+
const item = {
|
|
1428
|
+
...existing,
|
|
1429
|
+
status: 'answered',
|
|
1430
|
+
answer: cleanAns,
|
|
1431
|
+
answeredBy: clamp(by || 'lead', 40),
|
|
1432
|
+
answeredAt: now,
|
|
1433
|
+
}
|
|
1434
|
+
ws.inquiries[idx] = item
|
|
1435
|
+
if (item.taskId) {
|
|
1436
|
+
upsertTaskLedgerOnWs(ws, {
|
|
1437
|
+
taskId: item.taskId,
|
|
1438
|
+
kind: 'inquiry',
|
|
1439
|
+
status: 'completed',
|
|
1440
|
+
inquiryId: item.inquiryId,
|
|
1441
|
+
lastReceipt: `已收到 ${item.answeredBy} 原路答复:${clamp(cleanAns, 120)}`,
|
|
1442
|
+
resolvedAt: now,
|
|
1443
|
+
})
|
|
1444
|
+
}
|
|
1445
|
+
ws.chat.push({
|
|
1446
|
+
id: nextId('chat'),
|
|
1447
|
+
role: 'chief',
|
|
1448
|
+
kind: 'receipt',
|
|
1449
|
+
text: `- 【⚡ 优先问询回执 #${item.inquiryId}】已收到 \`${item.answeredBy}\` 不中断原路回复:\n- 【问】${item.question}\n- 【答】${cleanAns}`,
|
|
1450
|
+
actions: [`问询已回执 #${item.inquiryId}`],
|
|
1451
|
+
at: now,
|
|
1452
|
+
})
|
|
1453
|
+
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
1454
|
+
pushAuditToWs(ws, {
|
|
1455
|
+
mode: resolveWorkspaceConfig(state, rootId).permissionMode,
|
|
1456
|
+
stage: 'inquiry_channel',
|
|
1457
|
+
rule: 'inquiry_reply',
|
|
1458
|
+
decision: 'answered',
|
|
1459
|
+
operation: '优先问询原路回复',
|
|
1460
|
+
target: item.inquiryId,
|
|
1461
|
+
reason: clamp(cleanAns, 140),
|
|
1462
|
+
outcome: 'ok',
|
|
1463
|
+
by: item.answeredBy,
|
|
1464
|
+
}, rootId)
|
|
1465
|
+
return { ok: true, inquiry: item }
|
|
1466
|
+
})
|
|
1467
|
+
}
|
|
1468
|
+
|
|
1011
1469
|
const STATE_LOCK_WAIT_MS = 10000
|
|
1012
1470
|
|
|
1013
1471
|
const STATE_LOCK_STALE_MS = 15000
|
|
@@ -1094,13 +1552,34 @@ let cachedState = null
|
|
|
1094
1552
|
|
|
1095
1553
|
let cachedMtime = 0
|
|
1096
1554
|
|
|
1555
|
+
function applyColdLoadLedgerRecovery(state) {
|
|
1556
|
+
if (!state || !state.workspaces || typeof state.workspaces !== 'object') return false
|
|
1557
|
+
let changed = false
|
|
1558
|
+
const now = Date.now()
|
|
1559
|
+
for (const ws of Object.values(state.workspaces)) {
|
|
1560
|
+
if (!ws || !Array.isArray(ws.taskLedger) || ws.taskLedger.length === 0) continue
|
|
1561
|
+
const beforeStatuses = ws.taskLedger.map(t => t && t.status)
|
|
1562
|
+
const recovered = recoverTaskLedgerEntriesOnDiskLoad(ws.taskLedger, now)
|
|
1563
|
+
ws.taskLedger = recovered
|
|
1564
|
+
ws.resumeTasks = recovered
|
|
1565
|
+
for (let i = 0; i < recovered.length; i += 1) {
|
|
1566
|
+
if (recovered[i] && recovered[i].status !== beforeStatuses[i]) {
|
|
1567
|
+
changed = true
|
|
1568
|
+
}
|
|
1569
|
+
}
|
|
1570
|
+
}
|
|
1571
|
+
return changed
|
|
1572
|
+
}
|
|
1573
|
+
|
|
1097
1574
|
export function loadChiefState({ forceDisk = false } = {}) {
|
|
1098
1575
|
const file = stateFilePath()
|
|
1099
1576
|
try {
|
|
1100
1577
|
const stat = fs.statSync(file)
|
|
1101
1578
|
if (!forceDisk && cachedState && stat.mtimeMs === cachedMtime) return cachedState
|
|
1102
1579
|
const parsed = JSON.parse(fs.readFileSync(file, 'utf8'))
|
|
1103
|
-
|
|
1580
|
+
const nextState = normalizeState(parsed)
|
|
1581
|
+
applyColdLoadLedgerRecovery(nextState)
|
|
1582
|
+
cachedState = nextState
|
|
1104
1583
|
cachedMtime = stat.mtimeMs
|
|
1105
1584
|
return cachedState
|
|
1106
1585
|
} catch {
|
|
@@ -1114,6 +1593,10 @@ export function loadChiefState({ forceDisk = false } = {}) {
|
|
|
1114
1593
|
}
|
|
1115
1594
|
}
|
|
1116
1595
|
|
|
1596
|
+
export function reconcileChiefStateOnBoot() {
|
|
1597
|
+
return mutateChiefState((state) => applyColdLoadLedgerRecovery(state))
|
|
1598
|
+
}
|
|
1599
|
+
|
|
1117
1600
|
export function saveChiefState(state) {
|
|
1118
1601
|
const normalized = normalizeState(state)
|
|
1119
1602
|
const file = stateFilePath()
|
|
@@ -1405,14 +1888,18 @@ export function deployChiefWorkspaceState(deps, {
|
|
|
1405
1888
|
})
|
|
1406
1889
|
if (toWs.chat.length > CHAT_CAP) toWs.chat = toWs.chat.slice(-CHAT_CAP)
|
|
1407
1890
|
|
|
1408
|
-
// Clone safe workspace chief config (model,
|
|
1891
|
+
// Clone safe workspace chief config (model, effort, tactical preferences), ALWAYS forcing intervention=false, runMode='off' & L0 advisor!
|
|
1409
1892
|
const fromCfg = resolveWorkspaceConfig(state, fromKey)
|
|
1410
1893
|
toWs.config = {
|
|
1411
1894
|
modelRef: fromCfg.modelRef || '',
|
|
1412
|
-
paceMode:
|
|
1895
|
+
paceMode: 'manual',
|
|
1896
|
+
runMode: 'off',
|
|
1897
|
+
thinkingEffort: fromCfg.thinkingEffort || 'auto',
|
|
1898
|
+
teamEffortMode: fromCfg.teamEffortMode || 'auto',
|
|
1899
|
+
managedIdleTimeoutMs: fromCfg.managedIdleTimeoutMs || DEFAULT_MANAGED_IDLE_TIMEOUT_MS,
|
|
1413
1900
|
permissionMode: DEFAULT_CHIEF_PERMISSION_MODE,
|
|
1414
|
-
autoPilot:
|
|
1415
|
-
autoReview:
|
|
1901
|
+
autoPilot: false,
|
|
1902
|
+
autoReview: false,
|
|
1416
1903
|
tacticalModes: {
|
|
1417
1904
|
...normalizeTacticalModes(fromCfg.tacticalModes),
|
|
1418
1905
|
intervention: false,
|
|
@@ -1499,6 +1986,85 @@ export function updateChiefConfig(patch) {
|
|
|
1499
1986
|
}
|
|
1500
1987
|
}
|
|
1501
1988
|
|
|
1989
|
+
// Hard gate on model thinking effort lock mutations (human UI / explicit byUser only)
|
|
1990
|
+
const callerBy = typeof safePatch.by === 'string' ? safePatch.by.trim() : ''
|
|
1991
|
+
const isHumanBy = !callerBy || /^(?:user|human|operator|ui_panel)$/i.test(callerBy)
|
|
1992
|
+
const isHumanLockCaller = safePatch._fromUiPanel === true
|
|
1993
|
+
|| (safePatch.byUser === true && isHumanBy)
|
|
1994
|
+
const wantsLockMutation = safePatch.lockedModelEfforts !== undefined
|
|
1995
|
+
|| safePatch.toggleLockAgentEffort !== undefined
|
|
1996
|
+
|| safePatch.teamEffortMode !== undefined
|
|
1997
|
+
if (wantsLockMutation && !isHumanLockCaller) {
|
|
1998
|
+
pushAuditToWs(ws, {
|
|
1999
|
+
mode: effBefore.permissionMode,
|
|
2000
|
+
stage: 'model_effort_lock',
|
|
2001
|
+
rule: 'effort_lock_human_only',
|
|
2002
|
+
decision: 'blocked',
|
|
2003
|
+
operation: '修改模型思考强度锁挡',
|
|
2004
|
+
target: sid,
|
|
2005
|
+
reason: `未授权来源 (${callerBy || 'unknown'}) 试图修改 lockedModelEfforts,仅允许人类面板显式操作`,
|
|
2006
|
+
outcome: 'rejected',
|
|
2007
|
+
by: clamp(callerBy || 'unknown', 40),
|
|
2008
|
+
}, sid)
|
|
2009
|
+
return {
|
|
2010
|
+
ok: false,
|
|
2011
|
+
blocked: true,
|
|
2012
|
+
lockedByUser: true,
|
|
2013
|
+
code: 'effort_lock_human_only',
|
|
2014
|
+
error: '思考强度锁挡 (lockedModelEfforts) 仅允许人类通过面板或显式 byUser 授权修改,已拦截越权变更',
|
|
2015
|
+
}
|
|
2016
|
+
}
|
|
2017
|
+
if (
|
|
2018
|
+
typeof safePatch.thinkingEffort === 'string'
|
|
2019
|
+
&& effBefore.lockedModelEfforts
|
|
2020
|
+
&& effBefore.lockedModelEfforts.chief === true
|
|
2021
|
+
&& !isHumanLockCaller
|
|
2022
|
+
) {
|
|
2023
|
+
pushAuditToWs(ws, {
|
|
2024
|
+
mode: effBefore.permissionMode,
|
|
2025
|
+
stage: 'model_effort_lock',
|
|
2026
|
+
rule: 'effort_lock_human_only',
|
|
2027
|
+
decision: 'blocked',
|
|
2028
|
+
operation: '修改参谋长思考强度',
|
|
2029
|
+
target: sid,
|
|
2030
|
+
reason: `参谋长思考强度已被用户锁定 (lockedModelEfforts.chief),拒绝非人类来源 (${callerBy || 'unknown'}) 修改`,
|
|
2031
|
+
outcome: 'rejected',
|
|
2032
|
+
by: clamp(callerBy || 'unknown', 40),
|
|
2033
|
+
}, sid)
|
|
2034
|
+
return {
|
|
2035
|
+
ok: false,
|
|
2036
|
+
blocked: true,
|
|
2037
|
+
lockedByUser: true,
|
|
2038
|
+
code: 'effort_lock_human_only',
|
|
2039
|
+
error: '参谋长思考强度已被用户锁定 (lockedModelEfforts.chief),仅允许人类显式修改',
|
|
2040
|
+
}
|
|
2041
|
+
}
|
|
2042
|
+
|
|
2043
|
+
// Check explicit Policy Plugin list (restrict-only) BEFORE applying any changes
|
|
2044
|
+
let validatedPlugins = null
|
|
2045
|
+
if (safePatch.policyPlugins !== undefined) {
|
|
2046
|
+
const plugCheck = validatePolicyPluginList(safePatch.policyPlugins)
|
|
2047
|
+
if (!plugCheck.ok) {
|
|
2048
|
+
pushAuditToWs(ws, {
|
|
2049
|
+
mode: effBefore.permissionMode,
|
|
2050
|
+
stage: 'policy_plugin',
|
|
2051
|
+
rule: plugCheck.code || 'policy_plugin_rejected',
|
|
2052
|
+
decision: 'rejected',
|
|
2053
|
+
operation: '配置只紧不松策略插件',
|
|
2054
|
+
target: sid,
|
|
2055
|
+
reason: plugCheck.error,
|
|
2056
|
+
outcome: 'rejected',
|
|
2057
|
+
by: clamp(safePatch.by || 'operator', 40),
|
|
2058
|
+
}, sid)
|
|
2059
|
+
return {
|
|
2060
|
+
ok: false,
|
|
2061
|
+
code: plugCheck.code || 'POLICY_PLUGIN_WEAKENING_FORBIDDEN',
|
|
2062
|
+
error: plugCheck.error,
|
|
2063
|
+
}
|
|
2064
|
+
}
|
|
2065
|
+
validatedPlugins = plugCheck.plugins
|
|
2066
|
+
}
|
|
2067
|
+
|
|
1502
2068
|
// Check explicit permission mode transition BEFORE applying any changes
|
|
1503
2069
|
let normalizedReqPerm = ''
|
|
1504
2070
|
if (typeof safePatch.permissionMode === 'string' && safePatch.permissionMode.trim()) {
|
|
@@ -1555,18 +2121,22 @@ export function updateChiefConfig(patch) {
|
|
|
1555
2121
|
}
|
|
1556
2122
|
|
|
1557
2123
|
const wantsAutoPilot = Boolean(
|
|
1558
|
-
safePatch.
|
|
1559
|
-
||
|
|
2124
|
+
safePatch.runMode === 'managed'
|
|
2125
|
+
|| safePatch.paceMode === 'auto'
|
|
2126
|
+
|| (typeof safePatch.paceMode !== 'string' && typeof safePatch.runMode !== 'string' && safePatch.stopped !== true && safePatch.autoPilot === true)
|
|
1560
2127
|
)
|
|
1561
|
-
if (wantsAutoPilot && effBefore.paceMode !== 'auto' && safePatch.confirmedAutoPilot !== true) {
|
|
2128
|
+
if (wantsAutoPilot && effBefore.runMode !== 'managed' && effBefore.paceMode !== 'auto' && safePatch.confirmedAutoPilot !== true) {
|
|
1562
2129
|
return {
|
|
1563
2130
|
ok: false,
|
|
1564
2131
|
requireAutoPilotConfirm: true,
|
|
1565
|
-
error: '
|
|
2132
|
+
error: '开启「🤖 托管模式」需先确认本会话自治范围与 5 条件自动休眠保护(confirmedAutoPilot: true)',
|
|
1566
2133
|
}
|
|
1567
2134
|
}
|
|
1568
|
-
if (ws && wantsAutoPilot && effBefore.paceMode !== 'auto') {
|
|
1569
|
-
|
|
2135
|
+
if (ws && wantsAutoPilot && (effBefore.runMode !== 'managed' || effBefore.paceMode !== 'auto')) {
|
|
2136
|
+
const now = Date.now()
|
|
2137
|
+
ws.runtimeGuard.autoPilotStartedAt = now
|
|
2138
|
+
ws.runtimeGuard.managedStartedAt = now
|
|
2139
|
+
ws.runtimeGuard.lastActivityAt = now
|
|
1570
2140
|
ws.runtimeGuard.autoPilotHadTurn = false
|
|
1571
2141
|
}
|
|
1572
2142
|
|
|
@@ -1588,46 +2158,91 @@ export function updateChiefConfig(patch) {
|
|
|
1588
2158
|
}
|
|
1589
2159
|
}
|
|
1590
2160
|
|
|
1591
|
-
const applyPatchTo = (targetCfg, allowIntervention, allowAutoPilot = allowIntervention, allowPermSync = false) => {
|
|
2161
|
+
const applyPatchTo = (targetCfg, allowIntervention, allowAutoPilot = allowIntervention, allowPermSync = false, allowLocks = false) => {
|
|
1592
2162
|
if (typeof safePatch.modelRef === 'string') targetCfg.modelRef = safePatch.modelRef.trim()
|
|
2163
|
+
if (typeof safePatch.thinkingEffort === 'string') {
|
|
2164
|
+
targetCfg.thinkingEffort = normalizeThinkingEffort(safePatch.thinkingEffort)
|
|
2165
|
+
}
|
|
2166
|
+
if (allowLocks && typeof safePatch.teamEffortMode === 'string') {
|
|
2167
|
+
targetCfg.teamEffortMode = normalizeTeamEffortMode(safePatch.teamEffortMode)
|
|
2168
|
+
}
|
|
2169
|
+
if (Number.isFinite(Number(safePatch.managedIdleTimeoutMs)) && Number(safePatch.managedIdleTimeoutMs) >= 50) {
|
|
2170
|
+
targetCfg.managedIdleTimeoutMs = Math.min(2 * 60 * 60 * 1000, Math.round(Number(safePatch.managedIdleTimeoutMs)))
|
|
2171
|
+
}
|
|
2172
|
+
if (allowLocks && (
|
|
2173
|
+
(safePatch.lockedModelEfforts && typeof safePatch.lockedModelEfforts === 'object')
|
|
2174
|
+
|| (safePatch.toggleLockAgentEffort && typeof safePatch.toggleLockAgentEffort === 'object')
|
|
2175
|
+
)) {
|
|
2176
|
+
const curLocks = { ...(targetCfg.lockedModelEfforts || {}) }
|
|
2177
|
+
if (safePatch.lockedModelEfforts && typeof safePatch.lockedModelEfforts === 'object') {
|
|
2178
|
+
for (const [lk, lv] of Object.entries(safePatch.lockedModelEfforts)) {
|
|
2179
|
+
const ck = String(lk || '').trim().slice(0, 64)
|
|
2180
|
+
if (!ck) continue
|
|
2181
|
+
if (lv === true) curLocks[ck] = true
|
|
2182
|
+
else delete curLocks[ck]
|
|
2183
|
+
}
|
|
2184
|
+
}
|
|
2185
|
+
if (safePatch.toggleLockAgentEffort && typeof safePatch.toggleLockAgentEffort === 'object') {
|
|
2186
|
+
const lk = String(safePatch.toggleLockAgentEffort.target || 'lead').trim().slice(0, 64)
|
|
2187
|
+
if (lk) {
|
|
2188
|
+
if (safePatch.toggleLockAgentEffort.locked === true) curLocks[lk] = true
|
|
2189
|
+
else delete curLocks[lk]
|
|
2190
|
+
}
|
|
2191
|
+
}
|
|
2192
|
+
targetCfg.lockedModelEfforts = curLocks
|
|
2193
|
+
}
|
|
1593
2194
|
if (allowPermSync && normalizedReqPerm) {
|
|
1594
2195
|
targetCfg.permissionMode = normalizedReqPerm
|
|
1595
2196
|
}
|
|
1596
|
-
if (typeof safePatch.
|
|
2197
|
+
if (typeof safePatch.runMode === 'string' && CHIEF_RUN_MODES.includes(safePatch.runMode)) {
|
|
2198
|
+
const nextRun = (!allowAutoPilot && safePatch.runMode === 'managed') ? 'off' : safePatch.runMode
|
|
2199
|
+
targetCfg.runMode = nextRun
|
|
2200
|
+
targetCfg.stopped = false
|
|
2201
|
+
targetCfg.paceMode = nextRun === 'managed' ? 'auto' : (nextRun === 'patrol' ? 'smart' : 'manual')
|
|
2202
|
+
targetCfg.autoPilot = nextRun === 'managed' && allowAutoPilot
|
|
2203
|
+
targetCfg.autoReview = nextRun === 'managed' && allowAutoPilot
|
|
2204
|
+
} else if (typeof safePatch.paceMode === 'string' && ['manual', 'smart', 'auto', 'stopped'].includes(safePatch.paceMode)) {
|
|
1597
2205
|
const nextPace = (!allowAutoPilot && safePatch.paceMode === 'auto') ? 'manual' : safePatch.paceMode
|
|
1598
2206
|
targetCfg.paceMode = nextPace
|
|
1599
2207
|
const isStopped = nextPace === 'stopped'
|
|
1600
2208
|
targetCfg.stopped = isStopped
|
|
2209
|
+
targetCfg.runMode = isStopped ? 'off' : (nextPace === 'auto' ? 'managed' : (nextPace === 'smart' ? 'patrol' : 'off'))
|
|
1601
2210
|
targetCfg.autoPilot = !isStopped && nextPace === 'auto' && allowAutoPilot
|
|
1602
|
-
targetCfg.autoReview = !isStopped && nextPace
|
|
2211
|
+
targetCfg.autoReview = !isStopped && nextPace === 'auto' && allowAutoPilot
|
|
1603
2212
|
} else if (typeof safePatch.stopped === 'boolean') {
|
|
1604
2213
|
targetCfg.stopped = safePatch.stopped
|
|
1605
2214
|
if (safePatch.stopped) {
|
|
1606
2215
|
targetCfg.paceMode = 'stopped'
|
|
2216
|
+
targetCfg.runMode = 'off'
|
|
1607
2217
|
targetCfg.autoPilot = false
|
|
1608
2218
|
targetCfg.autoReview = false
|
|
1609
2219
|
} else {
|
|
1610
2220
|
if (targetCfg.paceMode === 'stopped') targetCfg.paceMode = 'manual'
|
|
1611
2221
|
if (!allowAutoPilot && targetCfg.paceMode === 'auto') targetCfg.paceMode = 'manual'
|
|
2222
|
+
targetCfg.runMode = normalizeRunMode(targetCfg.runMode, targetCfg)
|
|
1612
2223
|
targetCfg.autoPilot = targetCfg.paceMode === 'auto' && allowAutoPilot
|
|
1613
|
-
targetCfg.autoReview = targetCfg.paceMode
|
|
2224
|
+
targetCfg.autoReview = targetCfg.paceMode === 'auto' && allowAutoPilot
|
|
1614
2225
|
}
|
|
1615
2226
|
} else if (typeof safePatch.autoPilot === 'boolean') {
|
|
1616
2227
|
const nextAuto = Boolean(safePatch.autoPilot && allowAutoPilot)
|
|
1617
2228
|
targetCfg.stopped = false
|
|
1618
2229
|
targetCfg.paceMode = nextAuto ? 'auto' : 'manual'
|
|
2230
|
+
targetCfg.runMode = nextAuto ? 'managed' : 'off'
|
|
1619
2231
|
targetCfg.autoPilot = nextAuto
|
|
1620
2232
|
targetCfg.autoReview = nextAuto
|
|
1621
2233
|
}
|
|
1622
|
-
if (!allowAutoPilot && targetCfg.paceMode === 'auto') {
|
|
2234
|
+
if (!allowAutoPilot && (targetCfg.paceMode === 'auto' || targetCfg.runMode === 'managed')) {
|
|
1623
2235
|
targetCfg.paceMode = 'manual'
|
|
2236
|
+
targetCfg.runMode = 'off'
|
|
1624
2237
|
targetCfg.autoPilot = false
|
|
2238
|
+
targetCfg.autoReview = false
|
|
1625
2239
|
}
|
|
1626
|
-
if (typeof safePatch.autoReview === 'boolean' && typeof safePatch.paceMode !== 'string' && typeof safePatch.stopped !== 'boolean') {
|
|
2240
|
+
if (typeof safePatch.autoReview === 'boolean' && typeof safePatch.paceMode !== 'string' && typeof safePatch.runMode !== 'string' && typeof safePatch.stopped !== 'boolean') {
|
|
1627
2241
|
targetCfg.autoReview = safePatch.autoReview
|
|
1628
2242
|
if (!safePatch.autoReview) {
|
|
1629
2243
|
targetCfg.stopped = false
|
|
1630
2244
|
targetCfg.paceMode = 'manual'
|
|
2245
|
+
targetCfg.runMode = 'off'
|
|
1631
2246
|
}
|
|
1632
2247
|
}
|
|
1633
2248
|
if (incomingTactical) {
|
|
@@ -1642,11 +2257,41 @@ export function updateChiefConfig(patch) {
|
|
|
1642
2257
|
}
|
|
1643
2258
|
}
|
|
1644
2259
|
|
|
1645
|
-
if (!ws.config || typeof ws.config !== 'object')
|
|
1646
|
-
|
|
1647
|
-
|
|
2260
|
+
if (!ws.config || typeof ws.config !== 'object') {
|
|
2261
|
+
ws.config = {
|
|
2262
|
+
modelRef: effBefore.modelRef || '',
|
|
2263
|
+
paceMode: effBefore.paceMode || 'manual',
|
|
2264
|
+
runMode: effBefore.runMode || 'off',
|
|
2265
|
+
thinkingEffort: effBefore.thinkingEffort || 'auto',
|
|
2266
|
+
teamEffortMode: effBefore.teamEffortMode || 'auto',
|
|
2267
|
+
managedIdleTimeoutMs: effBefore.managedIdleTimeoutMs || DEFAULT_MANAGED_IDLE_TIMEOUT_MS,
|
|
2268
|
+
lockedModelEfforts: { ...(effBefore.lockedModelEfforts || {}) },
|
|
2269
|
+
permissionMode: effBefore.permissionMode || DEFAULT_CHIEF_PERMISSION_MODE,
|
|
2270
|
+
tacticalModes: { ...effBefore.tacticalModes },
|
|
2271
|
+
}
|
|
2272
|
+
}
|
|
2273
|
+
applyPatchTo(ws.config, true, true, true, isHumanLockCaller)
|
|
2274
|
+
if (validatedPlugins !== null) {
|
|
2275
|
+
if (safePatch.policyPluginsScope === 'global') {
|
|
2276
|
+
state.config.policyPlugins = validatedPlugins
|
|
2277
|
+
} else {
|
|
2278
|
+
ws.config.policyPlugins = validatedPlugins
|
|
2279
|
+
}
|
|
2280
|
+
pushAuditToWs(ws, {
|
|
2281
|
+
mode: resolveWorkspaceConfig(state, sid).permissionMode,
|
|
2282
|
+
stage: 'policy_plugin',
|
|
2283
|
+
rule: 'policy_plugin_updated',
|
|
2284
|
+
decision: 'executed',
|
|
2285
|
+
operation: '更新安全策略插件',
|
|
2286
|
+
target: `${safePatch.policyPluginsScope === 'global' ? 'global' : sid} (${validatedPlugins.length} 个)`,
|
|
2287
|
+
reason: `已加载 ${validatedPlugins.length} 个只紧不松安全策略插件`,
|
|
2288
|
+
outcome: 'ok',
|
|
2289
|
+
by: clamp(safePatch.by || 'operator', 40),
|
|
2290
|
+
}, sid)
|
|
2291
|
+
}
|
|
2292
|
+
// Session permissionMode, intervention, lockedModelEfforts, and autoPilot NEVER leak globally across new sessions!
|
|
1648
2293
|
state.config.permissionMode = DEFAULT_CHIEF_PERMISSION_MODE
|
|
1649
|
-
applyPatchTo(state.config, false, false, false)
|
|
2294
|
+
applyPatchTo(state.config, false, false, false, false)
|
|
1650
2295
|
|
|
1651
2296
|
if (normalizedReqPerm) {
|
|
1652
2297
|
if (normalizedReqPerm === 'chief' && safePatch.confirmedChiefRisk === true) {
|
|
@@ -1757,21 +2402,122 @@ export function isInternalCheckpointNoise(text) {
|
|
|
1757
2402
|
return false
|
|
1758
2403
|
}
|
|
1759
2404
|
|
|
2405
|
+
function repairJsonInvalidEscapes(jsonStr) {
|
|
2406
|
+
let out = ''
|
|
2407
|
+
let inString = false
|
|
2408
|
+
for (let i = 0; i < jsonStr.length; i += 1) {
|
|
2409
|
+
const ch = jsonStr[i]
|
|
2410
|
+
if (!inString) {
|
|
2411
|
+
if (ch === '"') inString = true
|
|
2412
|
+
out += ch
|
|
2413
|
+
continue
|
|
2414
|
+
}
|
|
2415
|
+
if (ch === '"') {
|
|
2416
|
+
inString = false
|
|
2417
|
+
out += ch
|
|
2418
|
+
continue
|
|
2419
|
+
}
|
|
2420
|
+
if (ch === '\\') {
|
|
2421
|
+
const next = jsonStr[i + 1]
|
|
2422
|
+
if (next === undefined) {
|
|
2423
|
+
out += '\\\\'
|
|
2424
|
+
continue
|
|
2425
|
+
}
|
|
2426
|
+
if (next === 'u' && /^[0-9a-fA-F]{4}$/.test(jsonStr.slice(i + 2, i + 6))) {
|
|
2427
|
+
out += jsonStr.slice(i, i + 6)
|
|
2428
|
+
i += 5
|
|
2429
|
+
continue
|
|
2430
|
+
}
|
|
2431
|
+
if ('"\\/bfnrt'.includes(next)) {
|
|
2432
|
+
out += '\\' + next
|
|
2433
|
+
i += 1
|
|
2434
|
+
continue
|
|
2435
|
+
}
|
|
2436
|
+
// Escape invalid bare backslash (e.g. regex \s, \., Windows D:\path) inside JSON strings
|
|
2437
|
+
out += '\\\\'
|
|
2438
|
+
continue
|
|
2439
|
+
}
|
|
2440
|
+
out += ch
|
|
2441
|
+
}
|
|
2442
|
+
return out
|
|
2443
|
+
}
|
|
2444
|
+
|
|
2445
|
+
function tryParseJsonRobust(candidate) {
|
|
2446
|
+
if (!candidate) return null
|
|
2447
|
+
try {
|
|
2448
|
+
const parsed = JSON.parse(candidate)
|
|
2449
|
+
if (parsed && typeof parsed === 'object') return parsed
|
|
2450
|
+
} catch {}
|
|
2451
|
+
try {
|
|
2452
|
+
const repaired = repairJsonInvalidEscapes(candidate)
|
|
2453
|
+
const parsed = JSON.parse(repaired)
|
|
2454
|
+
if (parsed && typeof parsed === 'object') return parsed
|
|
2455
|
+
} catch {}
|
|
2456
|
+
return null
|
|
2457
|
+
}
|
|
2458
|
+
|
|
1760
2459
|
export function extractJsonObject(raw) {
|
|
1761
2460
|
const text = String(raw || '').trim()
|
|
1762
2461
|
if (!text) return null
|
|
1763
2462
|
const stripped = text.replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/i, '').trim()
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
if (direct && typeof direct === 'object') return direct
|
|
1767
|
-
} catch {}
|
|
2463
|
+
const direct = tryParseJsonRobust(stripped)
|
|
2464
|
+
if (direct) return direct
|
|
1768
2465
|
const first = text.indexOf('{')
|
|
1769
2466
|
const last = text.lastIndexOf('}')
|
|
1770
2467
|
if (first !== -1 && last > first) {
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
if (sliced && typeof sliced === 'object') return sliced
|
|
1774
|
-
} catch {}
|
|
2468
|
+
const sliced = tryParseJsonRobust(text.slice(first, last + 1))
|
|
2469
|
+
if (sliced) return sliced
|
|
1775
2470
|
}
|
|
1776
2471
|
return null
|
|
1777
2472
|
}
|
|
2473
|
+
|
|
2474
|
+
const activeChiefWorkMap = new Map()
|
|
2475
|
+
const ACTIVE_CHIEF_WORK_TTL_MS = 90_000
|
|
2476
|
+
|
|
2477
|
+
export function beginChiefActiveWork(rootSessionId, spec = {}) {
|
|
2478
|
+
const key = String(rootSessionId || 'global').trim() || 'global'
|
|
2479
|
+
const id = 'cwork-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 6)
|
|
2480
|
+
activeChiefWorkMap.set(key, {
|
|
2481
|
+
id,
|
|
2482
|
+
tone: String(spec.tone || 'neon'),
|
|
2483
|
+
tab: String(spec.tab || ''),
|
|
2484
|
+
boundSubTab: String(spec.boundSubTab || ''),
|
|
2485
|
+
label: String(spec.label || '参谋长正在自动维护中...'),
|
|
2486
|
+
startedAt: Date.now(),
|
|
2487
|
+
})
|
|
2488
|
+
return id
|
|
2489
|
+
}
|
|
2490
|
+
|
|
2491
|
+
export function updateChiefActiveWork(rootSessionId, workId, patchSpec = {}) {
|
|
2492
|
+
const key = String(rootSessionId || 'global').trim() || 'global'
|
|
2493
|
+
const cur = activeChiefWorkMap.get(key)
|
|
2494
|
+
if (!cur || (workId && cur.id !== workId)) return false
|
|
2495
|
+
activeChiefWorkMap.set(key, {
|
|
2496
|
+
...cur,
|
|
2497
|
+
...(patchSpec.tone ? { tone: String(patchSpec.tone) } : {}),
|
|
2498
|
+
...(patchSpec.tab !== undefined ? { tab: String(patchSpec.tab || '') } : {}),
|
|
2499
|
+
...(patchSpec.boundSubTab !== undefined ? { boundSubTab: String(patchSpec.boundSubTab || '') } : {}),
|
|
2500
|
+
...(patchSpec.label ? { label: String(patchSpec.label) } : {}),
|
|
2501
|
+
})
|
|
2502
|
+
return true
|
|
2503
|
+
}
|
|
2504
|
+
|
|
2505
|
+
export function endChiefActiveWork(rootSessionId, workId = '') {
|
|
2506
|
+
const key = String(rootSessionId || 'global').trim() || 'global'
|
|
2507
|
+
const cur = activeChiefWorkMap.get(key)
|
|
2508
|
+
if (!cur) return false
|
|
2509
|
+
if (workId && cur.id !== workId) return false
|
|
2510
|
+
activeChiefWorkMap.delete(key)
|
|
2511
|
+
return true
|
|
2512
|
+
}
|
|
2513
|
+
|
|
2514
|
+
export function getChiefActiveWork(rootSessionId) {
|
|
2515
|
+
const key = String(rootSessionId || 'global').trim() || 'global'
|
|
2516
|
+
const cur = activeChiefWorkMap.get(key)
|
|
2517
|
+
if (!cur) return null
|
|
2518
|
+
if (Date.now() - Number(cur.startedAt || 0) > ACTIVE_CHIEF_WORK_TTL_MS) {
|
|
2519
|
+
activeChiefWorkMap.delete(key)
|
|
2520
|
+
return null
|
|
2521
|
+
}
|
|
2522
|
+
return { ...cur }
|
|
2523
|
+
}
|