dsh-chief 1.6.0 → 1.7.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 +31 -0
- package/README.en.md +277 -123
- package/README.md +283 -129
- package/api-routes.js +193 -2
- package/board-actions.js +1452 -2060
- package/board-handoff.js +709 -0
- package/board-schema.js +35 -2
- package/chief-approvals.js +6 -2
- package/chief-commands.js +1884 -3486
- package/chief-executor.js +6 -1
- package/chief-network.js +1098 -869
- package/chief-review.js +193 -3
- package/chief-state.js +1996 -3078
- package/chief-view.js +7 -4
- package/client.js +12237 -8021
- package/command-helpers.js +568 -0
- package/command-ops.js +1226 -0
- package/digest.js +25 -3
- package/index.js +6 -0
- package/locale/en.json +4 -4
- package/locale/zh.json +4 -4
- package/model-tools.js +40 -2
- package/network-harness.js +1047 -0
- package/package.json +8 -2
- package/runtime-hooks.js +69 -2
- package/safety/guard-walls.js +5 -0
- package/safety/invariant-guards.js +125 -6
- package/safety/tool-gate.js +2 -0
- package/state-media.js +173 -0
- package/state-schema.js +1505 -0
- package/subagent-runtime.js +57 -3
package/state-schema.js
ADDED
|
@@ -0,0 +1,1505 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* state-schema.js — 参谋状态常量、纯归一化校验器、紧缩阈值解析、JSON 容错提取与水泡目录
|
|
3
|
+
*
|
|
4
|
+
* 【核心职责】
|
|
5
|
+
* 集中存放 `chief-state.js` 中零磁盘锁依赖的纯数据契约与无副作用助手:
|
|
6
|
+
* 常量配额、LLM 账本统计/归一化、思考深度对齐、Workspace/Fact/Suggestion/Mail/Ledger 归一化、
|
|
7
|
+
* 上下文紧缩阈值解析(`COMPACT_*`)、容错 JSON 提取(`extractJsonObject`)、活跃工作追踪及官方外部 Harness 目录。
|
|
8
|
+
*
|
|
9
|
+
* 【边界与无环约定】
|
|
10
|
+
* - 只单向依赖 `node:path`、`node:crypto` 与 `./safety/index.js`;
|
|
11
|
+
* - 绝不导入 `chief-state.js`、`state-media.js` 或访问文件系统状态锁,严禁出现 `export let`。
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import path from 'node:path'
|
|
15
|
+
import crypto from 'node:crypto'
|
|
16
|
+
import {
|
|
17
|
+
DEFAULT_CHIEF_PERMISSION_MODE,
|
|
18
|
+
normalizePermissionMode,
|
|
19
|
+
normalizeAuditRecord,
|
|
20
|
+
resolveRoleCapabilities,
|
|
21
|
+
buildCapabilityScope,
|
|
22
|
+
validatePolicyPluginList,
|
|
23
|
+
} from './safety/index.js'
|
|
24
|
+
|
|
25
|
+
export const APPROVALS_CAP = 30
|
|
26
|
+
|
|
27
|
+
export const AUDIT_LOG_CAP = 80
|
|
28
|
+
|
|
29
|
+
export const RESUME_TASKS_CAP = 20
|
|
30
|
+
|
|
31
|
+
export const TASK_LEDGER_CAP = 30
|
|
32
|
+
|
|
33
|
+
export const DEFAULT_RESUME_TTL_MS = 30 * 60 * 1000
|
|
34
|
+
|
|
35
|
+
const STATE_VERSION = 1
|
|
36
|
+
|
|
37
|
+
const activeResumingTaskIds = new Set()
|
|
38
|
+
|
|
39
|
+
export function markTaskResumingActive(taskId) {
|
|
40
|
+
const id = String(taskId || '').trim()
|
|
41
|
+
if (id) activeResumingTaskIds.add(id)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function unmarkTaskResumingActive(taskId) {
|
|
45
|
+
const id = String(taskId || '').trim()
|
|
46
|
+
if (id) activeResumingTaskIds.delete(id)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export const FACTS_CAP = 120
|
|
50
|
+
|
|
51
|
+
export const FACT_TEXT_MAX = 260
|
|
52
|
+
|
|
53
|
+
export const CHAT_CAP = 36
|
|
54
|
+
|
|
55
|
+
export const MAIL_CAP = 80
|
|
56
|
+
|
|
57
|
+
export const SUGGESTIONS_CAP = 6
|
|
58
|
+
|
|
59
|
+
export const MODEL_TIMEOUT_MS = 90_000
|
|
60
|
+
|
|
61
|
+
export const CATALOG_TTL_MS = 10_000
|
|
62
|
+
|
|
63
|
+
export const REVIEW_DELAY_MS = 2_800
|
|
64
|
+
|
|
65
|
+
export const AUTO_SUMMARY_COOLDOWN_MS = 5 * 60_000
|
|
66
|
+
|
|
67
|
+
export const SMART_REVIEW_COOLDOWN_MS = 3 * 60_000
|
|
68
|
+
|
|
69
|
+
export const AUTO_REVIEW_COOLDOWN_MS = 90_000
|
|
70
|
+
|
|
71
|
+
// Thinking models spend several thousand output tokens on internal reasoning before emitting text;
|
|
72
|
+
// small caps (e.g. 2k-4k) starve the visible answer to empty string.
|
|
73
|
+
export const SUMMARY_MAX_TOKENS = 16_384
|
|
74
|
+
|
|
75
|
+
export const SUMMARY_RETRY_MAX_TOKENS = 32_768
|
|
76
|
+
|
|
77
|
+
export const CHIEF_UPDATE_SOURCE = 'dsh-chief-update'
|
|
78
|
+
|
|
79
|
+
export const CHIEF_RELAY_SOURCE = 'dsh-chief-relay'
|
|
80
|
+
|
|
81
|
+
export const CHIEF_INQUIRY_SOURCE = 'dsh-chief-inquiry'
|
|
82
|
+
|
|
83
|
+
export const CHIEF_EXEC_REQ_SOURCE = 'dsh-chief-execution-request'
|
|
84
|
+
|
|
85
|
+
export const CHAT_OPPORTUNISTIC_SUMMARY_COOLDOWN_MS = 60_000
|
|
86
|
+
|
|
87
|
+
export const CHIEF_RUN_MODES = ['off', 'patrol', 'managed']
|
|
88
|
+
|
|
89
|
+
export const DEFAULT_MANAGED_IDLE_TIMEOUT_MS = 15 * 60 * 1000
|
|
90
|
+
|
|
91
|
+
export const CHIEF_THINKING_EFFORTS = ['auto', 'off', 'low', 'medium', 'high', 'xhigh']
|
|
92
|
+
|
|
93
|
+
export const ALERT_EVENTS_CAP = 20
|
|
94
|
+
|
|
95
|
+
export const LLM_LEDGER_RECENT_CAP = 20
|
|
96
|
+
|
|
97
|
+
export const DEFAULT_MANAGED_BUDGET_MAX_CALLS = 30
|
|
98
|
+
|
|
99
|
+
export const DEFAULT_MANAGED_BUDGET_MAX_TOKENS = 300_000
|
|
100
|
+
|
|
101
|
+
export const CHIEF_UI_LANGS = ['auto', 'zh', 'en']
|
|
102
|
+
|
|
103
|
+
export const CHIEF_SCENARIO_PRESETS = {
|
|
104
|
+
observer: {
|
|
105
|
+
id: 'observer',
|
|
106
|
+
permissionMode: 'advisor',
|
|
107
|
+
runMode: 'off',
|
|
108
|
+
thinkingEffort: 'low',
|
|
109
|
+
tacticalModes: {
|
|
110
|
+
intervention: false,
|
|
111
|
+
autoCompact: false,
|
|
112
|
+
smartCompact: false,
|
|
113
|
+
redlineSentinel: false,
|
|
114
|
+
},
|
|
115
|
+
notifyEnabled: true,
|
|
116
|
+
},
|
|
117
|
+
collab: {
|
|
118
|
+
id: 'collab',
|
|
119
|
+
permissionMode: 'strategist',
|
|
120
|
+
runMode: 'patrol',
|
|
121
|
+
thinkingEffort: 'auto',
|
|
122
|
+
tacticalModes: {
|
|
123
|
+
intervention: false,
|
|
124
|
+
redlineSentinel: true,
|
|
125
|
+
},
|
|
126
|
+
notifyEnabled: true,
|
|
127
|
+
},
|
|
128
|
+
away: {
|
|
129
|
+
id: 'away',
|
|
130
|
+
permissionMode: 'chief',
|
|
131
|
+
runMode: 'managed',
|
|
132
|
+
thinkingEffort: 'auto',
|
|
133
|
+
tacticalModes: {
|
|
134
|
+
autoCompact: true,
|
|
135
|
+
compactThresholdMode: 'pct',
|
|
136
|
+
compactThresholdPct: 80,
|
|
137
|
+
redlineSentinel: true,
|
|
138
|
+
},
|
|
139
|
+
notifyEnabled: true,
|
|
140
|
+
managedBudgetMaxCalls: DEFAULT_MANAGED_BUDGET_MAX_CALLS,
|
|
141
|
+
managedBudgetMaxTokens: DEFAULT_MANAGED_BUDGET_MAX_TOKENS,
|
|
142
|
+
},
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export function normalizeUiLang(raw) {
|
|
146
|
+
const s = typeof raw === 'string' ? raw.trim().toLowerCase() : ''
|
|
147
|
+
if (s === 'zh' || s === 'zh-cn' || s === 'zh-hans') return 'zh'
|
|
148
|
+
if (s === 'en' || s === 'en-us' || s === 'en-gb') return 'en'
|
|
149
|
+
return 'auto'
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export function normalizeManagedBudgetCalls(raw) {
|
|
153
|
+
if (raw === 0 || raw === '0') return 0
|
|
154
|
+
const n = Number(raw)
|
|
155
|
+
if (!Number.isFinite(n)) return DEFAULT_MANAGED_BUDGET_MAX_CALLS
|
|
156
|
+
if (n <= 0) return 0
|
|
157
|
+
return Math.min(500, Math.max(3, Math.round(n)))
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
export function normalizeManagedBudgetTokens(raw) {
|
|
161
|
+
if (raw === 0 || raw === '0') return 0
|
|
162
|
+
const n = Number(raw)
|
|
163
|
+
if (!Number.isFinite(n)) return DEFAULT_MANAGED_BUDGET_MAX_TOKENS
|
|
164
|
+
if (n <= 0) return 0
|
|
165
|
+
return Math.min(5_000_000, Math.max(10_000, Math.round(n)))
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export function classifyChiefLlmCategory(reasonKind = '') {
|
|
169
|
+
const rk = String(reasonKind || '').trim().toLowerCase()
|
|
170
|
+
if (!rk) return 'chat'
|
|
171
|
+
if (
|
|
172
|
+
rk === 'dream_roam'
|
|
173
|
+
|| rk === 'precipitate'
|
|
174
|
+
|| rk === 'distill'
|
|
175
|
+
|| rk.startsWith('archive_')
|
|
176
|
+
) {
|
|
177
|
+
return 'dream'
|
|
178
|
+
}
|
|
179
|
+
if (
|
|
180
|
+
rk === 'turn_review'
|
|
181
|
+
|| rk === 'auto_summary'
|
|
182
|
+
|| rk === 'chat_summary'
|
|
183
|
+
|| rk === 'wall_blocked'
|
|
184
|
+
|| rk === 'strong_intervention'
|
|
185
|
+
|| rk === 'hazard_diagnosis'
|
|
186
|
+
|| rk === 'idle_watchdog'
|
|
187
|
+
|| rk === 'config_activated'
|
|
188
|
+
) {
|
|
189
|
+
return 'review'
|
|
190
|
+
}
|
|
191
|
+
if (
|
|
192
|
+
rk === 'ask_chief'
|
|
193
|
+
|| rk === 'consult_chief'
|
|
194
|
+
|| rk === 'blank_explore'
|
|
195
|
+
|| rk === 'craft_wall'
|
|
196
|
+
|| rk === 'extract_bounds'
|
|
197
|
+
|| rk === 'consolidate_bounds'
|
|
198
|
+
|| rk === 'suggest_objective'
|
|
199
|
+
|| rk === 'recommend_compact'
|
|
200
|
+
) {
|
|
201
|
+
return 'chat'
|
|
202
|
+
}
|
|
203
|
+
return 'other'
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export const LLM_LEDGER_CALLS_MAX = 1_000_000
|
|
207
|
+
export const LLM_LEDGER_TOKENS_MAX = 1_000_000_000
|
|
208
|
+
|
|
209
|
+
export function emptyLlmLedger() {
|
|
210
|
+
return {
|
|
211
|
+
totalCalls: 0,
|
|
212
|
+
totalInputTokens: 0,
|
|
213
|
+
totalOutputTokens: 0,
|
|
214
|
+
totalTokens: 0,
|
|
215
|
+
byCategory: {
|
|
216
|
+
chat: { calls: 0, tokens: 0 },
|
|
217
|
+
review: { calls: 0, tokens: 0 },
|
|
218
|
+
dream: { calls: 0, tokens: 0 },
|
|
219
|
+
other: { calls: 0, tokens: 0 },
|
|
220
|
+
},
|
|
221
|
+
managedRun: {
|
|
222
|
+
startedAt: 0,
|
|
223
|
+
calls: 0,
|
|
224
|
+
tokens: 0,
|
|
225
|
+
tripped: false,
|
|
226
|
+
trippedAt: 0,
|
|
227
|
+
trippedReason: '',
|
|
228
|
+
},
|
|
229
|
+
recent: [],
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
export function normalizeLlmLedger(raw) {
|
|
234
|
+
const base = emptyLlmLedger()
|
|
235
|
+
if (!raw || typeof raw !== 'object') return base
|
|
236
|
+
const nonNegTs = v => Math.max(0, Math.round(Number(v) || 0))
|
|
237
|
+
const clampCalls = v => Math.min(LLM_LEDGER_CALLS_MAX, Math.max(0, Math.round(Number(v) || 0)))
|
|
238
|
+
const clampTokens = v => Math.min(LLM_LEDGER_TOKENS_MAX, Math.max(0, Math.round(Number(v) || 0)))
|
|
239
|
+
base.totalCalls = clampCalls(raw.totalCalls)
|
|
240
|
+
base.totalInputTokens = clampTokens(raw.totalInputTokens)
|
|
241
|
+
base.totalOutputTokens = clampTokens(raw.totalOutputTokens)
|
|
242
|
+
base.totalTokens = clampTokens(raw.totalTokens) || clampTokens(base.totalInputTokens + base.totalOutputTokens)
|
|
243
|
+
const rawCats = raw.byCategory && typeof raw.byCategory === 'object' ? raw.byCategory : {}
|
|
244
|
+
for (const k of ['chat', 'review', 'dream', 'other']) {
|
|
245
|
+
const c = rawCats[k] && typeof rawCats[k] === 'object' ? rawCats[k] : {}
|
|
246
|
+
base.byCategory[k] = { calls: clampCalls(c.calls), tokens: clampTokens(c.tokens) }
|
|
247
|
+
}
|
|
248
|
+
const mr = raw.managedRun && typeof raw.managedRun === 'object' ? raw.managedRun : {}
|
|
249
|
+
base.managedRun = {
|
|
250
|
+
startedAt: nonNegTs(mr.startedAt),
|
|
251
|
+
calls: clampCalls(mr.calls),
|
|
252
|
+
tokens: clampTokens(mr.tokens),
|
|
253
|
+
tripped: Boolean(mr.tripped),
|
|
254
|
+
trippedAt: nonNegTs(mr.trippedAt),
|
|
255
|
+
trippedReason: clamp(mr.trippedReason || '', 220),
|
|
256
|
+
}
|
|
257
|
+
base.recent = (Array.isArray(raw.recent) ? raw.recent : [])
|
|
258
|
+
.filter(r => r && typeof r === 'object')
|
|
259
|
+
.slice(-LLM_LEDGER_RECENT_CAP)
|
|
260
|
+
.map(r => {
|
|
261
|
+
const inTok = clampTokens(r.inputTokens)
|
|
262
|
+
const outTok = clampTokens(r.outputTokens)
|
|
263
|
+
return {
|
|
264
|
+
id: typeof r.id === 'string' && r.id ? r.id : nextId('llm'),
|
|
265
|
+
at: nonNegTs(r.at) || Date.now(),
|
|
266
|
+
category: ['chat', 'review', 'dream', 'other'].includes(r.category) ? r.category : 'other',
|
|
267
|
+
reasonKind: clamp(r.reasonKind || '', 40),
|
|
268
|
+
modelRef: clamp(r.modelRef || '', 80),
|
|
269
|
+
inputTokens: inTok,
|
|
270
|
+
outputTokens: outTok,
|
|
271
|
+
totalTokens: clampTokens(r.totalTokens) || clampTokens(inTok + outTok),
|
|
272
|
+
estimated: Boolean(r.estimated),
|
|
273
|
+
ok: r.ok !== false,
|
|
274
|
+
}
|
|
275
|
+
})
|
|
276
|
+
return base
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
export function summarizeLlmLedger(rawLedger, cfg = null) {
|
|
280
|
+
const ledger = normalizeLlmLedger(rawLedger)
|
|
281
|
+
const maxCalls = cfg && cfg.managedBudgetMaxCalls !== undefined
|
|
282
|
+
? normalizeManagedBudgetCalls(cfg.managedBudgetMaxCalls)
|
|
283
|
+
: DEFAULT_MANAGED_BUDGET_MAX_CALLS
|
|
284
|
+
const maxTokens = cfg && cfg.managedBudgetMaxTokens !== undefined
|
|
285
|
+
? normalizeManagedBudgetTokens(cfg.managedBudgetMaxTokens)
|
|
286
|
+
: DEFAULT_MANAGED_BUDGET_MAX_TOKENS
|
|
287
|
+
return {
|
|
288
|
+
totalCalls: ledger.totalCalls,
|
|
289
|
+
totalInputTokens: ledger.totalInputTokens,
|
|
290
|
+
totalOutputTokens: ledger.totalOutputTokens,
|
|
291
|
+
totalTokens: ledger.totalTokens,
|
|
292
|
+
byCategory: {
|
|
293
|
+
chat: { ...ledger.byCategory.chat },
|
|
294
|
+
review: { ...ledger.byCategory.review },
|
|
295
|
+
dream: { ...ledger.byCategory.dream },
|
|
296
|
+
other: { ...ledger.byCategory.other },
|
|
297
|
+
},
|
|
298
|
+
managedRun: { ...ledger.managedRun },
|
|
299
|
+
budget: {
|
|
300
|
+
maxCalls,
|
|
301
|
+
maxTokens,
|
|
302
|
+
},
|
|
303
|
+
recent: ledger.recent.slice(-8),
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
export function normalizeAlertEvent(raw) {
|
|
308
|
+
if (!raw || typeof raw !== 'object') return null
|
|
309
|
+
const title = clamp(raw.title || '', 100)
|
|
310
|
+
if (!title) return null
|
|
311
|
+
const validKinds = [
|
|
312
|
+
'pending_approval',
|
|
313
|
+
'pending_elevation',
|
|
314
|
+
'guard_wall_blocked',
|
|
315
|
+
'auto_continue_rescue',
|
|
316
|
+
'managed_auto_sleep',
|
|
317
|
+
'budget_circuit_break',
|
|
318
|
+
'hazard_halt',
|
|
319
|
+
]
|
|
320
|
+
const kind = validKinds.includes(raw.kind) ? raw.kind : 'pending_approval'
|
|
321
|
+
const level = ['info', 'warn', 'danger', 'success'].includes(raw.level) ? raw.level : 'info'
|
|
322
|
+
return {
|
|
323
|
+
id: typeof raw.id === 'string' && raw.id ? raw.id : nextId('alt'),
|
|
324
|
+
kind,
|
|
325
|
+
level,
|
|
326
|
+
title,
|
|
327
|
+
body: clamp(raw.body || '', 220),
|
|
328
|
+
dedupeKey: clamp(raw.dedupeKey || '', 100),
|
|
329
|
+
at: Number(raw.at) || Date.now(),
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
export function pushAlertEventToWs(ws, spec = {}) {
|
|
334
|
+
if (!ws || typeof ws !== 'object') return null
|
|
335
|
+
if (!Array.isArray(ws.alertEvents)) ws.alertEvents = []
|
|
336
|
+
const norm = normalizeAlertEvent(spec)
|
|
337
|
+
if (!norm) return null
|
|
338
|
+
if (norm.dedupeKey) {
|
|
339
|
+
const dup = ws.alertEvents.find(
|
|
340
|
+
a => a && a.dedupeKey === norm.dedupeKey && Math.abs(norm.at - (Number(a.at) || 0)) < 5_000,
|
|
341
|
+
)
|
|
342
|
+
if (dup) return dup
|
|
343
|
+
}
|
|
344
|
+
ws.alertEvents.push(norm)
|
|
345
|
+
if (ws.alertEvents.length > ALERT_EVENTS_CAP) {
|
|
346
|
+
ws.alertEvents = ws.alertEvents.slice(-ALERT_EVENTS_CAP)
|
|
347
|
+
}
|
|
348
|
+
return norm
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
export function normalizeRunMode(raw, fallbackCfg = null) {
|
|
352
|
+
const s = typeof raw === 'string' ? raw.trim().toLowerCase() : ''
|
|
353
|
+
if (s === 'off' || s === 'patrol' || s === 'managed') return s
|
|
354
|
+
if (s === 'stopped' || s === 'manual') return 'off'
|
|
355
|
+
if (s === 'smart') return 'patrol'
|
|
356
|
+
if (s === 'auto' || s === 'autopilot') return 'managed'
|
|
357
|
+
if (fallbackCfg && typeof fallbackCfg === 'object') {
|
|
358
|
+
if (fallbackCfg.stopped || fallbackCfg.paceMode === 'stopped') return 'off'
|
|
359
|
+
if (fallbackCfg.autoPilot || fallbackCfg.paceMode === 'auto') return 'managed'
|
|
360
|
+
if (fallbackCfg.paceMode === 'smart') return 'patrol'
|
|
361
|
+
}
|
|
362
|
+
return 'off'
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
export function normalizeThinkingEffort(raw) {
|
|
366
|
+
const s = typeof raw === 'string' ? raw.trim().toLowerCase() : ''
|
|
367
|
+
if (CHIEF_THINKING_EFFORTS.includes(s)) return s
|
|
368
|
+
return 'auto'
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
export function normalizeTeamEffortMode(raw) {
|
|
372
|
+
return String(raw || '').trim().toLowerCase() === 'manual' ? 'manual' : 'auto'
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
export function normalizeLockedModelEfforts(raw) {
|
|
376
|
+
const out = {}
|
|
377
|
+
if (!raw || typeof raw !== 'object') return out
|
|
378
|
+
for (const [k, v] of Object.entries(raw)) {
|
|
379
|
+
const cleanKey = String(k || '').trim().slice(0, 64)
|
|
380
|
+
if (!cleanKey) continue
|
|
381
|
+
if (v === true) out[cleanKey] = true
|
|
382
|
+
}
|
|
383
|
+
return out
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
const EFFORT_ORDER_LADDER = ['off', 'low', 'medium', 'high', 'xhigh']
|
|
387
|
+
|
|
388
|
+
export function resolveAlignedModelEffort(desiredEffort, supportedEfforts = []) {
|
|
389
|
+
const list = Array.isArray(supportedEfforts)
|
|
390
|
+
? supportedEfforts.map(e => (typeof e === 'string' ? e : (e && e.id ? String(e.id) : ''))).filter(Boolean)
|
|
391
|
+
: []
|
|
392
|
+
if (!list.length) return undefined
|
|
393
|
+
const want = String(desiredEffort || '').trim().toLowerCase()
|
|
394
|
+
if (!want || want === 'auto') {
|
|
395
|
+
if (list.includes('medium')) return 'medium'
|
|
396
|
+
return list[Math.floor(list.length / 2)] || list[0]
|
|
397
|
+
}
|
|
398
|
+
if (list.includes(want)) return want
|
|
399
|
+
const wantIdx = EFFORT_ORDER_LADDER.indexOf(want)
|
|
400
|
+
if (wantIdx < 0) return list[0]
|
|
401
|
+
for (let d = 1; d < EFFORT_ORDER_LADDER.length; d += 1) {
|
|
402
|
+
if (wantIdx - d >= 0 && list.includes(EFFORT_ORDER_LADDER[wantIdx - d])) {
|
|
403
|
+
return EFFORT_ORDER_LADDER[wantIdx - d]
|
|
404
|
+
}
|
|
405
|
+
if (wantIdx + d < EFFORT_ORDER_LADDER.length && list.includes(EFFORT_ORDER_LADDER[wantIdx + d])) {
|
|
406
|
+
return EFFORT_ORDER_LADDER[wantIdx + d]
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
return list[0]
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
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-----)/
|
|
414
|
+
|
|
415
|
+
let idSeq = 0
|
|
416
|
+
|
|
417
|
+
export function nextId(prefix) {
|
|
418
|
+
idSeq = (idSeq + 1) % 1000000
|
|
419
|
+
return prefix + '-' + Date.now().toString(36) + '-' + idSeq.toString(36)
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
export function clamp(value, max) {
|
|
423
|
+
const text = String(value == null ? '' : value).replace(/\s+/g, ' ').trim()
|
|
424
|
+
if (text.length <= max) return text
|
|
425
|
+
return text.slice(0, Math.max(0, max - 1)) + '…'
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
export function cleanMultiline(value, max) {
|
|
429
|
+
const text = String(value == null ? '' : value).replace(/\r/g, '').trim()
|
|
430
|
+
if (text.length <= max) return text
|
|
431
|
+
return text.slice(0, Math.max(0, max - 1)) + '…'
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
export function secretLike(text) {
|
|
435
|
+
return SECRET_PATTERN.test(String(text || ''))
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
export function canonicalSortJsonValue(val) {
|
|
440
|
+
if (val === null || val === undefined) return null
|
|
441
|
+
if (Array.isArray(val)) return val.map(v => canonicalSortJsonValue(v))
|
|
442
|
+
if (typeof val === 'object') {
|
|
443
|
+
const out = {}
|
|
444
|
+
for (const k of Object.keys(val).sort()) {
|
|
445
|
+
const v = val[k]
|
|
446
|
+
if (v !== undefined) out[k] = canonicalSortJsonValue(v)
|
|
447
|
+
}
|
|
448
|
+
return out
|
|
449
|
+
}
|
|
450
|
+
return val
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
export function computeApprovalPayloadHash(kind = 'tool', payload = {}) {
|
|
454
|
+
const canonical = JSON.stringify(canonicalSortJsonValue({
|
|
455
|
+
kind: String(kind || 'tool'),
|
|
456
|
+
payload: payload && typeof payload === 'object' ? payload : {},
|
|
457
|
+
}))
|
|
458
|
+
return crypto.createHash('sha256').update(canonical).digest('hex')
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
export function normalizeChiefRiskAck(raw) {
|
|
462
|
+
if (!raw || typeof raw !== 'object' || raw.acknowledged !== true) return null
|
|
463
|
+
const at = Number(raw.at) || 0
|
|
464
|
+
if (at <= 0) return null
|
|
465
|
+
return {
|
|
466
|
+
acknowledged: true,
|
|
467
|
+
at,
|
|
468
|
+
by: clamp(raw.by || 'operator', 40),
|
|
469
|
+
version: clamp(raw.version || '1.2.1', 20),
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
export function hasValidChiefRiskAck(ws) {
|
|
474
|
+
return Boolean(ws && ws.chiefRiskAck && ws.chiefRiskAck.acknowledged === true && Number(ws.chiefRiskAck.at) > 0)
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
export function normalizePendingApproval(raw) {
|
|
478
|
+
if (!raw || typeof raw !== 'object') return null
|
|
479
|
+
const opLabel = clamp(raw.operationLabel || raw.operation || '', 80)
|
|
480
|
+
if (!opLabel) return null
|
|
481
|
+
const validStatuses = ['pending', 'approved', 'rejected', 'executed', 'failed', 'expired']
|
|
482
|
+
const status = validStatuses.includes(raw.status) ? raw.status : 'pending'
|
|
483
|
+
const validKinds = ['tool', 'relay', 'compact', 'auto_continue', 'archive_op', 'model_effort']
|
|
484
|
+
const kind = validKinds.includes(raw.kind) ? raw.kind : 'tool'
|
|
485
|
+
const validCategories = ['workspace_file', 'system_command', 'main_workflow', 'subagent_workflow']
|
|
486
|
+
const category = validCategories.includes(raw.category) ? raw.category : 'workspace_file'
|
|
487
|
+
const payload = raw.payload && typeof raw.payload === 'object' ? raw.payload : {}
|
|
488
|
+
const payloadHash = typeof raw.payloadHash === 'string' && raw.payloadHash.trim()
|
|
489
|
+
? raw.payloadHash.trim()
|
|
490
|
+
: computeApprovalPayloadHash(kind, payload)
|
|
491
|
+
const taskId = clamp(raw.taskId || raw.resumeTaskId || '', 80)
|
|
492
|
+
const capabilityScope = raw.capabilityScope && typeof raw.capabilityScope === 'object'
|
|
493
|
+
? raw.capabilityScope
|
|
494
|
+
: buildCapabilityScope({
|
|
495
|
+
kind,
|
|
496
|
+
tool: payload.tool || kind,
|
|
497
|
+
args: payload.args || {},
|
|
498
|
+
cwd: payload.cwd || '',
|
|
499
|
+
target: payload.target || '',
|
|
500
|
+
})
|
|
501
|
+
return {
|
|
502
|
+
id: typeof raw.id === 'string' && raw.id ? raw.id : nextId('apr'),
|
|
503
|
+
status,
|
|
504
|
+
category,
|
|
505
|
+
operationLabel: opLabel,
|
|
506
|
+
targetLabel: clamp(raw.targetLabel || raw.target || '', 120),
|
|
507
|
+
reason: clamp(raw.reason || '', 240),
|
|
508
|
+
impact: clamp(raw.impact || '', 220),
|
|
509
|
+
preview: cleanMultiline(raw.preview || '', 420),
|
|
510
|
+
kind,
|
|
511
|
+
payload,
|
|
512
|
+
payloadHash,
|
|
513
|
+
capabilityScope,
|
|
514
|
+
taskId,
|
|
515
|
+
resumeTaskId: taskId,
|
|
516
|
+
expiresAt: Math.max(0, Number(raw.expiresAt) || 0),
|
|
517
|
+
dedupeKey: clamp(raw.dedupeKey || '', 120),
|
|
518
|
+
by: clamp(raw.by || 'chief', 40),
|
|
519
|
+
createdAt: Number(raw.createdAt) || Date.now(),
|
|
520
|
+
resolvedAt: Number(raw.resolvedAt) || 0,
|
|
521
|
+
resolvedBy: clamp(raw.resolvedBy || '', 40),
|
|
522
|
+
resultMessage: clamp(raw.resultMessage || '', 260),
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
export function normalizePendingElevation(raw) {
|
|
527
|
+
if (!raw || typeof raw !== 'object') return null
|
|
528
|
+
if (raw.status && raw.status !== 'pending') return null
|
|
529
|
+
const targetMode = normalizePermissionMode(raw.targetMode)
|
|
530
|
+
if (targetMode === 'advisor') return null
|
|
531
|
+
const createdAt = Number(raw.createdAt) || Date.now()
|
|
532
|
+
const taskId = clamp(raw.taskId || raw.resumeTaskId || '', 80)
|
|
533
|
+
return {
|
|
534
|
+
id: typeof raw.id === 'string' && raw.id ? raw.id : nextId('elv'),
|
|
535
|
+
status: 'pending',
|
|
536
|
+
fromMode: normalizePermissionMode(raw.fromMode || 'advisor'),
|
|
537
|
+
targetMode,
|
|
538
|
+
reason: clamp(raw.reason || '当前任务需要更高参谋权限才能继续执行', 260),
|
|
539
|
+
requestedActionSummary: clamp(raw.requestedActionSummary || '', 220),
|
|
540
|
+
requestedCapabilities: Array.isArray(raw.requestedCapabilities)
|
|
541
|
+
? raw.requestedCapabilities.map(c => clamp(c, 60)).filter(Boolean).slice(0, 12)
|
|
542
|
+
: [],
|
|
543
|
+
taskId,
|
|
544
|
+
resumeTaskId: taskId,
|
|
545
|
+
expiresAt: Math.max(0, Number(raw.expiresAt) || (createdAt + DEFAULT_RESUME_TTL_MS)),
|
|
546
|
+
by: clamp(raw.by || 'chief', 40),
|
|
547
|
+
createdAt,
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
export const VALID_TASK_LEDGER_STATUSES = [
|
|
552
|
+
'proposed',
|
|
553
|
+
'awaiting_elevation',
|
|
554
|
+
'awaiting_approval',
|
|
555
|
+
'awaiting_inquiry',
|
|
556
|
+
'dispatched',
|
|
557
|
+
'running',
|
|
558
|
+
'resuming',
|
|
559
|
+
'verifying',
|
|
560
|
+
'completed',
|
|
561
|
+
'interrupted',
|
|
562
|
+
'rejected',
|
|
563
|
+
'cancelled',
|
|
564
|
+
'expired',
|
|
565
|
+
'failed',
|
|
566
|
+
]
|
|
567
|
+
|
|
568
|
+
export function normalizeTaskLedgerEntry(raw) {
|
|
569
|
+
if (!raw || typeof raw !== 'object') return null
|
|
570
|
+
const spec = raw.resumeSpec && typeof raw.resumeSpec === 'object' ? raw.resumeSpec : {}
|
|
571
|
+
const originalText = cleanMultiline(spec.originalText || raw.originalText || '', 2000)
|
|
572
|
+
if (!originalText) return null
|
|
573
|
+
const status = VALID_TASK_LEDGER_STATUSES.includes(raw.status) ? raw.status : 'awaiting_approval'
|
|
574
|
+
const createdAt = Number(raw.createdAt) || Date.now()
|
|
575
|
+
const updatedAt = Number(raw.updatedAt) || createdAt
|
|
576
|
+
const taskId = typeof (raw.taskId || raw.id) === 'string' && (raw.taskId || raw.id)
|
|
577
|
+
? String(raw.taskId || raw.id)
|
|
578
|
+
: nextId('rtask')
|
|
579
|
+
const validKinds = ['approval_resume', 'elevation_resume', 'tool_execution', 'inquiry', 'auto_continue']
|
|
580
|
+
const kind = validKinds.includes(raw.kind)
|
|
581
|
+
? raw.kind
|
|
582
|
+
: (raw.elevationId || status === 'awaiting_elevation' ? 'elevation_resume' : 'approval_resume')
|
|
583
|
+
const forcedTarget = clamp(spec.forcedTarget !== undefined ? spec.forcedTarget : (raw.forcedTarget || ''), 64)
|
|
584
|
+
const forcedModeRaw = spec.forcedMode !== undefined ? spec.forcedMode : raw.forcedMode
|
|
585
|
+
const forcedMode = ['steer', 'followup', 'silent'].includes(forcedModeRaw) ? forcedModeRaw : 'steer'
|
|
586
|
+
const rawImages = Array.isArray(spec.savedImagePaths) ? spec.savedImagePaths : raw.savedImagePaths
|
|
587
|
+
const savedImagePaths = Array.isArray(rawImages)
|
|
588
|
+
? rawImages.slice(0, 4).filter(p => p && typeof p.path === 'string').map(p => ({
|
|
589
|
+
index: Number(p.index) || 1,
|
|
590
|
+
path: String(p.path),
|
|
591
|
+
name: clamp(p.name || '', 80),
|
|
592
|
+
mediaType: clamp(p.mediaType || '', 40),
|
|
593
|
+
bytes: Math.max(0, Number(p.bytes) || 0),
|
|
594
|
+
}))
|
|
595
|
+
: []
|
|
596
|
+
const rawCompleted = Array.isArray(spec.completedActions) ? spec.completedActions : raw.completedActions
|
|
597
|
+
const completedActions = Array.isArray(rawCompleted)
|
|
598
|
+
? rawCompleted.map(x => clamp(x, 220)).filter(Boolean).slice(-12)
|
|
599
|
+
: []
|
|
600
|
+
const retryCount = Math.max(0, Math.min(4, Math.round(Number(raw.retryCount !== undefined ? raw.retryCount : raw.resumeDepth) || 0)))
|
|
601
|
+
const capabilityScope = raw.capabilityScope && typeof raw.capabilityScope === 'object' ? raw.capabilityScope : null
|
|
602
|
+
const payloadHash = typeof raw.payloadHash === 'string' ? raw.payloadHash.trim() : ''
|
|
603
|
+
return {
|
|
604
|
+
id: taskId,
|
|
605
|
+
taskId,
|
|
606
|
+
kind,
|
|
607
|
+
status,
|
|
608
|
+
capabilityScope,
|
|
609
|
+
payloadHash,
|
|
610
|
+
resumeSpec: {
|
|
611
|
+
originalText,
|
|
612
|
+
forcedTarget,
|
|
613
|
+
forcedMode,
|
|
614
|
+
savedImagePaths,
|
|
615
|
+
completedActions,
|
|
616
|
+
},
|
|
617
|
+
originalText,
|
|
618
|
+
forcedTarget,
|
|
619
|
+
forcedMode,
|
|
620
|
+
savedImagePaths,
|
|
621
|
+
completedActions,
|
|
622
|
+
pendingApprovalIds: Array.isArray(raw.pendingApprovalIds)
|
|
623
|
+
? [...new Set(raw.pendingApprovalIds.map(x => String(x || '').trim()).filter(Boolean))].slice(0, 12)
|
|
624
|
+
: [],
|
|
625
|
+
elevationId: clamp(raw.elevationId || '', 80),
|
|
626
|
+
inquiryId: clamp(raw.inquiryId || '', 80),
|
|
627
|
+
lastReceipt: cleanMultiline(raw.lastReceipt || '', 300),
|
|
628
|
+
retryCount,
|
|
629
|
+
resumeDepth: retryCount,
|
|
630
|
+
createdAt,
|
|
631
|
+
updatedAt,
|
|
632
|
+
expiresAt: Math.max(0, Number(raw.expiresAt) || (createdAt + DEFAULT_RESUME_TTL_MS)),
|
|
633
|
+
resolvedAt: Math.max(0, Number(raw.resolvedAt) || 0),
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
export function recoverTaskLedgerEntriesOnDiskLoad(entries, now = Date.now()) {
|
|
638
|
+
if (!Array.isArray(entries)) return []
|
|
639
|
+
return entries.map((entry) => {
|
|
640
|
+
if (!entry || typeof entry !== 'object') return entry
|
|
641
|
+
const tid = entry.taskId || entry.id
|
|
642
|
+
if (
|
|
643
|
+
(entry.status === 'running' || entry.status === 'resuming' || entry.status === 'verifying')
|
|
644
|
+
&& !activeResumingTaskIds.has(tid)
|
|
645
|
+
) {
|
|
646
|
+
return {
|
|
647
|
+
...entry,
|
|
648
|
+
status: 'interrupted',
|
|
649
|
+
updatedAt: now,
|
|
650
|
+
lastReceipt: entry.lastReceipt || '检测到上次运行中断,已安全降级为 interrupted 等待人工确认续跑',
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
if (
|
|
654
|
+
(entry.status === 'proposed' || entry.status === 'awaiting_approval' || entry.status === 'awaiting_elevation' || entry.status === 'awaiting_inquiry')
|
|
655
|
+
&& entry.expiresAt > 0
|
|
656
|
+
&& now > entry.expiresAt
|
|
657
|
+
) {
|
|
658
|
+
return {
|
|
659
|
+
...entry,
|
|
660
|
+
status: 'expired',
|
|
661
|
+
updatedAt: now,
|
|
662
|
+
resolvedAt: entry.resolvedAt || now,
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
return entry
|
|
666
|
+
})
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
export function normalizeAuditEntry(raw) {
|
|
670
|
+
return normalizeAuditRecord(raw, DEFAULT_CHIEF_PERMISSION_MODE)
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
|
|
674
|
+
export function emptyWorkspace() {
|
|
675
|
+
const sharedLedger = []
|
|
676
|
+
return {
|
|
677
|
+
config: null,
|
|
678
|
+
chiefRiskAck: null,
|
|
679
|
+
pendingApprovals: [],
|
|
680
|
+
pendingElevation: null,
|
|
681
|
+
taskLedger: sharedLedger,
|
|
682
|
+
resumeTasks: sharedLedger,
|
|
683
|
+
auditLog: [],
|
|
684
|
+
facts: [],
|
|
685
|
+
narrative: { hash: '', text: '', at: 0, byModel: '', clusterSig: '' },
|
|
686
|
+
suggestions: [],
|
|
687
|
+
inquiries: [],
|
|
688
|
+
chat: [],
|
|
689
|
+
mailbox: [],
|
|
690
|
+
seenMailAt: {},
|
|
691
|
+
seenFactsAt: {},
|
|
692
|
+
reviewCursors: {},
|
|
693
|
+
runtimeGuard: {
|
|
694
|
+
lastCompactedSeq: 0,
|
|
695
|
+
lastCompactedAt: 0,
|
|
696
|
+
interventionTurns: 0,
|
|
697
|
+
lastDigestHash: '',
|
|
698
|
+
unchangedCount: 0,
|
|
699
|
+
cooldownUntil: 0,
|
|
700
|
+
circuitBroken: false,
|
|
701
|
+
circuitReason: '',
|
|
702
|
+
hazardAlert: null,
|
|
703
|
+
lastGoalAchievedSig: '',
|
|
704
|
+
autoPilotStartedAt: 0,
|
|
705
|
+
autoPilotHadTurn: false,
|
|
706
|
+
managedStartedAt: 0,
|
|
707
|
+
lastActivityAt: 0,
|
|
708
|
+
lastDreamRoamAt: 0,
|
|
709
|
+
lastAutoArchiveOrgAt: 0,
|
|
710
|
+
},
|
|
711
|
+
flippedPrecipitatedIds: [],
|
|
712
|
+
llmLedger: emptyLlmLedger(),
|
|
713
|
+
alertEvents: [],
|
|
714
|
+
bubbleHarnesses: [],
|
|
715
|
+
bubbleLock: { manualLocked: false, lockedAt: 0, reason: '' },
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
export function normalizeFact(raw) {
|
|
720
|
+
if (!raw || typeof raw !== 'object') return null
|
|
721
|
+
const text = clamp(raw.text, FACT_TEXT_MAX)
|
|
722
|
+
if (!text || secretLike(text)) return null
|
|
723
|
+
const validCategories = ['discipline', 'architecture', 'progress', 'preference', 'team']
|
|
724
|
+
const category = validCategories.includes(raw.category) ? raw.category : 'discipline'
|
|
725
|
+
const peerRootIds = Array.isArray(raw.peerRootIds)
|
|
726
|
+
? [...new Set(raw.peerRootIds.map(x => String(x || '').trim()).filter(Boolean))].slice(0, 16)
|
|
727
|
+
: []
|
|
728
|
+
return {
|
|
729
|
+
id: typeof raw.id === 'string' && raw.id ? raw.id : nextId('fact'),
|
|
730
|
+
text,
|
|
731
|
+
category,
|
|
732
|
+
by: clamp(raw.by || 'chief', 36),
|
|
733
|
+
source: clamp(raw.source || '', 60),
|
|
734
|
+
originRootId: typeof raw.originRootId === 'string' ? raw.originRootId.trim() : '',
|
|
735
|
+
...(peerRootIds.length ? { peerRootIds } : {}),
|
|
736
|
+
pinned: Boolean(raw.pinned),
|
|
737
|
+
addedAt: Number(raw.addedAt) || Date.now(),
|
|
738
|
+
updatedAt: Number(raw.updatedAt) || Number(raw.addedAt) || Date.now(),
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
export function normalizeSuggestion(raw) {
|
|
743
|
+
if (!raw || typeof raw !== 'object') return null
|
|
744
|
+
const title = clamp(raw.title, 90)
|
|
745
|
+
if (!title) return null
|
|
746
|
+
const kind = ['bound', 'board', 'goal_approval', 'relay', 'advice', 'guard_wall', 'wall_removal', 'archive_op', 'model_effort'].includes(raw.kind) ? raw.kind : 'relay'
|
|
747
|
+
const boundField = ['forbidden', 'allowed', 'notes'].includes(raw.boundField) ? raw.boundField : 'forbidden'
|
|
748
|
+
const replaces = Array.isArray(raw.replaces)
|
|
749
|
+
? raw.replaces.map(x => String(x || '').trim()).filter(Boolean).slice(0, 20)
|
|
750
|
+
: []
|
|
751
|
+
const wallSpec = raw.wallSpec && typeof raw.wallSpec === 'object' ? { ...raw.wallSpec } : null
|
|
752
|
+
const wallRemovalSpec = raw.wallRemovalSpec && typeof raw.wallRemovalSpec === 'object' ? { ...raw.wallRemovalSpec } : null
|
|
753
|
+
const archiveSpec = (raw.archiveSpec && typeof raw.archiveSpec === 'object')
|
|
754
|
+
? { ...raw.archiveSpec }
|
|
755
|
+
: ((raw.archiveOp && typeof raw.archiveOp === 'object') ? { ...raw.archiveOp } : null)
|
|
756
|
+
const effortSpec = (raw.effortSpec && typeof raw.effortSpec === 'object')
|
|
757
|
+
? { ...raw.effortSpec }
|
|
758
|
+
: ((raw.effortOp && typeof raw.effortOp === 'object') ? { ...raw.effortOp } : null)
|
|
759
|
+
return {
|
|
760
|
+
id: typeof raw.id === 'string' && raw.id ? raw.id : nextId('sug'),
|
|
761
|
+
kind,
|
|
762
|
+
boundField,
|
|
763
|
+
replaces,
|
|
764
|
+
pinGlobal: Boolean(raw.pinGlobal),
|
|
765
|
+
...(wallSpec ? { wallSpec } : {}),
|
|
766
|
+
...(wallRemovalSpec ? { wallRemovalSpec } : {}),
|
|
767
|
+
...(archiveSpec ? { archiveSpec } : {}),
|
|
768
|
+
...(effortSpec ? { effortSpec } : {}),
|
|
769
|
+
fromAgent: clamp(raw.fromAgent || '', 48),
|
|
770
|
+
title,
|
|
771
|
+
reason: clamp(raw.reason || '', 220),
|
|
772
|
+
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),
|
|
773
|
+
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),
|
|
774
|
+
mode: ['steer', 'followup', 'silent'].includes(raw.mode) ? raw.mode : (kind === 'advice' ? 'followup' : 'steer'),
|
|
775
|
+
draftText: cleanMultiline(raw.draftText || '', 600),
|
|
776
|
+
evidence: cleanMultiline(raw.evidence || '', 600),
|
|
777
|
+
missing: clamp(raw.missing || '', 300),
|
|
778
|
+
boardOp: raw.boardOp && typeof raw.boardOp === 'object' ? raw.boardOp : null,
|
|
779
|
+
popup: Boolean(raw.popup || kind === 'advice' || kind === 'wall_removal'),
|
|
780
|
+
urgency: ['normal', 'high'].includes(raw.urgency) ? raw.urgency : (kind === 'wall_removal' ? 'high' : 'normal'),
|
|
781
|
+
status: ['pending', 'applied', 'dismissed'].includes(raw.status) ? raw.status : 'pending',
|
|
782
|
+
createdAt: Number(raw.createdAt) || Date.now(),
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
export function normalizeInquiryItem(raw) {
|
|
787
|
+
if (!raw || typeof raw !== 'object') return null
|
|
788
|
+
const question = cleanMultiline(raw.question || raw.text || '', 600)
|
|
789
|
+
if (!question) return null
|
|
790
|
+
const status = ['pending', 'delivered', 'answered', 'expired'].includes(raw.status) ? raw.status : 'pending'
|
|
791
|
+
const inquiryId = typeof (raw.inquiryId || raw.id) === 'string' && (raw.inquiryId || raw.id)
|
|
792
|
+
? String(raw.inquiryId || raw.id)
|
|
793
|
+
: nextId('inq')
|
|
794
|
+
return {
|
|
795
|
+
id: inquiryId,
|
|
796
|
+
inquiryId,
|
|
797
|
+
taskId: clamp(raw.taskId || '', 80),
|
|
798
|
+
target: clamp(raw.target || 'lead', 64),
|
|
799
|
+
question,
|
|
800
|
+
context: clamp(raw.context || '', 220),
|
|
801
|
+
answer: cleanMultiline(raw.answer || '', 1200),
|
|
802
|
+
status,
|
|
803
|
+
by: clamp(raw.by || 'chief', 40),
|
|
804
|
+
answeredBy: clamp(raw.answeredBy || '', 40),
|
|
805
|
+
createdAt: Number(raw.createdAt) || Date.now(),
|
|
806
|
+
deliveredAt: Number(raw.deliveredAt) || 0,
|
|
807
|
+
answeredAt: Number(raw.answeredAt) || 0,
|
|
808
|
+
expiresAt: Number(raw.expiresAt) || ((Number(raw.createdAt) || Date.now()) + DEFAULT_RESUME_TTL_MS),
|
|
809
|
+
}
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
export function normalizeMail(raw) {
|
|
813
|
+
if (!raw || typeof raw !== 'object') return null
|
|
814
|
+
const imageCount = Math.max(0, Math.round(Number(raw.imageCount) || 0))
|
|
815
|
+
const text = cleanMultiline(raw.text, 1500) || (imageCount > 0 ? `[附图 ×${imageCount}]` : '')
|
|
816
|
+
if (!text) return null
|
|
817
|
+
const participantRoots = Array.isArray(raw.participantRoots)
|
|
818
|
+
? [...new Set(raw.participantRoots.map(x => String(x || '').trim()).filter(Boolean))].sort().slice(0, 24)
|
|
819
|
+
: []
|
|
820
|
+
const validChannels = ['internal', 'pair', 'multi', 'broadcast']
|
|
821
|
+
const channelType = validChannels.includes(raw.channelType) ? raw.channelType : ''
|
|
822
|
+
return {
|
|
823
|
+
id: typeof raw.id === 'string' && raw.id ? raw.id : nextId('mail'),
|
|
824
|
+
from: clamp(raw.from || 'agent', 48),
|
|
825
|
+
fromSession: String(raw.fromSession || ''),
|
|
826
|
+
fromRootId: String(raw.fromRootId || ''),
|
|
827
|
+
to: clamp(raw.to || 'lead', 64),
|
|
828
|
+
toSession: String(raw.toSession || ''),
|
|
829
|
+
toRootId: String(raw.toRootId || ''),
|
|
830
|
+
...(participantRoots.length ? { participantRoots } : {}),
|
|
831
|
+
...(channelType ? { channelType } : {}),
|
|
832
|
+
...(raw.broadcastId ? { broadcastId: String(raw.broadcastId) } : {}),
|
|
833
|
+
subject: clamp(raw.subject || '', 80),
|
|
834
|
+
text,
|
|
835
|
+
...(imageCount > 0 ? { imageCount } : {}),
|
|
836
|
+
mode: ['steer', 'followup', 'silent'].includes(raw.mode) ? raw.mode : 'steer',
|
|
837
|
+
deliveredPhysical: Boolean(raw.deliveredPhysical),
|
|
838
|
+
readBy: Array.isArray(raw.readBy) ? raw.readBy.map(String).slice(0, 32) : [],
|
|
839
|
+
at: Number(raw.at) || Date.now(),
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
export function normalizeWorkspace(raw) {
|
|
844
|
+
const src = raw && typeof raw === 'object' ? raw : {}
|
|
845
|
+
const base = emptyWorkspace()
|
|
846
|
+
base.facts = (Array.isArray(src.facts) ? src.facts : []).map(normalizeFact).filter(Boolean).slice(-FACTS_CAP)
|
|
847
|
+
if (src.narrative && typeof src.narrative === 'object') {
|
|
848
|
+
base.narrative = {
|
|
849
|
+
hash: String(src.narrative.hash || ''),
|
|
850
|
+
text: String(src.narrative.text || ''),
|
|
851
|
+
at: Number(src.narrative.at) || 0,
|
|
852
|
+
byModel: String(src.narrative.byModel || ''),
|
|
853
|
+
clusterSig: String(src.narrative.clusterSig || ''),
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
base.suggestions = (Array.isArray(src.suggestions) ? src.suggestions : [])
|
|
857
|
+
.map(normalizeSuggestion)
|
|
858
|
+
.filter(Boolean)
|
|
859
|
+
.slice(-SUGGESTIONS_CAP * 2)
|
|
860
|
+
base.inquiries = (Array.isArray(src.inquiries) ? src.inquiries : [])
|
|
861
|
+
.map(normalizeInquiryItem)
|
|
862
|
+
.filter(Boolean)
|
|
863
|
+
.slice(-24)
|
|
864
|
+
base.chat = (Array.isArray(src.chat) ? src.chat : [])
|
|
865
|
+
.filter(item => item && typeof item === 'object' && typeof item.text === 'string')
|
|
866
|
+
.slice(-CHAT_CAP)
|
|
867
|
+
.map(item => {
|
|
868
|
+
const imageCount = Math.max(0, Math.round(Number(item.imageCount) || 0))
|
|
869
|
+
const kind = item.kind === 'receipt' ? 'receipt' : (item.kind === 'qa' ? 'qa' : '')
|
|
870
|
+
const resumeTaskId = item.resumeTaskId ? String(item.resumeTaskId) : ''
|
|
871
|
+
const thinkingEffort = typeof item.thinkingEffort === 'string' && item.thinkingEffort ? item.thinkingEffort : ''
|
|
872
|
+
const thinkingEffortMode = item.thinkingEffortMode === 'auto' || item.thinkingEffortMode === 'manual' ? item.thinkingEffortMode : ''
|
|
873
|
+
return {
|
|
874
|
+
id: String(item.id || nextId('chat')),
|
|
875
|
+
role: item.role === 'user' ? 'user' : 'chief',
|
|
876
|
+
text: cleanMultiline(item.text, 2000),
|
|
877
|
+
target: item.target ? String(item.target) : '',
|
|
878
|
+
...(kind ? { kind } : {}),
|
|
879
|
+
...(resumeTaskId ? { resumeTaskId } : {}),
|
|
880
|
+
...(thinkingEffort ? { thinkingEffort } : {}),
|
|
881
|
+
...(thinkingEffortMode ? { thinkingEffortMode } : {}),
|
|
882
|
+
...(item.isOneStopReport ? { isOneStopReport: true } : {}),
|
|
883
|
+
...(imageCount > 0 ? { imageCount } : {}),
|
|
884
|
+
actions: Array.isArray(item.actions) ? item.actions.slice(0, 8) : [],
|
|
885
|
+
at: Number(item.at) || Date.now(),
|
|
886
|
+
}
|
|
887
|
+
})
|
|
888
|
+
base.mailbox = (Array.isArray(src.mailbox) ? src.mailbox : []).map(normalizeMail).filter(Boolean).slice(-MAIL_CAP)
|
|
889
|
+
base.seenMailAt = src.seenMailAt && typeof src.seenMailAt === 'object' ? { ...src.seenMailAt } : {}
|
|
890
|
+
base.seenFactsAt = src.seenFactsAt && typeof src.seenFactsAt === 'object' ? { ...src.seenFactsAt } : {}
|
|
891
|
+
base.reviewCursors = src.reviewCursors && typeof src.reviewCursors === 'object' ? { ...src.reviewCursors } : {}
|
|
892
|
+
const rg = src.runtimeGuard && typeof src.runtimeGuard === 'object' ? src.runtimeGuard : {}
|
|
893
|
+
base.runtimeGuard = {
|
|
894
|
+
lastCompactedSeq: Math.max(0, Math.round(Number(rg.lastCompactedSeq) || 0)),
|
|
895
|
+
lastCompactedAt: Math.max(0, Number(rg.lastCompactedAt) || 0),
|
|
896
|
+
autoCompactCount: Math.max(0, Math.round(Number(rg.autoCompactCount) || 0)),
|
|
897
|
+
pendingSmartCompact: rg.pendingSmartCompact && typeof rg.pendingSmartCompact === 'object'
|
|
898
|
+
? {
|
|
899
|
+
at: Number(rg.pendingSmartCompact.at) || Date.now(),
|
|
900
|
+
reason: clamp(rg.pendingSmartCompact.reason || '', 240),
|
|
901
|
+
by: clamp(rg.pendingSmartCompact.by || 'lead', 40),
|
|
902
|
+
}
|
|
903
|
+
: null,
|
|
904
|
+
interventionTurns: Math.max(0, Math.round(Number(rg.interventionTurns) || 0)),
|
|
905
|
+
lastDigestHash: String(rg.lastDigestHash || ''),
|
|
906
|
+
unchangedCount: Math.max(0, Math.round(Number(rg.unchangedCount) || 0)),
|
|
907
|
+
cooldownUntil: Math.max(0, Number(rg.cooldownUntil) || 0),
|
|
908
|
+
circuitBroken: Boolean(rg.circuitBroken),
|
|
909
|
+
circuitReason: String(rg.circuitReason || ''),
|
|
910
|
+
hazardAlert: rg.hazardAlert && typeof rg.hazardAlert === 'object' && (rg.hazardAlert.reason || rg.hazardAlert.title)
|
|
911
|
+
? {
|
|
912
|
+
id: String(rg.hazardAlert.id || ''),
|
|
913
|
+
category: clamp(rg.hazardAlert.category || 'irreversible_risk', 40),
|
|
914
|
+
title: clamp(rg.hazardAlert.title || '强介入安全煞停', 120),
|
|
915
|
+
reason: cleanMultiline(rg.hazardAlert.reason || '', 600),
|
|
916
|
+
objective: clamp(rg.hazardAlert.objective || '', 300),
|
|
917
|
+
at: Math.max(0, Number(rg.hazardAlert.at) || 0),
|
|
918
|
+
}
|
|
919
|
+
: null,
|
|
920
|
+
lastGoalAchievedSig: String(rg.lastGoalAchievedSig || ''),
|
|
921
|
+
autoPilotStartedAt: Math.max(0, Number(rg.autoPilotStartedAt) || 0),
|
|
922
|
+
autoPilotHadTurn: Boolean(rg.autoPilotHadTurn),
|
|
923
|
+
managedStartedAt: Math.max(0, Number(rg.managedStartedAt) || Number(rg.autoPilotStartedAt) || 0),
|
|
924
|
+
lastActivityAt: Math.max(0, Number(rg.lastActivityAt) || 0),
|
|
925
|
+
lastDreamRoamAt: Math.max(0, Number(rg.lastDreamRoamAt) || 0),
|
|
926
|
+
lastAutoArchiveOrgAt: Math.max(0, Number(rg.lastAutoArchiveOrgAt) || 0),
|
|
927
|
+
}
|
|
928
|
+
base.chiefRiskAck = normalizeChiefRiskAck(src.chiefRiskAck)
|
|
929
|
+
base.pendingApprovals = (Array.isArray(src.pendingApprovals) ? src.pendingApprovals : [])
|
|
930
|
+
.map(normalizePendingApproval)
|
|
931
|
+
.filter(Boolean)
|
|
932
|
+
.slice(-APPROVALS_CAP)
|
|
933
|
+
base.pendingElevation = normalizePendingElevation(src.pendingElevation)
|
|
934
|
+
const rawLedgerSrc = Array.isArray(src.taskLedger) && src.taskLedger.length > 0
|
|
935
|
+
? src.taskLedger
|
|
936
|
+
: (Array.isArray(src.resumeTasks) ? src.resumeTasks : [])
|
|
937
|
+
const normalizedLedger = rawLedgerSrc
|
|
938
|
+
.map(normalizeTaskLedgerEntry)
|
|
939
|
+
.filter(Boolean)
|
|
940
|
+
.slice(-TASK_LEDGER_CAP)
|
|
941
|
+
base.taskLedger = normalizedLedger
|
|
942
|
+
base.resumeTasks = normalizedLedger
|
|
943
|
+
base.auditLog = (Array.isArray(src.auditLog) ? src.auditLog : [])
|
|
944
|
+
.map(normalizeAuditEntry)
|
|
945
|
+
.filter(Boolean)
|
|
946
|
+
.slice(-AUDIT_LOG_CAP)
|
|
947
|
+
const ackOk = hasValidChiefRiskAck(base)
|
|
948
|
+
if (src.config && typeof src.config === 'object') {
|
|
949
|
+
const validPaces = ['manual', 'smart', 'auto', 'stopped']
|
|
950
|
+
const pm = validPaces.includes(src.config.paceMode) ? src.config.paceMode : undefined
|
|
951
|
+
const rawStopped = typeof src.config.stopped === 'boolean' ? src.config.stopped : (pm === 'stopped')
|
|
952
|
+
const rm = normalizeRunMode(src.config.runMode, { ...src.config, stopped: rawStopped, paceMode: pm })
|
|
953
|
+
const rawPerm = typeof src.config.permissionMode === 'string'
|
|
954
|
+
? normalizePermissionMode(src.config.permissionMode, { requireAck: true, hasChiefRiskAck: ackOk })
|
|
955
|
+
: DEFAULT_CHIEF_PERMISSION_MODE
|
|
956
|
+
const plugCheck = validatePolicyPluginList(src.config.policyPlugins)
|
|
957
|
+
const policyPlugins = plugCheck.ok ? plugCheck.plugins : []
|
|
958
|
+
const lockedModelEfforts = normalizeLockedModelEfforts(src.config.lockedModelEfforts)
|
|
959
|
+
const managedIdleTimeoutMs = Number.isFinite(Number(src.config.managedIdleTimeoutMs)) && Number(src.config.managedIdleTimeoutMs) >= 50
|
|
960
|
+
? Math.min(2 * 60 * 60 * 1000, Math.round(Number(src.config.managedIdleTimeoutMs)))
|
|
961
|
+
: DEFAULT_MANAGED_IDLE_TIMEOUT_MS
|
|
962
|
+
base.config = {
|
|
963
|
+
...(typeof src.config.modelRef === 'string' ? { modelRef: src.config.modelRef.trim() } : {}),
|
|
964
|
+
...(typeof src.config.sessionEnabled === 'boolean' ? { sessionEnabled: src.config.sessionEnabled } : {}),
|
|
965
|
+
permissionMode: rawPerm,
|
|
966
|
+
runMode: rm,
|
|
967
|
+
managedIdleTimeoutMs,
|
|
968
|
+
...(typeof src.config.notifyEnabled === 'boolean' ? { notifyEnabled: src.config.notifyEnabled } : {}),
|
|
969
|
+
...(typeof src.config.notifySound === 'boolean' ? { notifySound: src.config.notifySound } : {}),
|
|
970
|
+
...(typeof src.config.uiLang === 'string' ? { uiLang: normalizeUiLang(src.config.uiLang) } : {}),
|
|
971
|
+
...(src.config.managedBudgetMaxCalls !== undefined ? { managedBudgetMaxCalls: normalizeManagedBudgetCalls(src.config.managedBudgetMaxCalls) } : {}),
|
|
972
|
+
...(src.config.managedBudgetMaxTokens !== undefined ? { managedBudgetMaxTokens: normalizeManagedBudgetTokens(src.config.managedBudgetMaxTokens) } : {}),
|
|
973
|
+
...(typeof src.config.thinkingEffort === 'string' ? { thinkingEffort: normalizeThinkingEffort(src.config.thinkingEffort) } : {}),
|
|
974
|
+
...(typeof src.config.teamEffortMode === 'string' ? { teamEffortMode: normalizeTeamEffortMode(src.config.teamEffortMode) } : {}),
|
|
975
|
+
...(Object.keys(lockedModelEfforts).length ? { lockedModelEfforts } : {}),
|
|
976
|
+
...(typeof src.config.stopped === 'boolean' || pm === 'stopped' ? { stopped: rawStopped } : {}),
|
|
977
|
+
...(pm ? { paceMode: pm, autoPilot: !rawStopped && pm === 'auto', autoReview: !rawStopped && pm !== 'manual' } : {}),
|
|
978
|
+
...(policyPlugins.length > 0 ? { policyPlugins } : {}),
|
|
979
|
+
...(src.config.tacticalModes && typeof src.config.tacticalModes === 'object'
|
|
980
|
+
? { tacticalModes: normalizeTacticalModes(src.config.tacticalModes) }
|
|
981
|
+
: {}),
|
|
982
|
+
}
|
|
983
|
+
}
|
|
984
|
+
base.flippedPrecipitatedIds = Array.isArray(src.flippedPrecipitatedIds)
|
|
985
|
+
? [...new Set(src.flippedPrecipitatedIds.map(x => String(x || '').trim()).filter(Boolean))].slice(0, 20)
|
|
986
|
+
: []
|
|
987
|
+
base.llmLedger = normalizeLlmLedger(src.llmLedger)
|
|
988
|
+
base.alertEvents = (Array.isArray(src.alertEvents) ? src.alertEvents : [])
|
|
989
|
+
.map(normalizeAlertEvent)
|
|
990
|
+
.filter(Boolean)
|
|
991
|
+
.slice(-ALERT_EVENTS_CAP)
|
|
992
|
+
const rawHarnesses = Array.isArray(src.bubbleHarnesses) ? src.bubbleHarnesses : []
|
|
993
|
+
const seenHarnesses = new Set()
|
|
994
|
+
base.bubbleHarnesses = []
|
|
995
|
+
for (const hItem of rawHarnesses) {
|
|
996
|
+
const normH = normalizeBubbleHarness(hItem)
|
|
997
|
+
if (!normH || seenHarnesses.has(normH.provider)) continue
|
|
998
|
+
seenHarnesses.add(normH.provider)
|
|
999
|
+
base.bubbleHarnesses.push(normH)
|
|
1000
|
+
if (base.bubbleHarnesses.length >= 12) break
|
|
1001
|
+
}
|
|
1002
|
+
const rawBl = src.bubbleLock && typeof src.bubbleLock === 'object' ? src.bubbleLock : {}
|
|
1003
|
+
base.bubbleLock = {
|
|
1004
|
+
manualLocked: Boolean(rawBl.manualLocked),
|
|
1005
|
+
lockedAt: Math.max(0, Number(rawBl.lockedAt) || 0),
|
|
1006
|
+
reason: clamp(rawBl.reason || '', 120),
|
|
1007
|
+
}
|
|
1008
|
+
return base
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
export const COMPACT_THRESHOLD_MIN_PCT = 10
|
|
1012
|
+
|
|
1013
|
+
export const COMPACT_THRESHOLD_MAX_PCT = 95
|
|
1014
|
+
|
|
1015
|
+
export const COMPACT_PCT_WARN_FLOOR = 25
|
|
1016
|
+
|
|
1017
|
+
export const COMPACT_TOKEN_HARD_MIN = 8_000
|
|
1018
|
+
|
|
1019
|
+
export const COMPACT_TOKEN_WARN_FLOOR = 32_000
|
|
1020
|
+
|
|
1021
|
+
/** Format a token threshold cleanly into compact K/M display notation (e.g. `64K`, `1M`). */
|
|
1022
|
+
export function formatCompactTokenShort(tokens) {
|
|
1023
|
+
const n = Math.max(0, Math.round(Number(tokens) || 0))
|
|
1024
|
+
if (n >= 1_000_000 && n % 100_000 === 0) {
|
|
1025
|
+
const m = n / 1_000_000
|
|
1026
|
+
return (Number.isInteger(m) ? String(m) : m.toFixed(1).replace(/\.0$/, '')) + 'M'
|
|
1027
|
+
}
|
|
1028
|
+
if (n >= 1_000) {
|
|
1029
|
+
const k = n / 1_000
|
|
1030
|
+
return (k >= 100 ? String(Math.round(k)) : k.toFixed(1).replace(/\.0$/, '')) + 'K'
|
|
1031
|
+
}
|
|
1032
|
+
return String(n)
|
|
1033
|
+
}
|
|
1034
|
+
|
|
1035
|
+
/**
|
|
1036
|
+
* Parse custom context size threshold input (`'1M'` -> 1,000,000; `'64K'` -> 64,000; bare `'64'` -> `64K`).
|
|
1037
|
+
* Bare numbers without a unit default to K, and values below `32K` attach a low-threshold warning.
|
|
1038
|
+
*/
|
|
1039
|
+
export function parseCompactTokensInput(rawInput) {
|
|
1040
|
+
const s = String(rawInput ?? '').trim()
|
|
1041
|
+
if (!s) return { ok: false, error: '请输入上下文阈值,例如 64K、1M 或纯数字(无单位默认为 K)' }
|
|
1042
|
+
const m = s.match(/^(\d+(?:\.\d+)?)\s*(k|m|t|tokens?)?$/i)
|
|
1043
|
+
if (!m) return { ok: false, error: '格式无效:支持如 64K、1M 或纯数字(无单位默认为 K)' }
|
|
1044
|
+
const num = Number(m[1])
|
|
1045
|
+
if (!Number.isFinite(num) || num <= 0) return { ok: false, error: '上下文阈值必须大于 0' }
|
|
1046
|
+
const unit = (m[2] || 'k').toLowerCase()
|
|
1047
|
+
let rawTokens = 0
|
|
1048
|
+
if (unit === 'm') rawTokens = Math.round(num * 1_000_000)
|
|
1049
|
+
else if (unit === 'k') rawTokens = Math.round(num * 1_000)
|
|
1050
|
+
else rawTokens = Math.round(num)
|
|
1051
|
+
const tokens = Math.max(COMPACT_TOKEN_HARD_MIN, rawTokens)
|
|
1052
|
+
const displayInput = formatCompactTokenShort(tokens)
|
|
1053
|
+
const lowWarning = tokens < COMPACT_TOKEN_WARN_FLOOR
|
|
1054
|
+
? `当前阈值(${displayInput})低于安全建议线 32K,可能导致上下文频繁压缩丢失现场细节`
|
|
1055
|
+
: ''
|
|
1056
|
+
return {
|
|
1057
|
+
ok: true,
|
|
1058
|
+
tokens,
|
|
1059
|
+
rawTokens,
|
|
1060
|
+
clampedToMin: rawTokens < COMPACT_TOKEN_HARD_MIN,
|
|
1061
|
+
displayInput,
|
|
1062
|
+
lowWarning,
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
1065
|
+
|
|
1066
|
+
/**
|
|
1067
|
+
* Determine whether DSH Chief is active for a specific root session.
|
|
1068
|
+
* Priority: explicit per-session flag > legacy configured/populated workspace > global defaultAutoEnableSessions (default false).
|
|
1069
|
+
*/
|
|
1070
|
+
export function isChiefSessionEnabled(state, sessionId = '') {
|
|
1071
|
+
const safeState = state && typeof state === 'object' ? state : {}
|
|
1072
|
+
const base = safeState.config && typeof safeState.config === 'object' ? safeState.config : {}
|
|
1073
|
+
const sid = String(sessionId || '').trim()
|
|
1074
|
+
if (!sid || sid === 'global') return Boolean(base.defaultAutoEnableSessions === true)
|
|
1075
|
+
const ws = safeState.workspaces && safeState.workspaces[sid] ? safeState.workspaces[sid] : null
|
|
1076
|
+
const wsCfg = ws && ws.config && typeof ws.config === 'object' ? ws.config : null
|
|
1077
|
+
if (wsCfg && typeof wsCfg.sessionEnabled === 'boolean') {
|
|
1078
|
+
return wsCfg.sessionEnabled
|
|
1079
|
+
}
|
|
1080
|
+
if (wsCfg) return true
|
|
1081
|
+
if (
|
|
1082
|
+
ws
|
|
1083
|
+
&& (
|
|
1084
|
+
(Array.isArray(ws.chat) && ws.chat.length > 0)
|
|
1085
|
+
|| (Array.isArray(ws.facts) && ws.facts.length > 0)
|
|
1086
|
+
|| (Array.isArray(ws.mailbox) && ws.mailbox.length > 0)
|
|
1087
|
+
|| (Array.isArray(ws.bubbleHarnesses) && ws.bubbleHarnesses.length > 0)
|
|
1088
|
+
)
|
|
1089
|
+
) {
|
|
1090
|
+
return true
|
|
1091
|
+
}
|
|
1092
|
+
if (safeState.links && typeof safeState.links === 'object') {
|
|
1093
|
+
if (Array.isArray(safeState.links[sid]) && safeState.links[sid].length > 0) return true
|
|
1094
|
+
for (const arr of Object.values(safeState.links)) {
|
|
1095
|
+
if (Array.isArray(arr) && arr.includes(sid)) return true
|
|
1096
|
+
}
|
|
1097
|
+
}
|
|
1098
|
+
return Boolean(base.defaultAutoEnableSessions === true)
|
|
1099
|
+
}
|
|
1100
|
+
|
|
1101
|
+
/** Resolve effective Chief config for a specific root session (isolates `intervention` and `permissionMode` per session). */
|
|
1102
|
+
export function resolveWorkspaceConfig(state, sessionId = '') {
|
|
1103
|
+
const safeState = state && typeof state === 'object' ? state : {}
|
|
1104
|
+
const base = safeState.config && typeof safeState.config === 'object' ? safeState.config : {}
|
|
1105
|
+
const baseTactical = normalizeTacticalModes(base.tacticalModes)
|
|
1106
|
+
const sid = String(sessionId || '').trim()
|
|
1107
|
+
const ws = sid && safeState.workspaces && safeState.workspaces[sid] ? safeState.workspaces[sid] : null
|
|
1108
|
+
const wsCfg = ws && ws.config && typeof ws.config === 'object' ? ws.config : null
|
|
1109
|
+
const validPaces = ['manual', 'smart', 'auto', 'stopped']
|
|
1110
|
+
const basePaceSafe = validPaces.includes(base.paceMode) && !(sid && base.paceMode === 'auto')
|
|
1111
|
+
? base.paceMode
|
|
1112
|
+
: 'manual'
|
|
1113
|
+
const rawPaceMode = wsCfg && validPaces.includes(wsCfg.paceMode)
|
|
1114
|
+
? wsCfg.paceMode
|
|
1115
|
+
: basePaceSafe
|
|
1116
|
+
const explicitStopped = wsCfg && typeof wsCfg.stopped === 'boolean'
|
|
1117
|
+
? wsCfg.stopped
|
|
1118
|
+
: (typeof base.stopped === 'boolean' ? base.stopped : false)
|
|
1119
|
+
const stopped = rawPaceMode === 'stopped' || explicitStopped
|
|
1120
|
+
const paceMode = stopped ? 'stopped' : rawPaceMode
|
|
1121
|
+
const modelRef = wsCfg && typeof wsCfg.modelRef === 'string'
|
|
1122
|
+
? wsCfg.modelRef.trim()
|
|
1123
|
+
: (typeof base.modelRef === 'string' ? base.modelRef.trim() : '')
|
|
1124
|
+
const globalSafetyGuardEnabled = baseTactical.safetyGuardEnabled !== false
|
|
1125
|
+
const sessionSafetyGuardEnabled = !(wsCfg && wsCfg.tacticalModes && wsCfg.tacticalModes.safetyGuardEnabled === false)
|
|
1126
|
+
const mergedTactical = wsCfg && wsCfg.tacticalModes
|
|
1127
|
+
? normalizeTacticalModes({ ...baseTactical, ...wsCfg.tacticalModes })
|
|
1128
|
+
: { ...baseTactical, ...(sid ? { intervention: false } : {}) }
|
|
1129
|
+
mergedTactical.safetyGuardEnabled = globalSafetyGuardEnabled && sessionSafetyGuardEnabled
|
|
1130
|
+
const ackOk = hasValidChiefRiskAck(ws)
|
|
1131
|
+
const rawPerm = (wsCfg && typeof wsCfg.permissionMode === 'string')
|
|
1132
|
+
? wsCfg.permissionMode
|
|
1133
|
+
: DEFAULT_CHIEF_PERMISSION_MODE
|
|
1134
|
+
const globalPlugCheck = validatePolicyPluginList(base.policyPlugins)
|
|
1135
|
+
const wsPlugCheck = validatePolicyPluginList(wsCfg && wsCfg.policyPlugins)
|
|
1136
|
+
const policyPlugins = [
|
|
1137
|
+
...(globalPlugCheck.ok ? globalPlugCheck.plugins : []),
|
|
1138
|
+
...(wsPlugCheck.ok ? wsPlugCheck.plugins : []),
|
|
1139
|
+
]
|
|
1140
|
+
const resolvedRoleCaps = resolveRoleCapabilities(rawPerm, {
|
|
1141
|
+
hasChiefRiskAck: ackOk,
|
|
1142
|
+
policyPlugins,
|
|
1143
|
+
})
|
|
1144
|
+
const permissionMode = resolvedRoleCaps.role
|
|
1145
|
+
const chiefRiskVerified = permissionMode === 'chief' ? ackOk : false
|
|
1146
|
+
const runMode = stopped
|
|
1147
|
+
? 'off'
|
|
1148
|
+
: (wsCfg && typeof wsCfg.runMode === 'string' && CHIEF_RUN_MODES.includes(wsCfg.runMode)
|
|
1149
|
+
? wsCfg.runMode
|
|
1150
|
+
: normalizeRunMode(undefined, { stopped, paceMode, autoPilot: paceMode === 'auto' }))
|
|
1151
|
+
const thinkingEffort = normalizeThinkingEffort(
|
|
1152
|
+
(wsCfg && typeof wsCfg.thinkingEffort === 'string' && wsCfg.thinkingEffort)
|
|
1153
|
+
|| (typeof base.thinkingEffort === 'string' && base.thinkingEffort)
|
|
1154
|
+
|| 'auto',
|
|
1155
|
+
)
|
|
1156
|
+
const teamEffortMode = normalizeTeamEffortMode(
|
|
1157
|
+
(wsCfg && typeof wsCfg.teamEffortMode === 'string' && wsCfg.teamEffortMode)
|
|
1158
|
+
|| (typeof base.teamEffortMode === 'string' && base.teamEffortMode)
|
|
1159
|
+
|| 'auto',
|
|
1160
|
+
)
|
|
1161
|
+
const lockedModelEfforts = normalizeLockedModelEfforts(wsCfg && wsCfg.lockedModelEfforts)
|
|
1162
|
+
const managedIdleTimeoutMs = wsCfg && Number.isFinite(Number(wsCfg.managedIdleTimeoutMs)) && Number(wsCfg.managedIdleTimeoutMs) >= 50
|
|
1163
|
+
? Math.min(2 * 60 * 60 * 1000, Math.round(Number(wsCfg.managedIdleTimeoutMs)))
|
|
1164
|
+
: (Number.isFinite(Number(base.managedIdleTimeoutMs)) && Number(base.managedIdleTimeoutMs) >= 50
|
|
1165
|
+
? Math.min(2 * 60 * 60 * 1000, Math.round(Number(base.managedIdleTimeoutMs)))
|
|
1166
|
+
: DEFAULT_MANAGED_IDLE_TIMEOUT_MS)
|
|
1167
|
+
const notifyEnabled = typeof (wsCfg && wsCfg.notifyEnabled) === 'boolean'
|
|
1168
|
+
? wsCfg.notifyEnabled
|
|
1169
|
+
: (typeof base.notifyEnabled === 'boolean' ? base.notifyEnabled : true)
|
|
1170
|
+
const notifySound = typeof (wsCfg && wsCfg.notifySound) === 'boolean'
|
|
1171
|
+
? wsCfg.notifySound
|
|
1172
|
+
: (typeof base.notifySound === 'boolean' ? base.notifySound : false)
|
|
1173
|
+
const uiLang = normalizeUiLang(
|
|
1174
|
+
(wsCfg && typeof wsCfg.uiLang === 'string' && wsCfg.uiLang)
|
|
1175
|
+
|| (typeof base.uiLang === 'string' && base.uiLang)
|
|
1176
|
+
|| 'auto',
|
|
1177
|
+
)
|
|
1178
|
+
const managedBudgetMaxCalls = (wsCfg && wsCfg.managedBudgetMaxCalls !== undefined)
|
|
1179
|
+
? normalizeManagedBudgetCalls(wsCfg.managedBudgetMaxCalls)
|
|
1180
|
+
: (base.managedBudgetMaxCalls !== undefined
|
|
1181
|
+
? normalizeManagedBudgetCalls(base.managedBudgetMaxCalls)
|
|
1182
|
+
: DEFAULT_MANAGED_BUDGET_MAX_CALLS)
|
|
1183
|
+
const managedBudgetMaxTokens = (wsCfg && wsCfg.managedBudgetMaxTokens !== undefined)
|
|
1184
|
+
? normalizeManagedBudgetTokens(wsCfg.managedBudgetMaxTokens)
|
|
1185
|
+
: (base.managedBudgetMaxTokens !== undefined
|
|
1186
|
+
? normalizeManagedBudgetTokens(base.managedBudgetMaxTokens)
|
|
1187
|
+
: DEFAULT_MANAGED_BUDGET_MAX_TOKENS)
|
|
1188
|
+
return {
|
|
1189
|
+
modelRef,
|
|
1190
|
+
sessionEnabled: isChiefSessionEnabled(safeState, sid),
|
|
1191
|
+
defaultAutoEnableSessions: Boolean(base.defaultAutoEnableSessions === true),
|
|
1192
|
+
paceMode,
|
|
1193
|
+
runMode,
|
|
1194
|
+
managedIdleTimeoutMs,
|
|
1195
|
+
notifyEnabled,
|
|
1196
|
+
notifySound,
|
|
1197
|
+
uiLang,
|
|
1198
|
+
managedBudgetMaxCalls,
|
|
1199
|
+
managedBudgetMaxTokens,
|
|
1200
|
+
thinkingEffort,
|
|
1201
|
+
teamEffortMode,
|
|
1202
|
+
lockedModelEfforts,
|
|
1203
|
+
stopped,
|
|
1204
|
+
permissionMode,
|
|
1205
|
+
capabilities: resolvedRoleCaps.capabilities,
|
|
1206
|
+
policyPlugins,
|
|
1207
|
+
chiefRiskVerified,
|
|
1208
|
+
autoPilot: !stopped && runMode === 'managed',
|
|
1209
|
+
autoReview: !stopped && runMode === 'managed',
|
|
1210
|
+
globalSafetyGuardEnabled,
|
|
1211
|
+
sessionSafetyGuardEnabled,
|
|
1212
|
+
tacticalModes: mergedTactical,
|
|
1213
|
+
}
|
|
1214
|
+
}
|
|
1215
|
+
|
|
1216
|
+
export const DEFAULT_TACTICAL_MODES = {
|
|
1217
|
+
intervention: false,
|
|
1218
|
+
autoCompact: false,
|
|
1219
|
+
smartCompact: false,
|
|
1220
|
+
compactThresholdMode: 'pct',
|
|
1221
|
+
compactThresholdPct: 80,
|
|
1222
|
+
compactThresholdTokens: 64_000,
|
|
1223
|
+
compactThresholdInput: '64K',
|
|
1224
|
+
strictVerify: false,
|
|
1225
|
+
redlineSentinel: false,
|
|
1226
|
+
conciseBrief: false,
|
|
1227
|
+
safetyGuardEnabled: true,
|
|
1228
|
+
maxInterventionTurns: 10,
|
|
1229
|
+
}
|
|
1230
|
+
|
|
1231
|
+
export function normalizeTacticalModes(raw) {
|
|
1232
|
+
const src = raw && typeof raw === 'object' ? raw : {}
|
|
1233
|
+
const pct = Math.round(Number(src.compactThresholdPct) || DEFAULT_TACTICAL_MODES.compactThresholdPct)
|
|
1234
|
+
const mode = src.compactThresholdMode === 'tokens' ? 'tokens' : 'pct'
|
|
1235
|
+
const rawTokens = Math.round(Number(src.compactThresholdTokens) || DEFAULT_TACTICAL_MODES.compactThresholdTokens)
|
|
1236
|
+
const compactThresholdTokens = Math.max(COMPACT_TOKEN_HARD_MIN, rawTokens)
|
|
1237
|
+
const compactThresholdInput = typeof src.compactThresholdInput === 'string' && src.compactThresholdInput.trim()
|
|
1238
|
+
? src.compactThresholdInput.trim()
|
|
1239
|
+
: formatCompactTokenShort(compactThresholdTokens)
|
|
1240
|
+
const rawTurns = src.maxInterventionTurns
|
|
1241
|
+
const isZeroTurns = rawTurns === 0 || rawTurns === '0'
|
|
1242
|
+
const parsedTurns = isZeroTurns
|
|
1243
|
+
? 0
|
|
1244
|
+
: Math.min(30, Math.max(1, Math.round(Number(rawTurns) || DEFAULT_TACTICAL_MODES.maxInterventionTurns)))
|
|
1245
|
+
return {
|
|
1246
|
+
intervention: Boolean(src.intervention),
|
|
1247
|
+
autoCompact: Boolean(src.autoCompact),
|
|
1248
|
+
smartCompact: Boolean(src.smartCompact),
|
|
1249
|
+
compactThresholdMode: mode,
|
|
1250
|
+
compactThresholdPct: Math.min(COMPACT_THRESHOLD_MAX_PCT, Math.max(COMPACT_THRESHOLD_MIN_PCT, pct)),
|
|
1251
|
+
compactThresholdTokens,
|
|
1252
|
+
compactThresholdInput,
|
|
1253
|
+
strictVerify: Boolean(src.strictVerify),
|
|
1254
|
+
redlineSentinel: Boolean(src.redlineSentinel),
|
|
1255
|
+
conciseBrief: Boolean(src.conciseBrief),
|
|
1256
|
+
safetyGuardEnabled: src.safetyGuardEnabled !== false,
|
|
1257
|
+
maxInterventionTurns: parsedTurns,
|
|
1258
|
+
}
|
|
1259
|
+
}
|
|
1260
|
+
|
|
1261
|
+
export function normalizeState(raw) {
|
|
1262
|
+
const src = raw && typeof raw === 'object' ? raw : {}
|
|
1263
|
+
const cfg = src.config && typeof src.config === 'object' ? src.config : {}
|
|
1264
|
+
const links = {}
|
|
1265
|
+
if (src.links && typeof src.links === 'object') {
|
|
1266
|
+
for (const [k, list] of Object.entries(src.links)) {
|
|
1267
|
+
if (!k || !Array.isArray(list)) continue
|
|
1268
|
+
const clean = [...new Set(list.map(v => String(v || '').trim()).filter(v => v && v !== k))]
|
|
1269
|
+
if (clean.length) links[k] = clean
|
|
1270
|
+
}
|
|
1271
|
+
}
|
|
1272
|
+
const workspaces = {}
|
|
1273
|
+
if (src.workspaces && typeof src.workspaces === 'object') {
|
|
1274
|
+
for (const [k, ws] of Object.entries(src.workspaces)) {
|
|
1275
|
+
if (!k) continue
|
|
1276
|
+
workspaces[k] = normalizeWorkspace(ws)
|
|
1277
|
+
}
|
|
1278
|
+
}
|
|
1279
|
+
const validPaces = ['manual', 'smart', 'auto', 'stopped']
|
|
1280
|
+
// Default to 'manual' (human-paced, zero background token burn) unless explicitly set to smart/auto
|
|
1281
|
+
const rawPace = validPaces.includes(cfg.paceMode) ? cfg.paceMode : 'manual'
|
|
1282
|
+
const stopped = rawPace === 'stopped' || Boolean(cfg.stopped)
|
|
1283
|
+
const paceMode = stopped ? 'stopped' : rawPace
|
|
1284
|
+
const globalPlugRes = validatePolicyPluginList(cfg.policyPlugins)
|
|
1285
|
+
return {
|
|
1286
|
+
version: STATE_VERSION,
|
|
1287
|
+
config: {
|
|
1288
|
+
modelRef: typeof cfg.modelRef === 'string' ? cfg.modelRef.trim() : '',
|
|
1289
|
+
defaultAutoEnableSessions: Boolean(cfg.defaultAutoEnableSessions),
|
|
1290
|
+
paceMode,
|
|
1291
|
+
runMode: stopped ? 'off' : normalizeRunMode(cfg.runMode, { stopped, paceMode }),
|
|
1292
|
+
managedIdleTimeoutMs: Number.isFinite(Number(cfg.managedIdleTimeoutMs)) && Number(cfg.managedIdleTimeoutMs) >= 50
|
|
1293
|
+
? Math.min(2 * 60 * 60 * 1000, Math.round(Number(cfg.managedIdleTimeoutMs)))
|
|
1294
|
+
: DEFAULT_MANAGED_IDLE_TIMEOUT_MS,
|
|
1295
|
+
notifyEnabled: typeof cfg.notifyEnabled === 'boolean' ? cfg.notifyEnabled : true,
|
|
1296
|
+
notifySound: typeof cfg.notifySound === 'boolean' ? cfg.notifySound : false,
|
|
1297
|
+
uiLang: normalizeUiLang(cfg.uiLang),
|
|
1298
|
+
managedBudgetMaxCalls: normalizeManagedBudgetCalls(cfg.managedBudgetMaxCalls),
|
|
1299
|
+
managedBudgetMaxTokens: normalizeManagedBudgetTokens(cfg.managedBudgetMaxTokens),
|
|
1300
|
+
thinkingEffort: normalizeThinkingEffort(cfg.thinkingEffort),
|
|
1301
|
+
teamEffortMode: normalizeTeamEffortMode(cfg.teamEffortMode),
|
|
1302
|
+
stopped,
|
|
1303
|
+
permissionMode: DEFAULT_CHIEF_PERMISSION_MODE,
|
|
1304
|
+
autoPilot: !stopped && paceMode === 'auto',
|
|
1305
|
+
autoReview: !stopped && paceMode !== 'manual',
|
|
1306
|
+
...(globalPlugRes.ok && globalPlugRes.plugins.length > 0 ? { policyPlugins: globalPlugRes.plugins } : {}),
|
|
1307
|
+
tacticalModes: normalizeTacticalModes(cfg.tacticalModes),
|
|
1308
|
+
},
|
|
1309
|
+
links,
|
|
1310
|
+
workspaces,
|
|
1311
|
+
}
|
|
1312
|
+
}
|
|
1313
|
+
|
|
1314
|
+
|
|
1315
|
+
export function shortAgentBriefName(name) {
|
|
1316
|
+
const raw = String(name || '').trim()
|
|
1317
|
+
if (!raw) return ''
|
|
1318
|
+
return raw
|
|
1319
|
+
.split('/')
|
|
1320
|
+
.map(seg => seg.replace(/[-_]([0-9a-f]{8,40})$/i, (_, hex) => '·' + hex.slice(0, 4)))
|
|
1321
|
+
.join('/')
|
|
1322
|
+
}
|
|
1323
|
+
|
|
1324
|
+
export function stripCheckpointNoise(text) {
|
|
1325
|
+
return String(text || '')
|
|
1326
|
+
.replace(/\[dsh-mnemon:[^\]]*\][\s\S]*/gi, '')
|
|
1327
|
+
.replace(/Bounded completed checkpoint[\s\S]*/gi, '')
|
|
1328
|
+
.replace(/\s+/g, ' ')
|
|
1329
|
+
.trim()
|
|
1330
|
+
}
|
|
1331
|
+
|
|
1332
|
+
export function isInternalCheckpointNoise(text) {
|
|
1333
|
+
const s = stripCheckpointNoise(text)
|
|
1334
|
+
if (!s) return true
|
|
1335
|
+
if (/^Mnemon idle checkpoint review\b/i.test(s)) return true
|
|
1336
|
+
return false
|
|
1337
|
+
}
|
|
1338
|
+
|
|
1339
|
+
export function repairJsonInvalidEscapes(jsonStr) {
|
|
1340
|
+
let out = ''
|
|
1341
|
+
let inString = false
|
|
1342
|
+
for (let i = 0; i < jsonStr.length; i += 1) {
|
|
1343
|
+
const ch = jsonStr[i]
|
|
1344
|
+
if (!inString) {
|
|
1345
|
+
if (ch === '"') inString = true
|
|
1346
|
+
out += ch
|
|
1347
|
+
continue
|
|
1348
|
+
}
|
|
1349
|
+
if (ch === '"') {
|
|
1350
|
+
inString = false
|
|
1351
|
+
out += ch
|
|
1352
|
+
continue
|
|
1353
|
+
}
|
|
1354
|
+
if (ch === '\\') {
|
|
1355
|
+
const next = jsonStr[i + 1]
|
|
1356
|
+
if (next === undefined) {
|
|
1357
|
+
out += '\\\\'
|
|
1358
|
+
continue
|
|
1359
|
+
}
|
|
1360
|
+
if (next === 'u' && /^[0-9a-fA-F]{4}$/.test(jsonStr.slice(i + 2, i + 6))) {
|
|
1361
|
+
out += jsonStr.slice(i, i + 6)
|
|
1362
|
+
i += 5
|
|
1363
|
+
continue
|
|
1364
|
+
}
|
|
1365
|
+
if ('"\\/bfnrt'.includes(next)) {
|
|
1366
|
+
out += '\\' + next
|
|
1367
|
+
i += 1
|
|
1368
|
+
continue
|
|
1369
|
+
}
|
|
1370
|
+
// Escape invalid bare backslash (e.g. regex \s, \., Windows D:\path) inside JSON strings
|
|
1371
|
+
out += '\\\\'
|
|
1372
|
+
continue
|
|
1373
|
+
}
|
|
1374
|
+
out += ch
|
|
1375
|
+
}
|
|
1376
|
+
return out
|
|
1377
|
+
}
|
|
1378
|
+
|
|
1379
|
+
export function tryParseJsonRobust(candidate) {
|
|
1380
|
+
if (!candidate) return null
|
|
1381
|
+
try {
|
|
1382
|
+
const parsed = JSON.parse(candidate)
|
|
1383
|
+
if (parsed && typeof parsed === 'object') return parsed
|
|
1384
|
+
} catch {}
|
|
1385
|
+
try {
|
|
1386
|
+
const repaired = repairJsonInvalidEscapes(candidate)
|
|
1387
|
+
const parsed = JSON.parse(repaired)
|
|
1388
|
+
if (parsed && typeof parsed === 'object') return parsed
|
|
1389
|
+
} catch {}
|
|
1390
|
+
return null
|
|
1391
|
+
}
|
|
1392
|
+
|
|
1393
|
+
export function extractJsonObject(raw) {
|
|
1394
|
+
const text = String(raw || '').trim()
|
|
1395
|
+
if (!text) return null
|
|
1396
|
+
const stripped = text.replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/i, '').trim()
|
|
1397
|
+
const direct = tryParseJsonRobust(stripped)
|
|
1398
|
+
if (direct) return direct
|
|
1399
|
+
const first = text.indexOf('{')
|
|
1400
|
+
const last = text.lastIndexOf('}')
|
|
1401
|
+
if (first !== -1 && last > first) {
|
|
1402
|
+
const sliced = tryParseJsonRobust(text.slice(first, last + 1))
|
|
1403
|
+
if (sliced) return sliced
|
|
1404
|
+
}
|
|
1405
|
+
return null
|
|
1406
|
+
}
|
|
1407
|
+
|
|
1408
|
+
const activeChiefWorkMap = new Map()
|
|
1409
|
+
const ACTIVE_CHIEF_WORK_TTL_MS = 90_000
|
|
1410
|
+
|
|
1411
|
+
export function beginChiefActiveWork(rootSessionId, spec = {}) {
|
|
1412
|
+
const key = String(rootSessionId || 'global').trim() || 'global'
|
|
1413
|
+
const id = 'cwork-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 6)
|
|
1414
|
+
activeChiefWorkMap.set(key, {
|
|
1415
|
+
id,
|
|
1416
|
+
tone: String(spec.tone || 'neon'),
|
|
1417
|
+
tab: String(spec.tab || ''),
|
|
1418
|
+
boundSubTab: String(spec.boundSubTab || ''),
|
|
1419
|
+
label: String(spec.label || '参谋长正在自动维护中...'),
|
|
1420
|
+
startedAt: Date.now(),
|
|
1421
|
+
})
|
|
1422
|
+
return id
|
|
1423
|
+
}
|
|
1424
|
+
|
|
1425
|
+
export function updateChiefActiveWork(rootSessionId, workId, patchSpec = {}) {
|
|
1426
|
+
const key = String(rootSessionId || 'global').trim() || 'global'
|
|
1427
|
+
const cur = activeChiefWorkMap.get(key)
|
|
1428
|
+
if (!cur || (workId && cur.id !== workId)) return false
|
|
1429
|
+
activeChiefWorkMap.set(key, {
|
|
1430
|
+
...cur,
|
|
1431
|
+
...(patchSpec.tone ? { tone: String(patchSpec.tone) } : {}),
|
|
1432
|
+
...(patchSpec.tab !== undefined ? { tab: String(patchSpec.tab || '') } : {}),
|
|
1433
|
+
...(patchSpec.boundSubTab !== undefined ? { boundSubTab: String(patchSpec.boundSubTab || '') } : {}),
|
|
1434
|
+
...(patchSpec.label ? { label: String(patchSpec.label) } : {}),
|
|
1435
|
+
})
|
|
1436
|
+
return true
|
|
1437
|
+
}
|
|
1438
|
+
|
|
1439
|
+
export function endChiefActiveWork(rootSessionId, workId = '') {
|
|
1440
|
+
const key = String(rootSessionId || 'global').trim() || 'global'
|
|
1441
|
+
const cur = activeChiefWorkMap.get(key)
|
|
1442
|
+
if (!cur) return false
|
|
1443
|
+
if (workId && cur.id !== workId) return false
|
|
1444
|
+
activeChiefWorkMap.delete(key)
|
|
1445
|
+
return true
|
|
1446
|
+
}
|
|
1447
|
+
|
|
1448
|
+
export function getChiefActiveWork(rootSessionId) {
|
|
1449
|
+
const key = String(rootSessionId || 'global').trim() || 'global'
|
|
1450
|
+
const cur = activeChiefWorkMap.get(key)
|
|
1451
|
+
if (!cur) return null
|
|
1452
|
+
if (Date.now() - Number(cur.startedAt || 0) > ACTIVE_CHIEF_WORK_TTL_MS) {
|
|
1453
|
+
activeChiefWorkMap.delete(key)
|
|
1454
|
+
return null
|
|
1455
|
+
}
|
|
1456
|
+
return { ...cur }
|
|
1457
|
+
}
|
|
1458
|
+
|
|
1459
|
+
/** Persist a critical alert event onto a workspace so UI can fire desktop notifications / gentle chimes without replay storms. */
|
|
1460
|
+
|
|
1461
|
+
export const OFFICIAL_HARNESS_CATALOG = [
|
|
1462
|
+
{
|
|
1463
|
+
provider: 'codex',
|
|
1464
|
+
label: 'Codex',
|
|
1465
|
+
packageName: '@deepseek-ai/dsh-subagent-codex',
|
|
1466
|
+
accent: '#10b981',
|
|
1467
|
+
roleHint: '独立代码实现 / 重构 / 单测',
|
|
1468
|
+
},
|
|
1469
|
+
{
|
|
1470
|
+
provider: 'claude-code',
|
|
1471
|
+
label: 'Claude Code',
|
|
1472
|
+
packageName: '@deepseek-ai/dsh-subagent-claude-code',
|
|
1473
|
+
accent: '#f59e0b',
|
|
1474
|
+
roleHint: '架构审查 / 深度排障 / 代码评审',
|
|
1475
|
+
},
|
|
1476
|
+
{
|
|
1477
|
+
provider: 'acp',
|
|
1478
|
+
label: 'ACP Agent',
|
|
1479
|
+
packageName: '@deepseek-ai/dsh-subagent-acp',
|
|
1480
|
+
accent: '#a855f7',
|
|
1481
|
+
roleHint: '通用 ACP 外部 Harness 进程',
|
|
1482
|
+
},
|
|
1483
|
+
{
|
|
1484
|
+
provider: 'dsh-sdk',
|
|
1485
|
+
label: 'DSH Sub-Instance',
|
|
1486
|
+
packageName: '@deepseek-ai/dsh-subagent-dsh-sdk',
|
|
1487
|
+
accent: '#38bdf8',
|
|
1488
|
+
roleHint: '独立 Profile / 模型 DSH 子实例',
|
|
1489
|
+
},
|
|
1490
|
+
]
|
|
1491
|
+
|
|
1492
|
+
export function normalizeBubbleHarness(raw) {
|
|
1493
|
+
if (!raw || typeof raw !== 'object') return null
|
|
1494
|
+
const provider = clamp(String(raw.provider || '').trim(), 64)
|
|
1495
|
+
if (!provider || provider === 'spawn' || provider === 'fork') return null
|
|
1496
|
+
const meta = OFFICIAL_HARNESS_CATALOG.find(item => item.provider === provider)
|
|
1497
|
+
return {
|
|
1498
|
+
provider,
|
|
1499
|
+
label: clamp(raw.label || (meta ? meta.label : provider), 48),
|
|
1500
|
+
role: clamp(raw.role || (meta ? meta.roleHint : '外部 Harness 协同成员'), 90),
|
|
1501
|
+
accent: (meta && meta.accent) || '#38bdf8',
|
|
1502
|
+
joinedAt: Math.max(0, Number(raw.joinedAt) || Date.now()),
|
|
1503
|
+
}
|
|
1504
|
+
}
|
|
1505
|
+
|