dsh-chief 1.3.0 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +42 -12
- package/README.en.md +143 -116
- package/README.md +134 -142
- package/api-routes.js +19 -2
- package/board-actions.js +72 -1
- package/board-schema.js +1 -1
- package/chief-approvals.js +241 -81
- package/chief-archives.js +35 -0
- package/chief-commands.js +615 -108
- package/chief-executor.js +279 -555
- package/chief-network.js +157 -8
- package/chief-review.js +33 -1
- package/chief-state.js +497 -81
- package/chief-view.js +21 -6
- package/client.js +1953 -506
- package/model-tools.js +78 -2
- package/package.json +35 -24
- package/runtime-hooks.js +108 -2
- 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 +9 -2
package/chief-state.js
CHANGED
|
@@ -22,7 +22,13 @@ import {
|
|
|
22
22
|
CHIEF_PERMISSION_META,
|
|
23
23
|
normalizePermissionMode,
|
|
24
24
|
permissionRank,
|
|
25
|
-
|
|
25
|
+
auditJsonlPath as safetyAuditJsonlPath,
|
|
26
|
+
normalizeAuditRecord,
|
|
27
|
+
appendAuditJsonlRecord,
|
|
28
|
+
resolveRoleCapabilities,
|
|
29
|
+
buildCapabilityScope,
|
|
30
|
+
validatePolicyPluginList,
|
|
31
|
+
} from './safety/index.js'
|
|
26
32
|
|
|
27
33
|
const APPROVALS_CAP = 30
|
|
28
34
|
|
|
@@ -30,10 +36,24 @@ const AUDIT_LOG_CAP = 80
|
|
|
30
36
|
|
|
31
37
|
const RESUME_TASKS_CAP = 20
|
|
32
38
|
|
|
39
|
+
const TASK_LEDGER_CAP = 30
|
|
40
|
+
|
|
33
41
|
const DEFAULT_RESUME_TTL_MS = 30 * 60 * 1000
|
|
34
42
|
|
|
35
43
|
const STATE_VERSION = 1
|
|
36
44
|
|
|
45
|
+
const activeResumingTaskIds = new Set()
|
|
46
|
+
|
|
47
|
+
export function markTaskResumingActive(taskId) {
|
|
48
|
+
const id = String(taskId || '').trim()
|
|
49
|
+
if (id) activeResumingTaskIds.add(id)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function unmarkTaskResumingActive(taskId) {
|
|
53
|
+
const id = String(taskId || '').trim()
|
|
54
|
+
if (id) activeResumingTaskIds.delete(id)
|
|
55
|
+
}
|
|
56
|
+
|
|
37
57
|
export const FACTS_CAP = 120
|
|
38
58
|
|
|
39
59
|
export const FACT_TEXT_MAX = 260
|
|
@@ -66,6 +86,12 @@ export const CHIEF_UPDATE_SOURCE = 'dsh-chief-update'
|
|
|
66
86
|
|
|
67
87
|
export const CHIEF_RELAY_SOURCE = 'dsh-chief-relay'
|
|
68
88
|
|
|
89
|
+
export const CHIEF_INQUIRY_SOURCE = 'dsh-chief-inquiry'
|
|
90
|
+
|
|
91
|
+
export const CHIEF_EXEC_REQ_SOURCE = 'dsh-chief-execution-request'
|
|
92
|
+
|
|
93
|
+
export const CHAT_OPPORTUNISTIC_SUMMARY_COOLDOWN_MS = 60_000
|
|
94
|
+
|
|
69
95
|
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
96
|
|
|
71
97
|
let dshAttachmentModulePromise = null
|
|
@@ -309,15 +335,7 @@ function stateFilePath() {
|
|
|
309
335
|
}
|
|
310
336
|
|
|
311
337
|
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 {}
|
|
338
|
+
return safetyAuditJsonlPath()
|
|
321
339
|
}
|
|
322
340
|
|
|
323
341
|
function canonicalSortJsonValue(val) {
|
|
@@ -362,7 +380,7 @@ function normalizePendingApproval(raw) {
|
|
|
362
380
|
if (!raw || typeof raw !== 'object') return null
|
|
363
381
|
const opLabel = clamp(raw.operationLabel || raw.operation || '', 80)
|
|
364
382
|
if (!opLabel) return null
|
|
365
|
-
const validStatuses = ['pending', 'approved', 'rejected', 'executed', 'failed']
|
|
383
|
+
const validStatuses = ['pending', 'approved', 'rejected', 'executed', 'failed', 'expired']
|
|
366
384
|
const status = validStatuses.includes(raw.status) ? raw.status : 'pending'
|
|
367
385
|
const validKinds = ['tool', 'relay', 'compact', 'auto_continue']
|
|
368
386
|
const kind = validKinds.includes(raw.kind) ? raw.kind : 'tool'
|
|
@@ -372,6 +390,16 @@ function normalizePendingApproval(raw) {
|
|
|
372
390
|
const payloadHash = typeof raw.payloadHash === 'string' && raw.payloadHash.trim()
|
|
373
391
|
? raw.payloadHash.trim()
|
|
374
392
|
: computeApprovalPayloadHash(kind, payload)
|
|
393
|
+
const taskId = clamp(raw.taskId || raw.resumeTaskId || '', 80)
|
|
394
|
+
const capabilityScope = raw.capabilityScope && typeof raw.capabilityScope === 'object'
|
|
395
|
+
? raw.capabilityScope
|
|
396
|
+
: buildCapabilityScope({
|
|
397
|
+
kind,
|
|
398
|
+
tool: payload.tool || kind,
|
|
399
|
+
args: payload.args || {},
|
|
400
|
+
cwd: payload.cwd || '',
|
|
401
|
+
target: payload.target || '',
|
|
402
|
+
})
|
|
375
403
|
return {
|
|
376
404
|
id: typeof raw.id === 'string' && raw.id ? raw.id : nextId('apr'),
|
|
377
405
|
status,
|
|
@@ -384,7 +412,9 @@ function normalizePendingApproval(raw) {
|
|
|
384
412
|
kind,
|
|
385
413
|
payload,
|
|
386
414
|
payloadHash,
|
|
387
|
-
|
|
415
|
+
capabilityScope,
|
|
416
|
+
taskId,
|
|
417
|
+
resumeTaskId: taskId,
|
|
388
418
|
expiresAt: Math.max(0, Number(raw.expiresAt) || 0),
|
|
389
419
|
dedupeKey: clamp(raw.dedupeKey || '', 120),
|
|
390
420
|
by: clamp(raw.by || 'chief', 40),
|
|
@@ -401,6 +431,7 @@ function normalizePendingElevation(raw) {
|
|
|
401
431
|
const targetMode = normalizePermissionMode(raw.targetMode)
|
|
402
432
|
if (targetMode === 'advisor') return null
|
|
403
433
|
const createdAt = Number(raw.createdAt) || Date.now()
|
|
434
|
+
const taskId = clamp(raw.taskId || raw.resumeTaskId || '', 80)
|
|
404
435
|
return {
|
|
405
436
|
id: typeof raw.id === 'string' && raw.id ? raw.id : nextId('elv'),
|
|
406
437
|
status: 'pending',
|
|
@@ -408,65 +439,137 @@ function normalizePendingElevation(raw) {
|
|
|
408
439
|
targetMode,
|
|
409
440
|
reason: clamp(raw.reason || '当前任务需要更高参谋权限才能继续执行', 260),
|
|
410
441
|
requestedActionSummary: clamp(raw.requestedActionSummary || '', 220),
|
|
411
|
-
|
|
442
|
+
requestedCapabilities: Array.isArray(raw.requestedCapabilities)
|
|
443
|
+
? raw.requestedCapabilities.map(c => clamp(c, 60)).filter(Boolean).slice(0, 12)
|
|
444
|
+
: [],
|
|
445
|
+
taskId,
|
|
446
|
+
resumeTaskId: taskId,
|
|
412
447
|
expiresAt: Math.max(0, Number(raw.expiresAt) || (createdAt + DEFAULT_RESUME_TTL_MS)),
|
|
413
448
|
by: clamp(raw.by || 'chief', 40),
|
|
414
449
|
createdAt,
|
|
415
450
|
}
|
|
416
451
|
}
|
|
417
452
|
|
|
418
|
-
|
|
453
|
+
const VALID_TASK_LEDGER_STATUSES = [
|
|
454
|
+
'proposed',
|
|
455
|
+
'awaiting_elevation',
|
|
456
|
+
'awaiting_approval',
|
|
457
|
+
'awaiting_inquiry',
|
|
458
|
+
'dispatched',
|
|
459
|
+
'running',
|
|
460
|
+
'resuming',
|
|
461
|
+
'verifying',
|
|
462
|
+
'completed',
|
|
463
|
+
'interrupted',
|
|
464
|
+
'rejected',
|
|
465
|
+
'cancelled',
|
|
466
|
+
'expired',
|
|
467
|
+
'failed',
|
|
468
|
+
]
|
|
469
|
+
|
|
470
|
+
function normalizeTaskLedgerEntry(raw) {
|
|
419
471
|
if (!raw || typeof raw !== 'object') return null
|
|
420
|
-
const
|
|
472
|
+
const spec = raw.resumeSpec && typeof raw.resumeSpec === 'object' ? raw.resumeSpec : {}
|
|
473
|
+
const originalText = cleanMultiline(spec.originalText || raw.originalText || '', 2000)
|
|
421
474
|
if (!originalText) return null
|
|
422
|
-
const
|
|
423
|
-
const status = validStatuses.includes(raw.status) ? raw.status : 'awaiting_approval'
|
|
475
|
+
const status = VALID_TASK_LEDGER_STATUSES.includes(raw.status) ? raw.status : 'awaiting_approval'
|
|
424
476
|
const createdAt = Number(raw.createdAt) || Date.now()
|
|
477
|
+
const updatedAt = Number(raw.updatedAt) || createdAt
|
|
478
|
+
const taskId = typeof (raw.taskId || raw.id) === 'string' && (raw.taskId || raw.id)
|
|
479
|
+
? String(raw.taskId || raw.id)
|
|
480
|
+
: nextId('rtask')
|
|
481
|
+
const validKinds = ['approval_resume', 'elevation_resume', 'tool_execution', 'inquiry', 'auto_continue']
|
|
482
|
+
const kind = validKinds.includes(raw.kind)
|
|
483
|
+
? raw.kind
|
|
484
|
+
: (raw.elevationId || status === 'awaiting_elevation' ? 'elevation_resume' : 'approval_resume')
|
|
485
|
+
const forcedTarget = clamp(spec.forcedTarget !== undefined ? spec.forcedTarget : (raw.forcedTarget || ''), 64)
|
|
486
|
+
const forcedModeRaw = spec.forcedMode !== undefined ? spec.forcedMode : raw.forcedMode
|
|
487
|
+
const forcedMode = ['steer', 'followup', 'silent'].includes(forcedModeRaw) ? forcedModeRaw : 'steer'
|
|
488
|
+
const rawImages = Array.isArray(spec.savedImagePaths) ? spec.savedImagePaths : raw.savedImagePaths
|
|
489
|
+
const savedImagePaths = Array.isArray(rawImages)
|
|
490
|
+
? rawImages.slice(0, 4).filter(p => p && typeof p.path === 'string').map(p => ({
|
|
491
|
+
index: Number(p.index) || 1,
|
|
492
|
+
path: String(p.path),
|
|
493
|
+
name: clamp(p.name || '', 80),
|
|
494
|
+
mediaType: clamp(p.mediaType || '', 40),
|
|
495
|
+
bytes: Math.max(0, Number(p.bytes) || 0),
|
|
496
|
+
}))
|
|
497
|
+
: []
|
|
498
|
+
const rawCompleted = Array.isArray(spec.completedActions) ? spec.completedActions : raw.completedActions
|
|
499
|
+
const completedActions = Array.isArray(rawCompleted)
|
|
500
|
+
? rawCompleted.map(x => clamp(x, 220)).filter(Boolean).slice(-12)
|
|
501
|
+
: []
|
|
502
|
+
const retryCount = Math.max(0, Math.min(4, Math.round(Number(raw.retryCount !== undefined ? raw.retryCount : raw.resumeDepth) || 0)))
|
|
503
|
+
const capabilityScope = raw.capabilityScope && typeof raw.capabilityScope === 'object' ? raw.capabilityScope : null
|
|
504
|
+
const payloadHash = typeof raw.payloadHash === 'string' ? raw.payloadHash.trim() : ''
|
|
425
505
|
return {
|
|
426
|
-
id:
|
|
506
|
+
id: taskId,
|
|
507
|
+
taskId,
|
|
508
|
+
kind,
|
|
427
509
|
status,
|
|
510
|
+
capabilityScope,
|
|
511
|
+
payloadHash,
|
|
512
|
+
resumeSpec: {
|
|
513
|
+
originalText,
|
|
514
|
+
forcedTarget,
|
|
515
|
+
forcedMode,
|
|
516
|
+
savedImagePaths,
|
|
517
|
+
completedActions,
|
|
518
|
+
},
|
|
428
519
|
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
|
-
: [],
|
|
520
|
+
forcedTarget,
|
|
521
|
+
forcedMode,
|
|
522
|
+
savedImagePaths,
|
|
523
|
+
completedActions,
|
|
443
524
|
pendingApprovalIds: Array.isArray(raw.pendingApprovalIds)
|
|
444
525
|
? [...new Set(raw.pendingApprovalIds.map(x => String(x || '').trim()).filter(Boolean))].slice(0, 12)
|
|
445
526
|
: [],
|
|
446
527
|
elevationId: clamp(raw.elevationId || '', 80),
|
|
447
|
-
|
|
528
|
+
inquiryId: clamp(raw.inquiryId || '', 80),
|
|
529
|
+
lastReceipt: cleanMultiline(raw.lastReceipt || '', 300),
|
|
530
|
+
retryCount,
|
|
531
|
+
resumeDepth: retryCount,
|
|
448
532
|
createdAt,
|
|
533
|
+
updatedAt,
|
|
449
534
|
expiresAt: Math.max(0, Number(raw.expiresAt) || (createdAt + DEFAULT_RESUME_TTL_MS)),
|
|
450
535
|
resolvedAt: Math.max(0, Number(raw.resolvedAt) || 0),
|
|
451
536
|
}
|
|
452
537
|
}
|
|
453
538
|
|
|
539
|
+
export function recoverTaskLedgerEntriesOnDiskLoad(entries, now = Date.now()) {
|
|
540
|
+
if (!Array.isArray(entries)) return []
|
|
541
|
+
return entries.map((entry) => {
|
|
542
|
+
if (!entry || typeof entry !== 'object') return entry
|
|
543
|
+
const tid = entry.taskId || entry.id
|
|
544
|
+
if (
|
|
545
|
+
(entry.status === 'running' || entry.status === 'resuming' || entry.status === 'verifying')
|
|
546
|
+
&& !activeResumingTaskIds.has(tid)
|
|
547
|
+
) {
|
|
548
|
+
return {
|
|
549
|
+
...entry,
|
|
550
|
+
status: 'interrupted',
|
|
551
|
+
updatedAt: now,
|
|
552
|
+
lastReceipt: entry.lastReceipt || '检测到上次运行中断,已安全降级为 interrupted 等待人工确认续跑',
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
if (
|
|
556
|
+
(entry.status === 'proposed' || entry.status === 'awaiting_approval' || entry.status === 'awaiting_elevation' || entry.status === 'awaiting_inquiry')
|
|
557
|
+
&& entry.expiresAt > 0
|
|
558
|
+
&& now > entry.expiresAt
|
|
559
|
+
) {
|
|
560
|
+
return {
|
|
561
|
+
...entry,
|
|
562
|
+
status: 'expired',
|
|
563
|
+
updatedAt: now,
|
|
564
|
+
resolvedAt: entry.resolvedAt || now,
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
return entry
|
|
568
|
+
})
|
|
569
|
+
}
|
|
570
|
+
|
|
454
571
|
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
|
-
}
|
|
572
|
+
return normalizeAuditRecord(raw, DEFAULT_CHIEF_PERMISSION_MODE)
|
|
470
573
|
}
|
|
471
574
|
|
|
472
575
|
export function pushAuditToWs(ws, entry = {}, sessionId = '') {
|
|
@@ -476,24 +579,24 @@ export function pushAuditToWs(ws, entry = {}, sessionId = '') {
|
|
|
476
579
|
if (!norm) return null
|
|
477
580
|
ws.auditLog.push(norm)
|
|
478
581
|
if (ws.auditLog.length > AUDIT_LOG_CAP) ws.auditLog = ws.auditLog.slice(-AUDIT_LOG_CAP)
|
|
479
|
-
|
|
480
|
-
...(sessionId ? { sessionId: String(sessionId) } : {}),
|
|
481
|
-
...norm,
|
|
482
|
-
})
|
|
582
|
+
appendAuditJsonlRecord(norm, sessionId)
|
|
483
583
|
return norm
|
|
484
584
|
}
|
|
485
585
|
|
|
486
586
|
function emptyWorkspace() {
|
|
587
|
+
const sharedLedger = []
|
|
487
588
|
return {
|
|
488
589
|
config: null,
|
|
489
590
|
chiefRiskAck: null,
|
|
490
591
|
pendingApprovals: [],
|
|
491
592
|
pendingElevation: null,
|
|
492
|
-
|
|
593
|
+
taskLedger: sharedLedger,
|
|
594
|
+
resumeTasks: sharedLedger,
|
|
493
595
|
auditLog: [],
|
|
494
596
|
facts: [],
|
|
495
597
|
narrative: { hash: '', text: '', at: 0, byModel: '', clusterSig: '' },
|
|
496
598
|
suggestions: [],
|
|
599
|
+
inquiries: [],
|
|
497
600
|
chat: [],
|
|
498
601
|
mailbox: [],
|
|
499
602
|
seenMailAt: {},
|
|
@@ -545,22 +648,24 @@ export function normalizeSuggestion(raw) {
|
|
|
545
648
|
if (!raw || typeof raw !== 'object') return null
|
|
546
649
|
const title = clamp(raw.title, 90)
|
|
547
650
|
if (!title) return null
|
|
548
|
-
const kind = ['bound', 'board', 'goal_approval', 'relay', 'advice'].includes(raw.kind) ? raw.kind : 'relay'
|
|
651
|
+
const kind = ['bound', 'board', 'goal_approval', 'relay', 'advice', 'guard_wall'].includes(raw.kind) ? raw.kind : 'relay'
|
|
549
652
|
const boundField = ['forbidden', 'allowed', 'notes'].includes(raw.boundField) ? raw.boundField : 'forbidden'
|
|
550
653
|
const replaces = Array.isArray(raw.replaces)
|
|
551
654
|
? raw.replaces.map(x => String(x || '').trim()).filter(Boolean).slice(0, 20)
|
|
552
655
|
: []
|
|
656
|
+
const wallSpec = raw.wallSpec && typeof raw.wallSpec === 'object' ? { ...raw.wallSpec } : null
|
|
553
657
|
return {
|
|
554
658
|
id: typeof raw.id === 'string' && raw.id ? raw.id : nextId('sug'),
|
|
555
659
|
kind,
|
|
556
660
|
boundField,
|
|
557
661
|
replaces,
|
|
558
662
|
pinGlobal: Boolean(raw.pinGlobal),
|
|
663
|
+
...(wallSpec ? { wallSpec } : {}),
|
|
559
664
|
fromAgent: clamp(raw.fromAgent || '', 48),
|
|
560
665
|
title,
|
|
561
666
|
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),
|
|
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),
|
|
564
669
|
mode: ['steer', 'followup', 'silent'].includes(raw.mode) ? raw.mode : (kind === 'advice' ? 'followup' : 'steer'),
|
|
565
670
|
draftText: cleanMultiline(raw.draftText || '', 600),
|
|
566
671
|
evidence: cleanMultiline(raw.evidence || '', 600),
|
|
@@ -573,6 +678,32 @@ export function normalizeSuggestion(raw) {
|
|
|
573
678
|
}
|
|
574
679
|
}
|
|
575
680
|
|
|
681
|
+
export function normalizeInquiryItem(raw) {
|
|
682
|
+
if (!raw || typeof raw !== 'object') return null
|
|
683
|
+
const question = cleanMultiline(raw.question || raw.text || '', 600)
|
|
684
|
+
if (!question) return null
|
|
685
|
+
const status = ['pending', 'delivered', 'answered', 'expired'].includes(raw.status) ? raw.status : 'pending'
|
|
686
|
+
const inquiryId = typeof (raw.inquiryId || raw.id) === 'string' && (raw.inquiryId || raw.id)
|
|
687
|
+
? String(raw.inquiryId || raw.id)
|
|
688
|
+
: nextId('inq')
|
|
689
|
+
return {
|
|
690
|
+
id: inquiryId,
|
|
691
|
+
inquiryId,
|
|
692
|
+
taskId: clamp(raw.taskId || '', 80),
|
|
693
|
+
target: clamp(raw.target || 'lead', 64),
|
|
694
|
+
question,
|
|
695
|
+
context: clamp(raw.context || '', 220),
|
|
696
|
+
answer: cleanMultiline(raw.answer || '', 1200),
|
|
697
|
+
status,
|
|
698
|
+
by: clamp(raw.by || 'chief', 40),
|
|
699
|
+
answeredBy: clamp(raw.answeredBy || '', 40),
|
|
700
|
+
createdAt: Number(raw.createdAt) || Date.now(),
|
|
701
|
+
deliveredAt: Number(raw.deliveredAt) || 0,
|
|
702
|
+
answeredAt: Number(raw.answeredAt) || 0,
|
|
703
|
+
expiresAt: Number(raw.expiresAt) || ((Number(raw.createdAt) || Date.now()) + DEFAULT_RESUME_TTL_MS),
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
|
|
576
707
|
export function normalizeMail(raw) {
|
|
577
708
|
if (!raw || typeof raw !== 'object') return null
|
|
578
709
|
const imageCount = Math.max(0, Math.round(Number(raw.imageCount) || 0))
|
|
@@ -621,6 +752,10 @@ function normalizeWorkspace(raw) {
|
|
|
621
752
|
.map(normalizeSuggestion)
|
|
622
753
|
.filter(Boolean)
|
|
623
754
|
.slice(-SUGGESTIONS_CAP * 2)
|
|
755
|
+
base.inquiries = (Array.isArray(src.inquiries) ? src.inquiries : [])
|
|
756
|
+
.map(normalizeInquiryItem)
|
|
757
|
+
.filter(Boolean)
|
|
758
|
+
.slice(-24)
|
|
624
759
|
base.chat = (Array.isArray(src.chat) ? src.chat : [])
|
|
625
760
|
.filter(item => item && typeof item === 'object' && typeof item.text === 'string')
|
|
626
761
|
.slice(-CHAT_CAP)
|
|
@@ -683,10 +818,15 @@ function normalizeWorkspace(raw) {
|
|
|
683
818
|
.filter(Boolean)
|
|
684
819
|
.slice(-APPROVALS_CAP)
|
|
685
820
|
base.pendingElevation = normalizePendingElevation(src.pendingElevation)
|
|
686
|
-
|
|
687
|
-
.
|
|
821
|
+
const rawLedgerSrc = Array.isArray(src.taskLedger) && src.taskLedger.length > 0
|
|
822
|
+
? src.taskLedger
|
|
823
|
+
: (Array.isArray(src.resumeTasks) ? src.resumeTasks : [])
|
|
824
|
+
const normalizedLedger = rawLedgerSrc
|
|
825
|
+
.map(normalizeTaskLedgerEntry)
|
|
688
826
|
.filter(Boolean)
|
|
689
|
-
.slice(-
|
|
827
|
+
.slice(-TASK_LEDGER_CAP)
|
|
828
|
+
base.taskLedger = normalizedLedger
|
|
829
|
+
base.resumeTasks = normalizedLedger
|
|
690
830
|
base.auditLog = (Array.isArray(src.auditLog) ? src.auditLog : [])
|
|
691
831
|
.map(normalizeAuditEntry)
|
|
692
832
|
.filter(Boolean)
|
|
@@ -699,11 +839,14 @@ function normalizeWorkspace(raw) {
|
|
|
699
839
|
const rawPerm = typeof src.config.permissionMode === 'string'
|
|
700
840
|
? normalizePermissionMode(src.config.permissionMode, { requireAck: true, hasChiefRiskAck: ackOk })
|
|
701
841
|
: DEFAULT_CHIEF_PERMISSION_MODE
|
|
842
|
+
const plugCheck = validatePolicyPluginList(src.config.policyPlugins)
|
|
843
|
+
const policyPlugins = plugCheck.ok ? plugCheck.plugins : []
|
|
702
844
|
base.config = {
|
|
703
845
|
...(typeof src.config.modelRef === 'string' ? { modelRef: src.config.modelRef.trim() } : {}),
|
|
704
846
|
permissionMode: rawPerm,
|
|
705
847
|
...(typeof src.config.stopped === 'boolean' || pm === 'stopped' ? { stopped: rawStopped } : {}),
|
|
706
848
|
...(pm ? { paceMode: pm, autoPilot: !rawStopped && pm === 'auto', autoReview: !rawStopped && pm !== 'manual' } : {}),
|
|
849
|
+
...(policyPlugins.length > 0 ? { policyPlugins } : {}),
|
|
707
850
|
...(src.config.tacticalModes && typeof src.config.tacticalModes === 'object'
|
|
708
851
|
? { tacticalModes: normalizeTacticalModes(src.config.tacticalModes) }
|
|
709
852
|
: {}),
|
|
@@ -800,16 +943,25 @@ export function resolveWorkspaceConfig(state, sessionId = '') {
|
|
|
800
943
|
const rawPerm = (wsCfg && typeof wsCfg.permissionMode === 'string')
|
|
801
944
|
? wsCfg.permissionMode
|
|
802
945
|
: DEFAULT_CHIEF_PERMISSION_MODE
|
|
803
|
-
const
|
|
804
|
-
|
|
946
|
+
const globalPlugCheck = validatePolicyPluginList(base.policyPlugins)
|
|
947
|
+
const wsPlugCheck = validatePolicyPluginList(wsCfg && wsCfg.policyPlugins)
|
|
948
|
+
const policyPlugins = [
|
|
949
|
+
...(globalPlugCheck.ok ? globalPlugCheck.plugins : []),
|
|
950
|
+
...(wsPlugCheck.ok ? wsPlugCheck.plugins : []),
|
|
951
|
+
]
|
|
952
|
+
const resolvedRoleCaps = resolveRoleCapabilities(rawPerm, {
|
|
805
953
|
hasChiefRiskAck: ackOk,
|
|
954
|
+
policyPlugins,
|
|
806
955
|
})
|
|
956
|
+
const permissionMode = resolvedRoleCaps.role
|
|
807
957
|
const chiefRiskVerified = permissionMode === 'chief' ? ackOk : false
|
|
808
958
|
return {
|
|
809
959
|
modelRef,
|
|
810
960
|
paceMode,
|
|
811
961
|
stopped,
|
|
812
962
|
permissionMode,
|
|
963
|
+
capabilities: resolvedRoleCaps.capabilities,
|
|
964
|
+
policyPlugins,
|
|
813
965
|
chiefRiskVerified,
|
|
814
966
|
autoPilot: !stopped && paceMode === 'auto',
|
|
815
967
|
autoReview: !stopped && paceMode !== 'manual',
|
|
@@ -883,6 +1035,7 @@ function normalizeState(raw) {
|
|
|
883
1035
|
const rawPace = validPaces.includes(cfg.paceMode) ? cfg.paceMode : 'manual'
|
|
884
1036
|
const stopped = rawPace === 'stopped' || Boolean(cfg.stopped)
|
|
885
1037
|
const paceMode = stopped ? 'stopped' : rawPace
|
|
1038
|
+
const globalPlugRes = validatePolicyPluginList(cfg.policyPlugins)
|
|
886
1039
|
return {
|
|
887
1040
|
version: STATE_VERSION,
|
|
888
1041
|
config: {
|
|
@@ -892,6 +1045,7 @@ function normalizeState(raw) {
|
|
|
892
1045
|
permissionMode: DEFAULT_CHIEF_PERMISSION_MODE,
|
|
893
1046
|
autoPilot: !stopped && paceMode === 'auto',
|
|
894
1047
|
autoReview: !stopped && paceMode !== 'manual',
|
|
1048
|
+
...(globalPlugRes.ok && globalPlugRes.plugins.length > 0 ? { policyPlugins: globalPlugRes.plugins } : {}),
|
|
895
1049
|
tacticalModes: normalizeTacticalModes(cfg.tacticalModes),
|
|
896
1050
|
},
|
|
897
1051
|
links,
|
|
@@ -982,32 +1136,118 @@ export function requestChiefElevation(sessionId = 'global', req = {}) {
|
|
|
982
1136
|
})
|
|
983
1137
|
}
|
|
984
1138
|
|
|
985
|
-
export function
|
|
1139
|
+
export function upsertTaskLedgerOnWs(ws, rawTask = {}) {
|
|
986
1140
|
if (!ws || typeof ws !== 'object') return null
|
|
987
|
-
if (!Array.isArray(ws.
|
|
988
|
-
|
|
1141
|
+
if (!Array.isArray(ws.taskLedger)) {
|
|
1142
|
+
ws.taskLedger = Array.isArray(ws.resumeTasks) ? ws.resumeTasks : []
|
|
1143
|
+
}
|
|
1144
|
+
ws.resumeTasks = ws.taskLedger
|
|
1145
|
+
const lookupId = rawTask.taskId || rawTask.id
|
|
1146
|
+
const existingIdx = lookupId ? ws.taskLedger.findIndex(t => t && (t.taskId === lookupId || t.id === lookupId)) : -1
|
|
989
1147
|
if (existingIdx >= 0) {
|
|
990
|
-
const prev = ws.
|
|
991
|
-
const merged =
|
|
1148
|
+
const prev = ws.taskLedger[existingIdx]
|
|
1149
|
+
const merged = normalizeTaskLedgerEntry({
|
|
992
1150
|
...prev,
|
|
993
1151
|
...rawTask,
|
|
1152
|
+
updatedAt: Date.now(),
|
|
994
1153
|
completedActions: rawTask.appendCompletedAction
|
|
995
1154
|
? [...(prev.completedActions || []), rawTask.appendCompletedAction]
|
|
996
1155
|
: (rawTask.completedActions || prev.completedActions),
|
|
997
1156
|
pendingApprovalIds: rawTask.pendingApprovalIds || prev.pendingApprovalIds,
|
|
998
1157
|
})
|
|
999
|
-
if (merged) ws.
|
|
1158
|
+
if (merged) ws.taskLedger[existingIdx] = merged
|
|
1000
1159
|
return merged
|
|
1001
1160
|
}
|
|
1002
|
-
const created =
|
|
1161
|
+
const created = normalizeTaskLedgerEntry(rawTask)
|
|
1003
1162
|
if (!created) return null
|
|
1004
|
-
ws.
|
|
1005
|
-
if (ws.
|
|
1006
|
-
ws.
|
|
1163
|
+
ws.taskLedger.push(created)
|
|
1164
|
+
if (ws.taskLedger.length > TASK_LEDGER_CAP) {
|
|
1165
|
+
ws.taskLedger = ws.taskLedger.slice(-TASK_LEDGER_CAP)
|
|
1166
|
+
ws.resumeTasks = ws.taskLedger
|
|
1007
1167
|
}
|
|
1008
1168
|
return created
|
|
1009
1169
|
}
|
|
1010
1170
|
|
|
1171
|
+
export function upsertResumeTaskOnWs(ws, rawTask = {}) {
|
|
1172
|
+
return upsertTaskLedgerOnWs(ws, rawTask)
|
|
1173
|
+
}
|
|
1174
|
+
|
|
1175
|
+
export function enqueueChiefInquiryOnWs(ws, raw = {}) {
|
|
1176
|
+
if (!ws || typeof ws !== 'object') return null
|
|
1177
|
+
if (!Array.isArray(ws.inquiries)) ws.inquiries = []
|
|
1178
|
+
const norm = normalizeInquiryItem(raw)
|
|
1179
|
+
if (!norm) return null
|
|
1180
|
+
const dup = ws.inquiries.find(
|
|
1181
|
+
q => q && (q.status === 'pending' || q.status === 'delivered') && q.question === norm.question && q.target === norm.target,
|
|
1182
|
+
)
|
|
1183
|
+
if (dup) return dup
|
|
1184
|
+
ws.inquiries.push(norm)
|
|
1185
|
+
if (ws.inquiries.length > 24) ws.inquiries = ws.inquiries.slice(-24)
|
|
1186
|
+
return norm
|
|
1187
|
+
}
|
|
1188
|
+
|
|
1189
|
+
export function answerChiefInquiry(sessionId = 'global', { inquiryId = '', answer = '', by = 'lead' } = {}) {
|
|
1190
|
+
const rootId = String(sessionId || 'global').trim() || 'global'
|
|
1191
|
+
const cleanAns = cleanMultiline(answer || '', 1200)
|
|
1192
|
+
if (!cleanAns) return { ok: false, error: 'inquiry.reply 需要非空答复文本 (text)' }
|
|
1193
|
+
return mutateChiefState((state) => {
|
|
1194
|
+
const ws = ensureWorkspace(state, rootId)
|
|
1195
|
+
if (!Array.isArray(ws.inquiries)) ws.inquiries = []
|
|
1196
|
+
let idx = inquiryId
|
|
1197
|
+
? ws.inquiries.findIndex(q => q && (q.inquiryId === inquiryId || q.id === inquiryId))
|
|
1198
|
+
: -1
|
|
1199
|
+
if (idx < 0 && !inquiryId) {
|
|
1200
|
+
for (let i = ws.inquiries.length - 1; i >= 0; i -= 1) {
|
|
1201
|
+
if (ws.inquiries[i] && (ws.inquiries[i].status === 'pending' || ws.inquiries[i].status === 'delivered')) {
|
|
1202
|
+
idx = i
|
|
1203
|
+
break
|
|
1204
|
+
}
|
|
1205
|
+
}
|
|
1206
|
+
}
|
|
1207
|
+
if (idx < 0) return { ok: false, error: `未找到待回复问询:${inquiryId || '最近未答问询'}` }
|
|
1208
|
+
const now = Date.now()
|
|
1209
|
+
const item = {
|
|
1210
|
+
...ws.inquiries[idx],
|
|
1211
|
+
status: 'answered',
|
|
1212
|
+
answer: cleanAns,
|
|
1213
|
+
answeredBy: clamp(by || 'lead', 40),
|
|
1214
|
+
answeredAt: now,
|
|
1215
|
+
}
|
|
1216
|
+
ws.inquiries[idx] = item
|
|
1217
|
+
if (item.taskId) {
|
|
1218
|
+
upsertTaskLedgerOnWs(ws, {
|
|
1219
|
+
taskId: item.taskId,
|
|
1220
|
+
kind: 'inquiry',
|
|
1221
|
+
status: 'completed',
|
|
1222
|
+
inquiryId: item.inquiryId,
|
|
1223
|
+
lastReceipt: `已收到 ${item.answeredBy} 原路答复:${clamp(cleanAns, 120)}`,
|
|
1224
|
+
resolvedAt: now,
|
|
1225
|
+
})
|
|
1226
|
+
}
|
|
1227
|
+
ws.chat.push({
|
|
1228
|
+
id: nextId('chat'),
|
|
1229
|
+
role: 'chief',
|
|
1230
|
+
kind: 'receipt',
|
|
1231
|
+
text: `- 【⚡ 优先问询回执 #${item.inquiryId}】已收到 \`${item.answeredBy}\` 不中断原路回复:\n- 【问】${item.question}\n- 【答】${cleanAns}`,
|
|
1232
|
+
actions: [`问询已回执 #${item.inquiryId}`],
|
|
1233
|
+
at: now,
|
|
1234
|
+
})
|
|
1235
|
+
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
1236
|
+
pushAuditToWs(ws, {
|
|
1237
|
+
mode: resolveWorkspaceConfig(state, rootId).permissionMode,
|
|
1238
|
+
stage: 'inquiry_channel',
|
|
1239
|
+
rule: 'inquiry_reply',
|
|
1240
|
+
decision: 'answered',
|
|
1241
|
+
operation: '优先问询原路回复',
|
|
1242
|
+
target: item.inquiryId,
|
|
1243
|
+
reason: clamp(cleanAns, 140),
|
|
1244
|
+
outcome: 'ok',
|
|
1245
|
+
by: item.answeredBy,
|
|
1246
|
+
}, rootId)
|
|
1247
|
+
return { ok: true, inquiry: item }
|
|
1248
|
+
})
|
|
1249
|
+
}
|
|
1250
|
+
|
|
1011
1251
|
const STATE_LOCK_WAIT_MS = 10000
|
|
1012
1252
|
|
|
1013
1253
|
const STATE_LOCK_STALE_MS = 15000
|
|
@@ -1094,13 +1334,34 @@ let cachedState = null
|
|
|
1094
1334
|
|
|
1095
1335
|
let cachedMtime = 0
|
|
1096
1336
|
|
|
1337
|
+
function applyColdLoadLedgerRecovery(state) {
|
|
1338
|
+
if (!state || !state.workspaces || typeof state.workspaces !== 'object') return false
|
|
1339
|
+
let changed = false
|
|
1340
|
+
const now = Date.now()
|
|
1341
|
+
for (const ws of Object.values(state.workspaces)) {
|
|
1342
|
+
if (!ws || !Array.isArray(ws.taskLedger) || ws.taskLedger.length === 0) continue
|
|
1343
|
+
const beforeStatuses = ws.taskLedger.map(t => t && t.status)
|
|
1344
|
+
const recovered = recoverTaskLedgerEntriesOnDiskLoad(ws.taskLedger, now)
|
|
1345
|
+
ws.taskLedger = recovered
|
|
1346
|
+
ws.resumeTasks = recovered
|
|
1347
|
+
for (let i = 0; i < recovered.length; i += 1) {
|
|
1348
|
+
if (recovered[i] && recovered[i].status !== beforeStatuses[i]) {
|
|
1349
|
+
changed = true
|
|
1350
|
+
}
|
|
1351
|
+
}
|
|
1352
|
+
}
|
|
1353
|
+
return changed
|
|
1354
|
+
}
|
|
1355
|
+
|
|
1097
1356
|
export function loadChiefState({ forceDisk = false } = {}) {
|
|
1098
1357
|
const file = stateFilePath()
|
|
1099
1358
|
try {
|
|
1100
1359
|
const stat = fs.statSync(file)
|
|
1101
1360
|
if (!forceDisk && cachedState && stat.mtimeMs === cachedMtime) return cachedState
|
|
1102
1361
|
const parsed = JSON.parse(fs.readFileSync(file, 'utf8'))
|
|
1103
|
-
|
|
1362
|
+
const nextState = normalizeState(parsed)
|
|
1363
|
+
applyColdLoadLedgerRecovery(nextState)
|
|
1364
|
+
cachedState = nextState
|
|
1104
1365
|
cachedMtime = stat.mtimeMs
|
|
1105
1366
|
return cachedState
|
|
1106
1367
|
} catch {
|
|
@@ -1114,6 +1375,10 @@ export function loadChiefState({ forceDisk = false } = {}) {
|
|
|
1114
1375
|
}
|
|
1115
1376
|
}
|
|
1116
1377
|
|
|
1378
|
+
export function reconcileChiefStateOnBoot() {
|
|
1379
|
+
return mutateChiefState((state) => applyColdLoadLedgerRecovery(state))
|
|
1380
|
+
}
|
|
1381
|
+
|
|
1117
1382
|
export function saveChiefState(state) {
|
|
1118
1383
|
const normalized = normalizeState(state)
|
|
1119
1384
|
const file = stateFilePath()
|
|
@@ -1499,6 +1764,31 @@ export function updateChiefConfig(patch) {
|
|
|
1499
1764
|
}
|
|
1500
1765
|
}
|
|
1501
1766
|
|
|
1767
|
+
// Check explicit Policy Plugin list (restrict-only) BEFORE applying any changes
|
|
1768
|
+
let validatedPlugins = null
|
|
1769
|
+
if (safePatch.policyPlugins !== undefined) {
|
|
1770
|
+
const plugCheck = validatePolicyPluginList(safePatch.policyPlugins)
|
|
1771
|
+
if (!plugCheck.ok) {
|
|
1772
|
+
pushAuditToWs(ws, {
|
|
1773
|
+
mode: effBefore.permissionMode,
|
|
1774
|
+
stage: 'policy_plugin',
|
|
1775
|
+
rule: plugCheck.code || 'policy_plugin_rejected',
|
|
1776
|
+
decision: 'rejected',
|
|
1777
|
+
operation: '配置只紧不松策略插件',
|
|
1778
|
+
target: sid,
|
|
1779
|
+
reason: plugCheck.error,
|
|
1780
|
+
outcome: 'rejected',
|
|
1781
|
+
by: clamp(safePatch.by || 'operator', 40),
|
|
1782
|
+
}, sid)
|
|
1783
|
+
return {
|
|
1784
|
+
ok: false,
|
|
1785
|
+
code: plugCheck.code || 'POLICY_PLUGIN_WEAKENING_FORBIDDEN',
|
|
1786
|
+
error: plugCheck.error,
|
|
1787
|
+
}
|
|
1788
|
+
}
|
|
1789
|
+
validatedPlugins = plugCheck.plugins
|
|
1790
|
+
}
|
|
1791
|
+
|
|
1502
1792
|
// Check explicit permission mode transition BEFORE applying any changes
|
|
1503
1793
|
let normalizedReqPerm = ''
|
|
1504
1794
|
if (typeof safePatch.permissionMode === 'string' && safePatch.permissionMode.trim()) {
|
|
@@ -1642,8 +1932,33 @@ export function updateChiefConfig(patch) {
|
|
|
1642
1932
|
}
|
|
1643
1933
|
}
|
|
1644
1934
|
|
|
1645
|
-
if (!ws.config || typeof ws.config !== 'object')
|
|
1935
|
+
if (!ws.config || typeof ws.config !== 'object') {
|
|
1936
|
+
ws.config = {
|
|
1937
|
+
modelRef: effBefore.modelRef || '',
|
|
1938
|
+
paceMode: effBefore.paceMode || 'manual',
|
|
1939
|
+
permissionMode: effBefore.permissionMode || DEFAULT_CHIEF_PERMISSION_MODE,
|
|
1940
|
+
tacticalModes: { ...effBefore.tacticalModes },
|
|
1941
|
+
}
|
|
1942
|
+
}
|
|
1646
1943
|
applyPatchTo(ws.config, true, true, true)
|
|
1944
|
+
if (validatedPlugins !== null) {
|
|
1945
|
+
if (safePatch.policyPluginsScope === 'global') {
|
|
1946
|
+
state.config.policyPlugins = validatedPlugins
|
|
1947
|
+
} else {
|
|
1948
|
+
ws.config.policyPlugins = validatedPlugins
|
|
1949
|
+
}
|
|
1950
|
+
pushAuditToWs(ws, {
|
|
1951
|
+
mode: resolveWorkspaceConfig(state, sid).permissionMode,
|
|
1952
|
+
stage: 'policy_plugin',
|
|
1953
|
+
rule: 'policy_plugin_updated',
|
|
1954
|
+
decision: 'executed',
|
|
1955
|
+
operation: '更新安全策略插件',
|
|
1956
|
+
target: `${safePatch.policyPluginsScope === 'global' ? 'global' : sid} (${validatedPlugins.length} 个)`,
|
|
1957
|
+
reason: `已加载 ${validatedPlugins.length} 个只紧不松安全策略插件`,
|
|
1958
|
+
outcome: 'ok',
|
|
1959
|
+
by: clamp(safePatch.by || 'operator', 40),
|
|
1960
|
+
}, sid)
|
|
1961
|
+
}
|
|
1647
1962
|
// Session permissionMode, intervention, and autoPilot NEVER leak globally across new sessions!
|
|
1648
1963
|
state.config.permissionMode = DEFAULT_CHIEF_PERMISSION_MODE
|
|
1649
1964
|
applyPatchTo(state.config, false, false, false)
|
|
@@ -1757,21 +2072,122 @@ export function isInternalCheckpointNoise(text) {
|
|
|
1757
2072
|
return false
|
|
1758
2073
|
}
|
|
1759
2074
|
|
|
2075
|
+
function repairJsonInvalidEscapes(jsonStr) {
|
|
2076
|
+
let out = ''
|
|
2077
|
+
let inString = false
|
|
2078
|
+
for (let i = 0; i < jsonStr.length; i += 1) {
|
|
2079
|
+
const ch = jsonStr[i]
|
|
2080
|
+
if (!inString) {
|
|
2081
|
+
if (ch === '"') inString = true
|
|
2082
|
+
out += ch
|
|
2083
|
+
continue
|
|
2084
|
+
}
|
|
2085
|
+
if (ch === '"') {
|
|
2086
|
+
inString = false
|
|
2087
|
+
out += ch
|
|
2088
|
+
continue
|
|
2089
|
+
}
|
|
2090
|
+
if (ch === '\\') {
|
|
2091
|
+
const next = jsonStr[i + 1]
|
|
2092
|
+
if (next === undefined) {
|
|
2093
|
+
out += '\\\\'
|
|
2094
|
+
continue
|
|
2095
|
+
}
|
|
2096
|
+
if (next === 'u' && /^[0-9a-fA-F]{4}$/.test(jsonStr.slice(i + 2, i + 6))) {
|
|
2097
|
+
out += jsonStr.slice(i, i + 6)
|
|
2098
|
+
i += 5
|
|
2099
|
+
continue
|
|
2100
|
+
}
|
|
2101
|
+
if ('"\\/bfnrt'.includes(next)) {
|
|
2102
|
+
out += '\\' + next
|
|
2103
|
+
i += 1
|
|
2104
|
+
continue
|
|
2105
|
+
}
|
|
2106
|
+
// Escape invalid bare backslash (e.g. regex \s, \., Windows D:\path) inside JSON strings
|
|
2107
|
+
out += '\\\\'
|
|
2108
|
+
continue
|
|
2109
|
+
}
|
|
2110
|
+
out += ch
|
|
2111
|
+
}
|
|
2112
|
+
return out
|
|
2113
|
+
}
|
|
2114
|
+
|
|
2115
|
+
function tryParseJsonRobust(candidate) {
|
|
2116
|
+
if (!candidate) return null
|
|
2117
|
+
try {
|
|
2118
|
+
const parsed = JSON.parse(candidate)
|
|
2119
|
+
if (parsed && typeof parsed === 'object') return parsed
|
|
2120
|
+
} catch {}
|
|
2121
|
+
try {
|
|
2122
|
+
const repaired = repairJsonInvalidEscapes(candidate)
|
|
2123
|
+
const parsed = JSON.parse(repaired)
|
|
2124
|
+
if (parsed && typeof parsed === 'object') return parsed
|
|
2125
|
+
} catch {}
|
|
2126
|
+
return null
|
|
2127
|
+
}
|
|
2128
|
+
|
|
1760
2129
|
export function extractJsonObject(raw) {
|
|
1761
2130
|
const text = String(raw || '').trim()
|
|
1762
2131
|
if (!text) return null
|
|
1763
2132
|
const stripped = text.replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/i, '').trim()
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
if (direct && typeof direct === 'object') return direct
|
|
1767
|
-
} catch {}
|
|
2133
|
+
const direct = tryParseJsonRobust(stripped)
|
|
2134
|
+
if (direct) return direct
|
|
1768
2135
|
const first = text.indexOf('{')
|
|
1769
2136
|
const last = text.lastIndexOf('}')
|
|
1770
2137
|
if (first !== -1 && last > first) {
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
if (sliced && typeof sliced === 'object') return sliced
|
|
1774
|
-
} catch {}
|
|
2138
|
+
const sliced = tryParseJsonRobust(text.slice(first, last + 1))
|
|
2139
|
+
if (sliced) return sliced
|
|
1775
2140
|
}
|
|
1776
2141
|
return null
|
|
1777
2142
|
}
|
|
2143
|
+
|
|
2144
|
+
const activeChiefWorkMap = new Map()
|
|
2145
|
+
const ACTIVE_CHIEF_WORK_TTL_MS = 90_000
|
|
2146
|
+
|
|
2147
|
+
export function beginChiefActiveWork(rootSessionId, spec = {}) {
|
|
2148
|
+
const key = String(rootSessionId || 'global').trim() || 'global'
|
|
2149
|
+
const id = 'cwork-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 6)
|
|
2150
|
+
activeChiefWorkMap.set(key, {
|
|
2151
|
+
id,
|
|
2152
|
+
tone: String(spec.tone || 'neon'),
|
|
2153
|
+
tab: String(spec.tab || ''),
|
|
2154
|
+
boundSubTab: String(spec.boundSubTab || ''),
|
|
2155
|
+
label: String(spec.label || '参谋长正在自动维护中...'),
|
|
2156
|
+
startedAt: Date.now(),
|
|
2157
|
+
})
|
|
2158
|
+
return id
|
|
2159
|
+
}
|
|
2160
|
+
|
|
2161
|
+
export function updateChiefActiveWork(rootSessionId, workId, patchSpec = {}) {
|
|
2162
|
+
const key = String(rootSessionId || 'global').trim() || 'global'
|
|
2163
|
+
const cur = activeChiefWorkMap.get(key)
|
|
2164
|
+
if (!cur || (workId && cur.id !== workId)) return false
|
|
2165
|
+
activeChiefWorkMap.set(key, {
|
|
2166
|
+
...cur,
|
|
2167
|
+
...(patchSpec.tone ? { tone: String(patchSpec.tone) } : {}),
|
|
2168
|
+
...(patchSpec.tab !== undefined ? { tab: String(patchSpec.tab || '') } : {}),
|
|
2169
|
+
...(patchSpec.boundSubTab !== undefined ? { boundSubTab: String(patchSpec.boundSubTab || '') } : {}),
|
|
2170
|
+
...(patchSpec.label ? { label: String(patchSpec.label) } : {}),
|
|
2171
|
+
})
|
|
2172
|
+
return true
|
|
2173
|
+
}
|
|
2174
|
+
|
|
2175
|
+
export function endChiefActiveWork(rootSessionId, workId = '') {
|
|
2176
|
+
const key = String(rootSessionId || 'global').trim() || 'global'
|
|
2177
|
+
const cur = activeChiefWorkMap.get(key)
|
|
2178
|
+
if (!cur) return false
|
|
2179
|
+
if (workId && cur.id !== workId) return false
|
|
2180
|
+
activeChiefWorkMap.delete(key)
|
|
2181
|
+
return true
|
|
2182
|
+
}
|
|
2183
|
+
|
|
2184
|
+
export function getChiefActiveWork(rootSessionId) {
|
|
2185
|
+
const key = String(rootSessionId || 'global').trim() || 'global'
|
|
2186
|
+
const cur = activeChiefWorkMap.get(key)
|
|
2187
|
+
if (!cur) return null
|
|
2188
|
+
if (Date.now() - Number(cur.startedAt || 0) > ACTIVE_CHIEF_WORK_TTL_MS) {
|
|
2189
|
+
activeChiefWorkMap.delete(key)
|
|
2190
|
+
return null
|
|
2191
|
+
}
|
|
2192
|
+
return { ...cur }
|
|
2193
|
+
}
|