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/command-ops.js
ADDED
|
@@ -0,0 +1,1226 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* command-ops.js — 参谋建议落地执行器(Fact / Board / Archive / Network)、边界归并、目标建议与 Lead 直连处理
|
|
3
|
+
*
|
|
4
|
+
* 【核心职责】
|
|
5
|
+
* 1. 提供 `applyFactChanges`、`applyBoardOps`、`executeChiefArchiveInjectionOp`、`applyArchiveOps`、
|
|
6
|
+
* `applyNetworkOps` 等原子落盘动作,供 `askOrCommandChief` 与自动审阅复用。
|
|
7
|
+
* 2. 提供 `consolidateBoundsWithChief`、`proposeBoundToChief` 与 `suggestCoreObjectiveWithChief`。
|
|
8
|
+
* 3. 承载 `handleLeadDirectRequestToChief`(主代理 `chief.request` / 邮箱直传参谋长分档处置)及
|
|
9
|
+
* `registerAskOrCommandChiefRunner` 回调注入。
|
|
10
|
+
*
|
|
11
|
+
* 【边界约定】
|
|
12
|
+
* - 依赖 `command-helpers.js` 与底层领域模块,绝不反向依赖 `chief-commands.js`。
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import {
|
|
16
|
+
loadArchiveStore,
|
|
17
|
+
getArchiveDetail,
|
|
18
|
+
mutateArchive,
|
|
19
|
+
} from './archives.js'
|
|
20
|
+
import {
|
|
21
|
+
DEFAULT_CHIEF_PERMISSION_MODE,
|
|
22
|
+
CHIEF_PERMISSION_META,
|
|
23
|
+
normalizePermissionMode,
|
|
24
|
+
permissionRank,
|
|
25
|
+
buildCapabilityScope,
|
|
26
|
+
listGuardWalls,
|
|
27
|
+
stripToolCallMarkup,
|
|
28
|
+
} from './chief-executor.js'
|
|
29
|
+
import {
|
|
30
|
+
FACTS_CAP,
|
|
31
|
+
FACT_TEXT_MAX,
|
|
32
|
+
CHAT_CAP,
|
|
33
|
+
SUGGESTIONS_CAP,
|
|
34
|
+
SUMMARY_MAX_TOKENS,
|
|
35
|
+
archiveTargetForRoot,
|
|
36
|
+
nextId,
|
|
37
|
+
hasValidChiefRiskAck,
|
|
38
|
+
queueChiefApproval,
|
|
39
|
+
requestChiefElevation,
|
|
40
|
+
upsertTaskLedgerOnWs,
|
|
41
|
+
resolveSessionWorkspaceCwd,
|
|
42
|
+
clamp,
|
|
43
|
+
cleanMultiline,
|
|
44
|
+
secretLike,
|
|
45
|
+
normalizeFact,
|
|
46
|
+
normalizeSuggestion,
|
|
47
|
+
resolveWorkspaceConfig,
|
|
48
|
+
loadChiefState,
|
|
49
|
+
mutateChiefState,
|
|
50
|
+
setPeerLink,
|
|
51
|
+
ensureWorkspace,
|
|
52
|
+
clusterView,
|
|
53
|
+
extractJsonObject,
|
|
54
|
+
beginChiefActiveWork,
|
|
55
|
+
endChiefActiveWork,
|
|
56
|
+
} from './chief-state.js'
|
|
57
|
+
import { callChiefLlm } from './chief-models.js'
|
|
58
|
+
import { listPeerDirectory, deliverCrossMessage } from './chief-network.js'
|
|
59
|
+
import { getChiefView } from './chief-view.js'
|
|
60
|
+
import { organizeArchivesWithChief, distillSessionArchivesToGlobal } from './chief-archives.js'
|
|
61
|
+
import { CONSOLIDATE_BOUNDS_SYSTEM, collectLiveConversationsDigest, deterministicConsolidateClauses, OBJECTIVE_SUGGEST_SYSTEM } from './command-helpers.js'
|
|
62
|
+
|
|
63
|
+
let askOrCommandChiefRunner = null
|
|
64
|
+
|
|
65
|
+
/** Register `askOrCommandChief` executor from `chief-commands.js` without creating a circular ESM import. */
|
|
66
|
+
export function registerAskOrCommandChiefRunner(fn) {
|
|
67
|
+
askOrCommandChiefRunner = typeof fn === 'function' ? fn : null
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function applyFactChanges(ws, numberedFacts, changes, actor = 'user', meta = {}) {
|
|
71
|
+
const applied = []
|
|
72
|
+
if (!Array.isArray(changes) || !changes.length) return applied
|
|
73
|
+
const originRootId = typeof meta.originRootId === 'string' ? meta.originRootId : ''
|
|
74
|
+
const clusterRoots = Array.isArray(meta.peerRootIds) ? meta.peerRootIds : []
|
|
75
|
+
|
|
76
|
+
for (const ch of changes.slice(0, 12)) {
|
|
77
|
+
if (!ch || typeof ch !== 'object') continue
|
|
78
|
+
const op = String(ch.op || '').trim()
|
|
79
|
+
if (op === 'add') {
|
|
80
|
+
const category = ch.category || 'discipline'
|
|
81
|
+
const fact = normalizeFact({
|
|
82
|
+
text: ch.text,
|
|
83
|
+
category,
|
|
84
|
+
by: actor,
|
|
85
|
+
source: 'chief',
|
|
86
|
+
originRootId: originRootId && originRootId !== 'global' ? originRootId : '',
|
|
87
|
+
peerRootIds: category === 'team' ? clusterRoots : [],
|
|
88
|
+
})
|
|
89
|
+
if (!fact) continue
|
|
90
|
+
const dup = ws.facts.find(f => f.text === fact.text)
|
|
91
|
+
if (dup) {
|
|
92
|
+
dup.updatedAt = Date.now()
|
|
93
|
+
continue
|
|
94
|
+
}
|
|
95
|
+
ws.facts.push(fact)
|
|
96
|
+
if (ws.facts.length > FACTS_CAP) ws.facts = ws.facts.slice(-FACTS_CAP)
|
|
97
|
+
applied.push({ op: 'add', text: fact.text })
|
|
98
|
+
} else if (op === 'edit') {
|
|
99
|
+
const target = numberedFacts[Number(ch.index) - 1]
|
|
100
|
+
const nextText = clamp(ch.text, FACT_TEXT_MAX)
|
|
101
|
+
if (!target || !nextText || secretLike(nextText)) continue
|
|
102
|
+
const found = ws.facts.find(f => f.id === target.id)
|
|
103
|
+
if (found && !found.pinned) {
|
|
104
|
+
found.text = nextText
|
|
105
|
+
found.updatedAt = Date.now()
|
|
106
|
+
applied.push({ op: 'edit', text: nextText })
|
|
107
|
+
}
|
|
108
|
+
} else if (op === 'remove') {
|
|
109
|
+
const target = numberedFacts[Number(ch.index) - 1]
|
|
110
|
+
if (!target) continue
|
|
111
|
+
const idx = ws.facts.findIndex(f => f.id === target.id)
|
|
112
|
+
if (idx !== -1 && !ws.facts[idx].pinned) {
|
|
113
|
+
const [removed] = ws.facts.splice(idx, 1)
|
|
114
|
+
applied.push({ op: 'remove', text: removed.text })
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return applied
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export function applyBoardOps(deps, rootId, boardOps, opts = {}) {
|
|
122
|
+
const executed = []
|
|
123
|
+
if (!Array.isArray(boardOps) || !boardOps.length || !deps || typeof deps.runAction !== 'function') return executed
|
|
124
|
+
const forceSessionOnly = Boolean(opts && opts.forceSessionOnly)
|
|
125
|
+
const allowLockedObjectiveWrite = Boolean(opts && opts.allowLockedObjectiveWrite)
|
|
126
|
+
const callerOrigin = String((opts && opts.callerOrigin) || 'chief_llm')
|
|
127
|
+
const effCfg = resolveWorkspaceConfig(loadChiefState(), rootId)
|
|
128
|
+
const objectiveLocked = Boolean(effCfg && effCfg.tacticalModes && effCfg.tacticalModes.intervention) && !allowLockedObjectiveWrite
|
|
129
|
+
|
|
130
|
+
for (const opItem of boardOps.slice(0, 10)) {
|
|
131
|
+
if (!opItem || typeof opItem !== 'object') continue
|
|
132
|
+
const op = String(opItem.op || '').trim()
|
|
133
|
+
if (op === 'objective.set' && opItem.objective) {
|
|
134
|
+
if (objectiveLocked) {
|
|
135
|
+
executed.push('核心目标已锁定(强介入进行中,跳过改写)')
|
|
136
|
+
continue
|
|
137
|
+
}
|
|
138
|
+
deps.runAction({ action: 'objective.set', objective: String(opItem.objective), session: rootId, by: 'chief' })
|
|
139
|
+
executed.push('更新目标:' + clamp(opItem.objective, 40))
|
|
140
|
+
} else if (op === 'task.add' && opItem.title) {
|
|
141
|
+
deps.runAction({
|
|
142
|
+
action: 'task.add',
|
|
143
|
+
title: String(opItem.title),
|
|
144
|
+
owner: opItem.owner ? String(opItem.owner) : '',
|
|
145
|
+
subagent: opItem.owner ? String(opItem.owner) : '',
|
|
146
|
+
priority: opItem.priority || 'normal',
|
|
147
|
+
session: rootId,
|
|
148
|
+
by: 'chief',
|
|
149
|
+
})
|
|
150
|
+
executed.push('新增任务:' + clamp(opItem.title, 40))
|
|
151
|
+
} else if (op === 'task.update' && (opItem.id || opItem.taskId)) {
|
|
152
|
+
const tid = String(opItem.id || opItem.taskId).trim()
|
|
153
|
+
const res = deps.runAction({
|
|
154
|
+
action: 'task.update',
|
|
155
|
+
id: tid,
|
|
156
|
+
...(typeof opItem.status === 'string' ? { status: opItem.status } : {}),
|
|
157
|
+
...(typeof opItem.note === 'string' ? { note: opItem.note } : {}),
|
|
158
|
+
...(typeof opItem.evidence === 'string' ? { evidence: opItem.evidence } : {}),
|
|
159
|
+
...(typeof opItem.owner === 'string' ? { owner: opItem.owner } : {}),
|
|
160
|
+
session: rootId,
|
|
161
|
+
by: 'chief',
|
|
162
|
+
})
|
|
163
|
+
if (res && res.ok) executed.push(`更新任务 #${tid}${opItem.status ? ' → ' + opItem.status : ''}`)
|
|
164
|
+
} else if (op === 'task.remove' && (opItem.id || opItem.taskId)) {
|
|
165
|
+
const tid = String(opItem.id || opItem.taskId).trim()
|
|
166
|
+
const res = deps.runAction({ action: 'task.remove', id: tid, session: rootId, by: 'chief' })
|
|
167
|
+
if (res && res.ok) executed.push(`移除任务 #${tid}`)
|
|
168
|
+
} else if (op === 'task.reset') {
|
|
169
|
+
const res = deps.runAction({
|
|
170
|
+
action: 'task.reset',
|
|
171
|
+
...(typeof opItem.status === 'string' ? { status: opItem.status } : {}),
|
|
172
|
+
...(opItem.resetPlan !== undefined ? { resetPlan: Boolean(opItem.resetPlan) } : {}),
|
|
173
|
+
session: rootId,
|
|
174
|
+
by: 'chief',
|
|
175
|
+
})
|
|
176
|
+
if (res && res.ok) executed.push(`重设任务看板(${res.removedCount ?? 0}项)`)
|
|
177
|
+
} else if ((op === 'graph.plan' || op === 'task.batch') && Array.isArray(opItem.tasks) && opItem.tasks.length > 0) {
|
|
178
|
+
const canSetObj = !objectiveLocked && typeof opItem.objective === 'string' && opItem.objective.trim()
|
|
179
|
+
const res = deps.runAction({
|
|
180
|
+
action: 'graph.plan',
|
|
181
|
+
tasks: opItem.tasks,
|
|
182
|
+
...(canSetObj ? { objective: opItem.objective } : {}),
|
|
183
|
+
...(opItem.replace !== undefined ? { replace: Boolean(opItem.replace) } : {}),
|
|
184
|
+
session: rootId,
|
|
185
|
+
by: 'chief',
|
|
186
|
+
})
|
|
187
|
+
if (res && res.ok) executed.push(`重编任务拓扑(${(res.tasks || opItem.tasks).length}项)`)
|
|
188
|
+
} else if (op === 'cursor.set') {
|
|
189
|
+
const res = deps.runAction({
|
|
190
|
+
action: 'cursor.set',
|
|
191
|
+
...(typeof opItem.step === 'string' ? { step: opItem.step } : {}),
|
|
192
|
+
...(typeof opItem.next === 'string' ? { next: opItem.next } : {}),
|
|
193
|
+
...(typeof opItem.blocked === 'string' ? { blocked: opItem.blocked } : {}),
|
|
194
|
+
session: rootId,
|
|
195
|
+
by: 'chief',
|
|
196
|
+
})
|
|
197
|
+
if (res && res.ok) executed.push('更新推进断点')
|
|
198
|
+
} else if (op === 'plan.resetForGoal') {
|
|
199
|
+
const res = deps.runAction({ action: 'plan.resetForGoal', session: rootId, by: 'chief' })
|
|
200
|
+
if (res && res.ok) executed.push('清空陈旧计划以便按新目标重编')
|
|
201
|
+
} else if (op === 'plan.set' && Array.isArray(opItem.steps)) {
|
|
202
|
+
const steps = opItem.steps.map(s => (typeof s === 'string' ? { text: s, done: false } : s)).filter(Boolean)
|
|
203
|
+
if (steps.length > 0) {
|
|
204
|
+
const res = deps.runAction({ action: 'plan.set', steps, session: rootId, by: 'chief' })
|
|
205
|
+
if (res && res.ok) executed.push(`更新计划共 ${steps.length} 步`)
|
|
206
|
+
}
|
|
207
|
+
} else if (op === 'goal.proposeApproval') {
|
|
208
|
+
const res = deps.runAction({
|
|
209
|
+
action: 'goal.proposeApproval',
|
|
210
|
+
objective: String(opItem.objective || ''),
|
|
211
|
+
summary: String(opItem.summary || ''),
|
|
212
|
+
evidence: String(opItem.evidence || ''),
|
|
213
|
+
session: rootId,
|
|
214
|
+
by: 'chief',
|
|
215
|
+
})
|
|
216
|
+
if (res && res.ok) executed.push('呈批目标结项')
|
|
217
|
+
} else if (op === 'bounds.set') {
|
|
218
|
+
const rawField = String(opItem.field || '').trim().toLowerCase()
|
|
219
|
+
const normField = rawField === 'must' ? 'allowed' : rawField
|
|
220
|
+
const col = ['forbidden', 'allowed', 'notes'].includes(normField) ? normField : ''
|
|
221
|
+
if (col && Array.isArray(opItem.items)) {
|
|
222
|
+
const items = opItem.items.map(x => clamp(x, 220)).filter(Boolean)
|
|
223
|
+
const res = deps.runAction({ action: 'bounds.set', field: col, items, session: rootId, by: 'chief', _callerOrigin: callerOrigin })
|
|
224
|
+
if (res && res.ok) executed.push(`覆写边界(${col})共 ${items.length} 条`)
|
|
225
|
+
else if (res && res.blockedBySafetyGuard) executed.push(`🛡️ 已拦截覆写红线(${col})`)
|
|
226
|
+
} else if (Array.isArray(opItem.allowed) || Array.isArray(opItem.must) || Array.isArray(opItem.forbidden) || Array.isArray(opItem.notes)) {
|
|
227
|
+
const allowList = Array.isArray(opItem.allowed) ? opItem.allowed : opItem.must
|
|
228
|
+
const res = deps.runAction({
|
|
229
|
+
action: 'bounds.set',
|
|
230
|
+
...(Array.isArray(allowList) ? { allowed: allowList.map(x => clamp(x, 220)).filter(Boolean) } : {}),
|
|
231
|
+
...(Array.isArray(opItem.forbidden) ? { forbidden: opItem.forbidden.map(x => clamp(x, 220)).filter(Boolean) } : {}),
|
|
232
|
+
...(Array.isArray(opItem.notes) ? { notes: opItem.notes.map(x => clamp(x, 220)).filter(Boolean) } : {}),
|
|
233
|
+
session: rootId,
|
|
234
|
+
by: 'chief',
|
|
235
|
+
_callerOrigin: callerOrigin,
|
|
236
|
+
})
|
|
237
|
+
if (res && res.ok) executed.push('重置边界列表')
|
|
238
|
+
else if (res && res.blockedBySafetyGuard) executed.push('🛡️ 已拦截批量覆写边界')
|
|
239
|
+
}
|
|
240
|
+
} else if ((op === 'bounds.forbid' || op === 'bounds.allow' || op === 'bounds.must' || op === 'bounds.note') && opItem.item) {
|
|
241
|
+
const field = op === 'bounds.forbid' ? 'forbidden' : (op === 'bounds.note' ? 'notes' : 'allowed')
|
|
242
|
+
const label = field === 'forbidden' ? '红线' : (field === 'notes' ? '注意' : '必做')
|
|
243
|
+
const val = clamp(opItem.item, 220)
|
|
244
|
+
const pinned = forceSessionOnly ? false : Boolean(opItem.pinGlobal)
|
|
245
|
+
if (val) {
|
|
246
|
+
const res = deps.runAction({
|
|
247
|
+
action: 'bounds.add',
|
|
248
|
+
field,
|
|
249
|
+
item: val,
|
|
250
|
+
pinned,
|
|
251
|
+
session: rootId,
|
|
252
|
+
by: 'chief',
|
|
253
|
+
_callerOrigin: callerOrigin,
|
|
254
|
+
})
|
|
255
|
+
if (res && res.ok) {
|
|
256
|
+
executed.push(`${pinned ? '📌全局' : '本任务'}${label}:${clamp(val, 30)}`)
|
|
257
|
+
} else if (res && res.blockedBySafetyGuard) {
|
|
258
|
+
executed.push(`🛡️ 已拦截写入边界(${field})`)
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
} else if (op === 'bounds.remove' && opItem.item) {
|
|
262
|
+
const field = ['forbidden', 'allowed', 'notes'].includes(opItem.field) ? opItem.field : 'forbidden'
|
|
263
|
+
const val = clamp(opItem.item, 220)
|
|
264
|
+
const pinned = forceSessionOnly ? false : Boolean(opItem.pinGlobal)
|
|
265
|
+
if (val) {
|
|
266
|
+
const res = deps.runAction({
|
|
267
|
+
action: 'bounds.remove',
|
|
268
|
+
field,
|
|
269
|
+
item: val,
|
|
270
|
+
pinned,
|
|
271
|
+
session: rootId,
|
|
272
|
+
by: 'chief',
|
|
273
|
+
_callerOrigin: callerOrigin,
|
|
274
|
+
})
|
|
275
|
+
if (res && res.ok) {
|
|
276
|
+
executed.push(`移除边界:${clamp(val, 30)}`)
|
|
277
|
+
} else if (res && res.blockedBySafetyGuard) {
|
|
278
|
+
executed.push(`🛡️ 已拦截移除红线(${field})`)
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
return executed
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/**
|
|
287
|
+
* Execute Wishing-Box `archiveOps` across Session / Global / Precipitated vaults
|
|
288
|
+
* while strictly preserving the upward gradient (`session -> global -> precipitated`;
|
|
289
|
+
* direct session -> precipitated jump is forbidden).
|
|
290
|
+
*/
|
|
291
|
+
export const MAIN_INJECT_ARCHIVE_OPS = new Set(['pin_to_desktop', 'unpin_from_desktop', 'take_out', 'put_back', 'deliver_to_lead'])
|
|
292
|
+
|
|
293
|
+
export function normalizeArchiveOpName(rawOp) {
|
|
294
|
+
const s = String(rawOp || '').trim()
|
|
295
|
+
if (s === 'take_out') return 'pin_to_desktop'
|
|
296
|
+
if (s === 'put_back') return 'unpin_from_desktop'
|
|
297
|
+
return s
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
export function resolveItemIdForChiefScope(scope, rawId, rawTitle, { sessionOpt, globalOpt }) {
|
|
301
|
+
const idQ = String(rawId || '').trim()
|
|
302
|
+
const titleQ = String(rawTitle || '').trim().toLowerCase()
|
|
303
|
+
const opt = scope === 'global' ? globalOpt : sessionOpt
|
|
304
|
+
if (!opt) return idQ
|
|
305
|
+
const store = loadArchiveStore(opt)
|
|
306
|
+
const items = Array.isArray(store.items) ? store.items : []
|
|
307
|
+
if (idQ) {
|
|
308
|
+
const exact = items.find(it => it.id === idQ)
|
|
309
|
+
if (exact) return exact.id
|
|
310
|
+
}
|
|
311
|
+
if (titleQ) {
|
|
312
|
+
const byTitle = items.find(it => String(it.title || '').toLowerCase().includes(titleQ))
|
|
313
|
+
if (byTitle) return byTitle.id
|
|
314
|
+
}
|
|
315
|
+
return idQ
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* Shared Chief executor for main-session archive injection ops (`pin_to_desktop`, `unpin_from_desktop`, `deliver_to_lead`)
|
|
320
|
+
* and `pull_global`, enforcing strict cold-vault isolation and dual-channel injection rules.
|
|
321
|
+
*/
|
|
322
|
+
export async function executeChiefArchiveInjectionOp(deps, rootId, opItem = {}, opts = {}) {
|
|
323
|
+
const sid = rootId && rootId !== 'global' ? String(rootId).trim() : ''
|
|
324
|
+
const op = normalizeArchiveOpName(opItem.op)
|
|
325
|
+
const scope = opItem.vaultScope === 'precipitated'
|
|
326
|
+
? 'precipitated'
|
|
327
|
+
: (opItem.vaultScope === 'global' ? 'global' : 'session')
|
|
328
|
+
if (scope === 'precipitated' || op === 'pull_precipitated') {
|
|
329
|
+
return { ok: false, blocked: true, error: '冷藏档案柜 100% 归属人类专属隔离,参谋无权读档或推送。' }
|
|
330
|
+
}
|
|
331
|
+
if (!sid) {
|
|
332
|
+
return { ok: false, error: '当前为空白未绑定会话,无法推上桌面或递送主对话。' }
|
|
333
|
+
}
|
|
334
|
+
const globalOpt = archiveTargetForRoot(deps, sid, { vaultScope: 'global' })
|
|
335
|
+
const sessionOpt = archiveTargetForRoot(deps, sid, { vaultScope: 'session' })
|
|
336
|
+
const hitId = resolveItemIdForChiefScope(scope, opItem.id || opItem.archiveId, opItem.title, { sessionOpt, globalOpt })
|
|
337
|
+
if (!hitId) {
|
|
338
|
+
return { ok: false, error: '未匹配到目标工程档案。' }
|
|
339
|
+
}
|
|
340
|
+
const targetOpt = scope === 'global' ? globalOpt : sessionOpt
|
|
341
|
+
|
|
342
|
+
if (op === 'pin_to_desktop' || op === 'unpin_from_desktop') {
|
|
343
|
+
const mOp = op === 'pin_to_desktop' ? 'pinToDesktop' : 'unpinFromDesktop'
|
|
344
|
+
const r = mutateArchive({
|
|
345
|
+
op: mOp,
|
|
346
|
+
vaultScope: scope,
|
|
347
|
+
rootSessionId: sid,
|
|
348
|
+
id: hitId,
|
|
349
|
+
by: opts.by || 'chief',
|
|
350
|
+
}, targetOpt)
|
|
351
|
+
if (!r || !r.ok) {
|
|
352
|
+
return { ok: false, error: (r && r.error) || '桌面调配失败' }
|
|
353
|
+
}
|
|
354
|
+
const ev = Array.isArray(r.evicted) && r.evicted.length > 0 ? `(超 2400 Tokens/6 份自动撤回:${r.evicted.map(x => `《${clamp(x.title, 18)}》`).join('、')})` : ''
|
|
355
|
+
const actionText = `${op === 'pin_to_desktop' ? '📌 摆上桌面' : '撤出桌面'} #${hitId}${ev}`
|
|
356
|
+
return { ok: true, op, scope, id: hitId, evicted: r.evicted || [], actionText }
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
if (op === 'deliver_to_lead') {
|
|
360
|
+
const det = getArchiveDetail(hitId, sid, targetOpt)
|
|
361
|
+
if (!det || !det.ok || !det.item) {
|
|
362
|
+
return { ok: false, error: '未读取到待递送档案内容' }
|
|
363
|
+
}
|
|
364
|
+
const it = det.item
|
|
365
|
+
const ptLines = Array.isArray(it.points) && it.points.length > 0
|
|
366
|
+
? it.points.slice(0, 5).map(pt => `- ${pt.title}:${clamp(pt.detail || pt.cue, 180)}`)
|
|
367
|
+
: []
|
|
368
|
+
const instr = cleanMultiline(opItem.instruction || opItem.note || '', 240)
|
|
369
|
+
const msgBody = [
|
|
370
|
+
`[DSH 参谋长档案馆 · 一次性重点递送(不占桌面置顶槽)]`,
|
|
371
|
+
`来源:${scope === 'global' ? '🌐 全局档案柜(参谋核准后专递)' : '🗂️ 本局档案柜'} · 《${clamp(it.title, 48)}》 (id=${it.id})`,
|
|
372
|
+
instr ? `参谋附言:${instr}` : '',
|
|
373
|
+
it.summary ? `提要:${clamp(it.summary, 200)}` : '',
|
|
374
|
+
...(ptLines.length ? ['核心要点:', ...ptLines] : []),
|
|
375
|
+
!ptLines.length && it.body ? `正文节选:\n${clamp(it.body, 900)}` : '',
|
|
376
|
+
].filter(Boolean).join('\n')
|
|
377
|
+
|
|
378
|
+
const deliverTarget = String(opItem.target || 'lead').trim() || 'lead'
|
|
379
|
+
const deliv = await deliverCrossMessage(deps, {
|
|
380
|
+
fromSession: sid,
|
|
381
|
+
fromLabel: opts.byLabel || 'DSH 参谋长 (档案馆重点递送)',
|
|
382
|
+
target: deliverTarget,
|
|
383
|
+
subject: `档案馆递送《${clamp(it.title, 28)}》`,
|
|
384
|
+
text: msgBody,
|
|
385
|
+
mode: 'steer',
|
|
386
|
+
envelopeKind: 'execution_request',
|
|
387
|
+
recordBoardLog: true,
|
|
388
|
+
})
|
|
389
|
+
mutateArchive({ op: 'markDeliveredToLead', vaultScope: scope, rootSessionId: sid, id: hitId }, targetOpt)
|
|
390
|
+
return {
|
|
391
|
+
ok: Boolean(deliv && deliv.ok),
|
|
392
|
+
op,
|
|
393
|
+
scope,
|
|
394
|
+
id: hitId,
|
|
395
|
+
delivery: deliv,
|
|
396
|
+
actionText: deliv && deliv.ok
|
|
397
|
+
? `📨 递送档案《${clamp(it.title, 20)}》→ ${deliv.target || deliverTarget}`
|
|
398
|
+
: `递送失败:${(deliv && deliv.error) || '目标不可达'}`,
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
if (op === 'pull_global') {
|
|
403
|
+
const r = mutateArchive({ op: 'pullByChief', vaultScope: 'global', rootSessionId: sid, id: hitId }, globalOpt)
|
|
404
|
+
if (r && r.ok) {
|
|
405
|
+
return { ok: true, op, scope: 'global', id: hitId, actionText: `👁️ 参谋拉阅全局档案 #${hitId}` }
|
|
406
|
+
}
|
|
407
|
+
return { ok: false, error: (r && r.error) || '全局拉阅失败' }
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
return { ok: false, error: `不支持的档案注入指令:${op}` }
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/**
|
|
414
|
+
* Execute Wishing-Box `archiveOps` requested by user in natural language (`整理`/`提炼入全局`/内务操作),
|
|
415
|
+
* strictly enforcing cold-vault 0-byte isolation (`precipitated` blocked) and upward gradient (`session -> global -> precipitated`).
|
|
416
|
+
*/
|
|
417
|
+
export async function applyArchiveOps(deps, rootId, archiveOps, ctx = {}) {
|
|
418
|
+
const executed = []
|
|
419
|
+
if (!Array.isArray(archiveOps) || !archiveOps.length) return { executed, changed: false }
|
|
420
|
+
const sid = rootId && rootId !== 'global' ? String(rootId).trim() : ''
|
|
421
|
+
const globalOpt = archiveTargetForRoot(deps, sid || 'global', { vaultScope: 'global' })
|
|
422
|
+
const sessionOpt = sid ? archiveTargetForRoot(deps, sid, { vaultScope: 'session' }) : null
|
|
423
|
+
let changed = false
|
|
424
|
+
|
|
425
|
+
const resolveItemInScope = (scope, rawId, rawTitle) =>
|
|
426
|
+
resolveItemIdForChiefScope(scope, rawId, rawTitle, { sessionOpt, globalOpt })
|
|
427
|
+
|
|
428
|
+
for (const opItem of archiveOps.slice(0, 8)) {
|
|
429
|
+
if (!opItem || typeof opItem !== 'object') continue
|
|
430
|
+
const op = normalizeArchiveOpName(opItem.op)
|
|
431
|
+
const scope = opItem.vaultScope === 'precipitated'
|
|
432
|
+
? 'precipitated'
|
|
433
|
+
: (opItem.vaultScope === 'global' ? 'global' : 'session')
|
|
434
|
+
|
|
435
|
+
// Cold vault (`precipitated`) is 100% human-only: Chief may never inspect, pin, or pull from it.
|
|
436
|
+
if (scope === 'precipitated' || op === 'pull_precipitated') {
|
|
437
|
+
executed.push('🧊 已拦截:冷藏档案柜仅人类可见,参谋无权读取或调取')
|
|
438
|
+
continue
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
if (op === 'organize') {
|
|
442
|
+
const orgScope = opItem.vaultScope === 'global' ? 'global' : 'session'
|
|
443
|
+
if (orgScope === 'session' && !sid) continue
|
|
444
|
+
const r = await organizeArchivesWithChief(deps, {
|
|
445
|
+
sessionId: sid || 'global',
|
|
446
|
+
vaultScope: orgScope,
|
|
447
|
+
ids: Array.isArray(opItem.ids) ? opItem.ids : [],
|
|
448
|
+
scope: opItem.scope === 'all' ? 'all' : 'unorganized',
|
|
449
|
+
instruction: String(opItem.instruction || ctx.input || ''),
|
|
450
|
+
}).catch(() => null)
|
|
451
|
+
if (r && r.ok) {
|
|
452
|
+
changed = true
|
|
453
|
+
executed.push(`整理${orgScope === 'global' ? '全局' : '本局'}档案 ×${r.updatedCount ?? 0}`)
|
|
454
|
+
}
|
|
455
|
+
} else if (op === 'distill_to_global' || op === 'distill') {
|
|
456
|
+
if (!sid) continue
|
|
457
|
+
const r = await distillSessionArchivesToGlobal(deps, {
|
|
458
|
+
sessionId: sid,
|
|
459
|
+
ids: Array.isArray(opItem.ids) ? opItem.ids : (opItem.id ? [opItem.id] : []),
|
|
460
|
+
instruction: String(opItem.instruction || ctx.input || ''),
|
|
461
|
+
}).catch(() => null)
|
|
462
|
+
if (r && r.ok) {
|
|
463
|
+
changed = true
|
|
464
|
+
executed.push(`提炼入全局 ×${r.createdCount ?? 0}`)
|
|
465
|
+
}
|
|
466
|
+
} else if (op === 'pull_global') {
|
|
467
|
+
const r = await executeChiefArchiveInjectionOp(deps, rootId, { ...opItem, op: 'pull_global', vaultScope: 'global' })
|
|
468
|
+
if (r && r.ok) {
|
|
469
|
+
changed = true
|
|
470
|
+
executed.push(r.actionText)
|
|
471
|
+
}
|
|
472
|
+
} else if (op === 'save' || op === 'create') {
|
|
473
|
+
if (scope === 'session' && !sid) continue
|
|
474
|
+
const targetOpt = scope === 'global' ? globalOpt : sessionOpt
|
|
475
|
+
const allowPin = Boolean(opItem.takeOut) && optsTakeOutAllowed(ctx)
|
|
476
|
+
const r = mutateArchive({
|
|
477
|
+
op: 'save',
|
|
478
|
+
vaultScope: scope,
|
|
479
|
+
rootSessionId: sid,
|
|
480
|
+
folder: opItem.folder || 'inbox',
|
|
481
|
+
paperclip: ['gold', 'silver', 'copper'].includes(opItem.paperclip) ? opItem.paperclip : 'silver',
|
|
482
|
+
title: clamp(opItem.title || '参谋长工作归档', 160),
|
|
483
|
+
summary: clamp(opItem.summary || '', 400),
|
|
484
|
+
body: cleanMultiline(opItem.body || opItem.summary || opItem.title || '', 12000),
|
|
485
|
+
takeOutNow: allowPin,
|
|
486
|
+
organizedBy: 'chief',
|
|
487
|
+
by: 'chief',
|
|
488
|
+
}, targetOpt)
|
|
489
|
+
if (r && r.ok) {
|
|
490
|
+
changed = true
|
|
491
|
+
executed.push(`存档(${scope === 'global' ? '全局' : '本局'}):《${clamp(opItem.title || '', 24)}》`)
|
|
492
|
+
}
|
|
493
|
+
} else if (op === 'pin_to_desktop' || op === 'unpin_from_desktop' || op === 'deliver_to_lead') {
|
|
494
|
+
const r = await executeChiefArchiveInjectionOp(deps, rootId, opItem, ctx)
|
|
495
|
+
if (r && r.ok) {
|
|
496
|
+
changed = true
|
|
497
|
+
executed.push(r.actionText)
|
|
498
|
+
}
|
|
499
|
+
} else if (op === 'mount_chief' || op === 'unmount_chief') {
|
|
500
|
+
if (!sid) continue
|
|
501
|
+
const hitId = resolveItemInScope('global', opItem.id || opItem.archiveId, opItem.title)
|
|
502
|
+
if (!hitId) continue
|
|
503
|
+
const r = mutateArchive({
|
|
504
|
+
op: op === 'mount_chief' ? 'mountChief' : 'unmountChief',
|
|
505
|
+
vaultScope: 'global',
|
|
506
|
+
rootSessionId: sid,
|
|
507
|
+
id: hitId,
|
|
508
|
+
}, globalOpt)
|
|
509
|
+
if (r && r.ok) {
|
|
510
|
+
changed = true
|
|
511
|
+
executed.push(`${op === 'mount_chief' ? '参阅全局档案' : '取消全局参阅'} #${hitId}`)
|
|
512
|
+
}
|
|
513
|
+
} else if (op === 'copy_to_global') {
|
|
514
|
+
if (!sid) continue
|
|
515
|
+
const hitId = resolveItemInScope('session', opItem.id || opItem.archiveId, opItem.title)
|
|
516
|
+
if (!hitId) continue
|
|
517
|
+
const r = mutateArchive({ op: 'copyToGlobal', vaultScope: 'session', rootSessionId: sid, id: hitId }, sessionOpt)
|
|
518
|
+
if (r && r.ok) {
|
|
519
|
+
changed = true
|
|
520
|
+
executed.push(`升入全局档案 #${hitId}`)
|
|
521
|
+
}
|
|
522
|
+
} else if (op === 'copy_to_session') {
|
|
523
|
+
if (!sid) continue
|
|
524
|
+
const hitId = resolveItemInScope('global', opItem.id || opItem.archiveId, opItem.title)
|
|
525
|
+
if (!hitId) continue
|
|
526
|
+
const r = mutateArchive({ op: 'copyToSession', vaultScope: 'global', rootSessionId: sid, id: hitId }, globalOpt)
|
|
527
|
+
if (r && r.ok) {
|
|
528
|
+
changed = true
|
|
529
|
+
executed.push(`全局调入本局 #${hitId}`)
|
|
530
|
+
}
|
|
531
|
+
} else if (op === 'move_folder' && opItem.folder) {
|
|
532
|
+
if (scope === 'session' && !sid) continue
|
|
533
|
+
const targetOpt = scope === 'global' ? globalOpt : sessionOpt
|
|
534
|
+
const hitId = resolveItemInScope(scope, opItem.id || opItem.archiveId, opItem.title)
|
|
535
|
+
if (!hitId) continue
|
|
536
|
+
const r = mutateArchive({ op: 'moveFolder', vaultScope: scope, rootSessionId: sid, id: hitId, folder: opItem.folder }, targetOpt)
|
|
537
|
+
if (r && r.ok) {
|
|
538
|
+
changed = true
|
|
539
|
+
executed.push(`移动档案分类 → ${opItem.folder}`)
|
|
540
|
+
}
|
|
541
|
+
} else if (op === 'delete' || op === 'remove') {
|
|
542
|
+
if (scope === 'session' && !sid) continue
|
|
543
|
+
const targetOpt = scope === 'global' ? globalOpt : sessionOpt
|
|
544
|
+
const hitId = resolveItemInScope(scope, opItem.id || opItem.archiveId, opItem.title)
|
|
545
|
+
if (!hitId) continue
|
|
546
|
+
const r = mutateArchive({ op: 'delete', vaultScope: scope, rootSessionId: sid, id: hitId }, targetOpt)
|
|
547
|
+
if (r && r.ok) {
|
|
548
|
+
changed = true
|
|
549
|
+
executed.push(`移除${scope === 'global' ? '全局' : '本局'}档案 #${hitId}`)
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
return { executed, changed }
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
export function optsTakeOutAllowed(ctx) {
|
|
558
|
+
return Boolean(ctx && ctx.allowPinToDesktop !== false)
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
/** Execute Wishing-Box `networkOps` to link or unlink standalone DSH sessions. */
|
|
562
|
+
export function applyNetworkOps(rootId, networkOps, directory) {
|
|
563
|
+
const executed = []
|
|
564
|
+
if (!Array.isArray(networkOps) || !networkOps.length || !rootId || rootId === 'global') return executed
|
|
565
|
+
const otherSessions = (directory && Array.isArray(directory.otherSessions)) ? directory.otherSessions : []
|
|
566
|
+
|
|
567
|
+
for (const opItem of networkOps.slice(0, 6)) {
|
|
568
|
+
if (!opItem || typeof opItem !== 'object') continue
|
|
569
|
+
const op = String(opItem.op || '').trim()
|
|
570
|
+
if (op !== 'link' && op !== 'unlink') continue
|
|
571
|
+
const rawQ = String(opItem.targetSessionId || opItem.target || opItem.sessionId || opItem.name || '').trim()
|
|
572
|
+
if (!rawQ) continue
|
|
573
|
+
const qLower = rawQ.toLowerCase()
|
|
574
|
+
const match = otherSessions.find(s =>
|
|
575
|
+
s.id === rawQ
|
|
576
|
+
|| String(s.id).toLowerCase().includes(qLower)
|
|
577
|
+
|| (s.name && String(s.name).toLowerCase().includes(qLower))
|
|
578
|
+
)
|
|
579
|
+
const targetSid = match ? match.id : (/^session-/i.test(rawQ) ? rawQ : '')
|
|
580
|
+
if (!targetSid || targetSid === rootId) continue
|
|
581
|
+
const r = setPeerLink(rootId, targetSid, op === 'link')
|
|
582
|
+
if (r && r.ok) {
|
|
583
|
+
executed.push(`${op === 'link' ? '连接协同窗口' : '断开协同窗口'}:${match ? match.name : targetSid.slice(0, 14)}`)
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
return executed
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
/** Detect pure beginner progress/status questions where all truth is already in live snapshot + board (zero disk/shell tools needed). */
|
|
590
|
+
|
|
591
|
+
export async function consolidateBoundsWithChief(deps, {
|
|
592
|
+
sessionId = '',
|
|
593
|
+
field = '',
|
|
594
|
+
items = [],
|
|
595
|
+
instruction = '',
|
|
596
|
+
} = {}) {
|
|
597
|
+
const rootId = (deps.resolveRootSessionId && deps.resolveRootSessionId(sessionId)) || String(sessionId || 'global')
|
|
598
|
+
const board = deps.boardForSession && deps.boardFileFor
|
|
599
|
+
? deps.boardForSession(deps.boardFileFor(rootId))
|
|
600
|
+
: { bounds: { allowed: [], forbidden: [], notes: [] }, pinnedBounds: { allowed: [], forbidden: [], notes: [] } }
|
|
601
|
+
const bounds = (board && board.bounds) || { allowed: [], forbidden: [], notes: [] }
|
|
602
|
+
const pinnedBounds = (board && board.pinnedBounds) || { allowed: [], forbidden: [], notes: [] }
|
|
603
|
+
const BOUND_COL_LABEL = { forbidden: '禁止红线', allowed: '必做事项', notes: '注意事项' }
|
|
604
|
+
|
|
605
|
+
// Determine which column(s) to consolidate
|
|
606
|
+
const targetCols = []
|
|
607
|
+
const explicitItems = Array.isArray(items)
|
|
608
|
+
? items.map(x => String(x || '').trim()).filter(Boolean)
|
|
609
|
+
: []
|
|
610
|
+
|
|
611
|
+
const normField = String(field || '').trim().toLowerCase() === 'must' ? 'allowed' : field
|
|
612
|
+
if (['forbidden', 'allowed', 'notes'].includes(normField)) {
|
|
613
|
+
const colList = Array.isArray(bounds[normField]) ? bounds[normField] : []
|
|
614
|
+
const chosen = explicitItems.length >= 2
|
|
615
|
+
? colList.filter(x => explicitItems.includes(x))
|
|
616
|
+
: colList
|
|
617
|
+
if (chosen.length < 2) {
|
|
618
|
+
return { ok: false, error: `【${BOUND_COL_LABEL[normField]}】当前不足 2 条规则,无需浓缩合并。` }
|
|
619
|
+
}
|
|
620
|
+
targetCols.push({ col: normField, sourceItems: chosen })
|
|
621
|
+
} else if (explicitItems.length >= 2) {
|
|
622
|
+
// Infer column with most matches, default forbidden
|
|
623
|
+
let bestCol = 'forbidden'
|
|
624
|
+
let bestHits = -1
|
|
625
|
+
for (const c of ['forbidden', 'allowed', 'notes']) {
|
|
626
|
+
const hits = (bounds[c] || []).filter(x => explicitItems.includes(x)).length
|
|
627
|
+
if (hits > bestHits) {
|
|
628
|
+
bestHits = hits
|
|
629
|
+
bestCol = c
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
targetCols.push({ col: bestCol, sourceItems: explicitItems })
|
|
633
|
+
} else {
|
|
634
|
+
for (const c of ['forbidden', 'allowed', 'notes']) {
|
|
635
|
+
const colList = Array.isArray(bounds[c]) ? bounds[c] : []
|
|
636
|
+
if (colList.length >= 2) {
|
|
637
|
+
targetCols.push({ col: c, sourceItems: colList })
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
if (!targetCols.length) {
|
|
641
|
+
return { ok: false, error: '当前各边界分栏均不足 2 条零散规则,暂时无需合并。' }
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
const consWorkId = beginChiefActiveWork(rootId, {
|
|
646
|
+
tone: 'bounds',
|
|
647
|
+
tab: 'boundaries',
|
|
648
|
+
boundSubTab: 'rules',
|
|
649
|
+
label: '参谋长正在浓缩边界中...',
|
|
650
|
+
})
|
|
651
|
+
try {
|
|
652
|
+
const createdProposals = []
|
|
653
|
+
for (const { col, sourceItems } of targetCols) {
|
|
654
|
+
const colLabel = BOUND_COL_LABEL[col] || '禁止红线'
|
|
655
|
+
const hadPinned = sourceItems.some(x => (pinnedBounds[col] || []).includes(x))
|
|
656
|
+
const prompt = [
|
|
657
|
+
`目标边界分栏:【${colLabel}】(${col})`,
|
|
658
|
+
instruction ? `用户额外要求:${clamp(instruction, 200)}` : '',
|
|
659
|
+
`待浓缩合并的 ${sourceItems.length} 条零散边界:`,
|
|
660
|
+
...sourceItems.map((it, idx) => `${idx + 1}. ${(pinnedBounds[col] || []).includes(it) ? '[📌全局定住] ' : ''}${it}`),
|
|
661
|
+
'',
|
|
662
|
+
'请将以上零散规则浓缩合并为唯一 1 条高密度总则(保留具体命令、路径与硬红线),只输出 JSON:',
|
|
663
|
+
].filter(Boolean).join('\n')
|
|
664
|
+
|
|
665
|
+
const llmRes = await callChiefLlm(deps, {
|
|
666
|
+
sessionId: rootId,
|
|
667
|
+
reasonKind: 'consolidate_bounds',
|
|
668
|
+
system: CONSOLIDATE_BOUNDS_SYSTEM,
|
|
669
|
+
prompt,
|
|
670
|
+
maxTokens: SUMMARY_MAX_TOKENS,
|
|
671
|
+
})
|
|
672
|
+
|
|
673
|
+
const parsed = llmRes.ok ? extractJsonObject(llmRes.text) : null
|
|
674
|
+
const mergedText = clamp(
|
|
675
|
+
(parsed && (parsed.item || parsed.draftText || parsed.text)) || deterministicConsolidateClauses(sourceItems),
|
|
676
|
+
220,
|
|
677
|
+
)
|
|
678
|
+
const mergedReason = clamp(
|
|
679
|
+
(parsed && parsed.reason) || `已将【${colLabel}】下 ${sourceItems.length} 条零散边界浓缩合成为 1 条总则,批准后自动替换原零散条目。`,
|
|
680
|
+
180,
|
|
681
|
+
)
|
|
682
|
+
|
|
683
|
+
if (!mergedText || secretLike(mergedText)) continue
|
|
684
|
+
|
|
685
|
+
mutateChiefState((s) => {
|
|
686
|
+
const ws = ensureWorkspace(s, rootId)
|
|
687
|
+
// Dismiss older pending consolidation proposals for the exact same column to avoid clutter
|
|
688
|
+
for (const existing of ws.suggestions) {
|
|
689
|
+
if (existing.status === 'pending' && existing.kind === 'bound' && existing.boundField === col && Array.isArray(existing.replaces) && existing.replaces.length > 0) {
|
|
690
|
+
existing.status = 'dismissed'
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
const sug = normalizeSuggestion({
|
|
694
|
+
kind: 'bound',
|
|
695
|
+
boundField: col,
|
|
696
|
+
fromAgent: '✦ 参谋长浓缩',
|
|
697
|
+
title: `${colLabel} ${sourceItems.length} 合 1:${clamp(mergedText, 26)}`,
|
|
698
|
+
reason: mergedReason,
|
|
699
|
+
target: 'bounds',
|
|
700
|
+
targetLabel: colLabel,
|
|
701
|
+
mode: 'silent',
|
|
702
|
+
draftText: mergedText,
|
|
703
|
+
replaces: sourceItems,
|
|
704
|
+
pinGlobal: hadPinned,
|
|
705
|
+
})
|
|
706
|
+
if (sug) {
|
|
707
|
+
ws.suggestions.push(sug)
|
|
708
|
+
createdProposals.push(sug)
|
|
709
|
+
}
|
|
710
|
+
})
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
if (!createdProposals.length) {
|
|
714
|
+
return { ok: false, error: '未能生成浓缩边界,请稍后重试。' }
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
const replyLines = createdProposals.map(p =>
|
|
718
|
+
`- 【${p.targetLabel} · ${p.replaces.length} 合 1】${p.draftText}(可在上方请示卡片选「📌 定住全局」或「仅本任务」一键替换)`,
|
|
719
|
+
)
|
|
720
|
+
|
|
721
|
+
return {
|
|
722
|
+
ok: true,
|
|
723
|
+
proposals: createdProposals,
|
|
724
|
+
reply: replyLines.join('\n'),
|
|
725
|
+
view: await getChiefView(deps, rootId, { autoSummarize: false }),
|
|
726
|
+
}
|
|
727
|
+
} finally {
|
|
728
|
+
endChiefActiveWork(rootId, consWorkId)
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
|
|
733
|
+
export function proposeBoundToChief(deps, { sessionId, callerAgent, by, field, item, items, reason }) {
|
|
734
|
+
const sid = String(sessionId || (callerAgent && callerAgent.id) || '').trim()
|
|
735
|
+
const rootId = (deps.resolveRootSessionId && deps.resolveRootSessionId(sid, callerAgent)) || sid || 'global'
|
|
736
|
+
const identity = deps.resolveAgentIdentity ? deps.resolveAgentIdentity(deps.runtime, sid, callerAgent) : null
|
|
737
|
+
const speaker = identity && identity.isChild
|
|
738
|
+
? `@${identity.self}`
|
|
739
|
+
: (by && by !== 'agent' ? String(by) : '@lead')
|
|
740
|
+
|
|
741
|
+
const rawCol = String(field || '').trim().toLowerCase()
|
|
742
|
+
const normCol = rawCol === 'must' ? 'allowed' : rawCol
|
|
743
|
+
const col = ['forbidden', 'allowed', 'notes'].includes(normCol) ? normCol : 'forbidden'
|
|
744
|
+
const BOUND_COL_LABEL = { forbidden: '禁止红线', allowed: '必做事项', notes: '注意事项' }
|
|
745
|
+
const colLabel = BOUND_COL_LABEL[col] || '禁止红线'
|
|
746
|
+
|
|
747
|
+
const rawItems = []
|
|
748
|
+
if (typeof item === 'string' && item.trim()) rawItems.push(item.trim())
|
|
749
|
+
if (Array.isArray(items)) {
|
|
750
|
+
for (const entry of items) {
|
|
751
|
+
if (typeof entry === 'string' && entry.trim()) rawItems.push(entry.trim())
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
if (!rawItems.length) {
|
|
755
|
+
return { ok: false, error: 'bounds.propose requires item (string) or items (string[])' }
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
const board = deps.boardForSession && deps.boardFileFor && rootId !== 'global'
|
|
759
|
+
? deps.boardForSession(deps.boardFileFor(rootId))
|
|
760
|
+
: null
|
|
761
|
+
const existingCol = Array.isArray(board?.bounds?.[col]) ? board.bounds[col] : []
|
|
762
|
+
|
|
763
|
+
const proposed = []
|
|
764
|
+
const skippedDuplicates = []
|
|
765
|
+
|
|
766
|
+
mutateChiefState((state) => {
|
|
767
|
+
const ws = ensureWorkspace(state, rootId)
|
|
768
|
+
for (const rawRule of rawItems.slice(0, 6)) {
|
|
769
|
+
const ruleText = clamp(rawRule, 220)
|
|
770
|
+
if (!ruleText || secretLike(ruleText)) continue
|
|
771
|
+
if (existingCol.some(x => String(x).trim() === ruleText)) {
|
|
772
|
+
skippedDuplicates.push(ruleText)
|
|
773
|
+
continue
|
|
774
|
+
}
|
|
775
|
+
const dupPending = ws.suggestions.some(
|
|
776
|
+
s => s.status === 'pending' && s.kind === 'bound' && s.draftText === ruleText,
|
|
777
|
+
)
|
|
778
|
+
if (dupPending) {
|
|
779
|
+
skippedDuplicates.push(ruleText)
|
|
780
|
+
continue
|
|
781
|
+
}
|
|
782
|
+
const sug = normalizeSuggestion({
|
|
783
|
+
kind: 'bound',
|
|
784
|
+
boundField: col,
|
|
785
|
+
fromAgent: speaker,
|
|
786
|
+
title: `拟入${colLabel}:${clamp(ruleText, 30)}`,
|
|
787
|
+
reason: clamp(reason || `${speaker} 在执行中上报的边界约束,请批准后注入全局边界。`, 180),
|
|
788
|
+
target: 'bounds',
|
|
789
|
+
targetLabel: colLabel,
|
|
790
|
+
mode: 'silent',
|
|
791
|
+
draftText: ruleText,
|
|
792
|
+
})
|
|
793
|
+
if (sug) {
|
|
794
|
+
const pendingNonBound = ws.suggestions.filter(s => s.status === 'pending' && s.kind !== 'bound')
|
|
795
|
+
const pendingAll = ws.suggestions.filter(s => s.status === 'pending')
|
|
796
|
+
if (pendingAll.length >= SUGGESTIONS_CAP && pendingNonBound.length > 0) {
|
|
797
|
+
pendingNonBound[0].status = 'dismissed'
|
|
798
|
+
}
|
|
799
|
+
ws.suggestions.push(sug)
|
|
800
|
+
proposed.push(sug)
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
})
|
|
804
|
+
|
|
805
|
+
if (proposed.length && typeof deps.appendBoardLog === 'function' && rootId !== 'global') {
|
|
806
|
+
deps.appendBoardLog(
|
|
807
|
+
rootId,
|
|
808
|
+
`🏛 收到边界奏请 (${colLabel}):${proposed.map(p => clamp(p.draftText, 40)).join(';')}`,
|
|
809
|
+
speaker,
|
|
810
|
+
)
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
return {
|
|
814
|
+
ok: true,
|
|
815
|
+
proposed: proposed.map(p => ({ id: p.id, field: p.boundField, item: p.draftText, from: p.fromAgent })),
|
|
816
|
+
skippedDuplicates,
|
|
817
|
+
message: proposed.length
|
|
818
|
+
? `已呈交 DSH 参谋长(共 ${proposed.length} 条),参谋长正请示用户批准后注入全局【${colLabel}】。`
|
|
819
|
+
: '该边界已在全局边界或待批请示列表中,无需重复上报。',
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
|
|
824
|
+
export async function suggestCoreObjectiveWithChief(deps, {
|
|
825
|
+
sessionId = '',
|
|
826
|
+
draft = '',
|
|
827
|
+
mode = 'auto',
|
|
828
|
+
previousSuggestions = [],
|
|
829
|
+
} = {}) {
|
|
830
|
+
const rootId = (deps && typeof deps.resolveRootSessionId === 'function' ? deps.resolveRootSessionId(sessionId) : sessionId) || String(sessionId || 'global')
|
|
831
|
+
const rawDraft = String(draft || '').replace(/\s+/g, ' ').trim()
|
|
832
|
+
const prevList = (Array.isArray(previousSuggestions) ? previousSuggestions : [])
|
|
833
|
+
.map(x => String(x || '').replace(/\s+/g, ' ').trim())
|
|
834
|
+
.filter(Boolean)
|
|
835
|
+
.slice(-12)
|
|
836
|
+
|
|
837
|
+
const normalizedDraft = rawDraft.toLowerCase()
|
|
838
|
+
const isCycleOfPreviousAi = Boolean(
|
|
839
|
+
rawDraft && prevList.some(p => p.toLowerCase() === normalizedDraft),
|
|
840
|
+
)
|
|
841
|
+
const effectiveMode = (mode === 'refine' || (mode === 'auto' && rawDraft && !isCycleOfPreviousAi))
|
|
842
|
+
? 'refine'
|
|
843
|
+
: 'guess'
|
|
844
|
+
|
|
845
|
+
const directory = await listPeerDirectory(deps, rootId)
|
|
846
|
+
const board = deps && deps.boardForSession && deps.boardFileFor
|
|
847
|
+
? deps.boardForSession(deps.boardFileFor(rootId))
|
|
848
|
+
: null
|
|
849
|
+
const liveDigest = collectLiveConversationsDigest(deps, rootId, directory)
|
|
850
|
+
const state = loadChiefState()
|
|
851
|
+
const view = clusterView(state, rootId)
|
|
852
|
+
const numberedFacts = view.facts.slice(-8)
|
|
853
|
+
const planSteps = Array.isArray(board && board.plan) ? board.plan.filter(Boolean) : []
|
|
854
|
+
const openPlan = planSteps.filter(s => !s.done)
|
|
855
|
+
const tasks = Array.isArray(board && board.tasks) ? board.tasks : []
|
|
856
|
+
const activeTasks = tasks.filter(t => t && (t.status === 'doing' || t.status === 'todo' || t.status === 'blocked'))
|
|
857
|
+
const bounds = (board && board.bounds) || { allowed: [], forbidden: [], notes: [] }
|
|
858
|
+
const leadEntry = (liveDigest.entries || []).find(e => e.kind === 'lead') || (liveDigest.entries || [])[0] || null
|
|
859
|
+
const latestUser = (leadEntry && leadEntry.lastUser) ? leadEntry.lastUser : ''
|
|
860
|
+
const existingObj = board && board.objective ? String(board.objective).trim() : ''
|
|
861
|
+
|
|
862
|
+
// Build non-repeating deterministic fallback candidates ordered by attempt index
|
|
863
|
+
const buildFallbackCandidate = () => {
|
|
864
|
+
if (effectiveMode === 'refine' && rawDraft) {
|
|
865
|
+
const cleanDraft = clamp(rawDraft.replace(/[。;;]+$/, ''), 96)
|
|
866
|
+
const refined = /完成|实现|通过|验证|修复|交付|生成|输出/.test(cleanDraft)
|
|
867
|
+
? `${cleanDraft},确保可实测验收后收尾`
|
|
868
|
+
: `完成「${cleanDraft}」并完成实测核验`
|
|
869
|
+
return {
|
|
870
|
+
suggestion: clamp(refined, 120),
|
|
871
|
+
rationale: '已保留您原有核心意图,并补充清晰的可验收收口标准。',
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
const candidates = []
|
|
876
|
+
if (latestUser) {
|
|
877
|
+
candidates.push({
|
|
878
|
+
suggestion: clamp(`彻底完成用户当前诉求「${clamp(latestUser, 72)}」并经实测核验交付`, 120),
|
|
879
|
+
rationale: '根据主对话最近一次真实诉求提炼的核心目标。',
|
|
880
|
+
})
|
|
881
|
+
}
|
|
882
|
+
if (openPlan.length > 0) {
|
|
883
|
+
candidates.push({
|
|
884
|
+
suggestion: clamp(`按小任务板推进完成:${openPlan.slice(0, 2).map(s => clamp(s.text, 38)).join(' → ')}`, 120),
|
|
885
|
+
rationale: '聚焦小任务板当前尚未勾选的待办节点。',
|
|
886
|
+
})
|
|
887
|
+
}
|
|
888
|
+
if (activeTasks.length > 0) {
|
|
889
|
+
candidates.push({
|
|
890
|
+
suggestion: clamp(`攻克在手关键任务(${activeTasks.slice(0, 2).map(t => clamp(t.title, 36)).join('、')})并通过验证`, 120),
|
|
891
|
+
rationale: '围绕目前推进中与待办的核心任务收敛目标。',
|
|
892
|
+
})
|
|
893
|
+
}
|
|
894
|
+
if (existingObj) {
|
|
895
|
+
candidates.push({
|
|
896
|
+
suggestion: clamp(`${existingObj.replace(/[。;;]+$/, '')},完成全部必做事项与实证验收`, 120),
|
|
897
|
+
rationale: '在当前规划核心目标基础上强化完结验收基准。',
|
|
898
|
+
})
|
|
899
|
+
}
|
|
900
|
+
if (bounds.allowed && bounds.allowed.length > 0) {
|
|
901
|
+
candidates.push({
|
|
902
|
+
suggestion: clamp(`推进完成本轮主线研发与交付(必做:${clamp(bounds.allowed[0], 55)})`, 120),
|
|
903
|
+
rationale: '结合当前必做事项清单拟定的可监督落地目标。',
|
|
904
|
+
})
|
|
905
|
+
}
|
|
906
|
+
if (leadEntry && leadEntry.lastAssistant) {
|
|
907
|
+
candidates.push({
|
|
908
|
+
suggestion: clamp(`收口当前主线工作(${clamp(leadEntry.lastAssistant, 68)})并验证通过`, 120),
|
|
909
|
+
rationale: '结合主对话最新工作现场推断的收尾目标。',
|
|
910
|
+
})
|
|
911
|
+
}
|
|
912
|
+
candidates.push(
|
|
913
|
+
{
|
|
914
|
+
suggestion: '完整实现本轮设定功能需求、完成自测校验并清晰交付最终结果',
|
|
915
|
+
rationale: '通用端到端实现与实测交付目标。',
|
|
916
|
+
},
|
|
917
|
+
{
|
|
918
|
+
suggestion: '排查解决当前阻断卡点与遗留缺陷,确保系统运行稳定并通过复测',
|
|
919
|
+
rationale: '偏向排查修复与稳定收口的兜底目标。',
|
|
920
|
+
},
|
|
921
|
+
)
|
|
922
|
+
|
|
923
|
+
const prevNormSet = new Set(prevList.map(x => x.toLowerCase()))
|
|
924
|
+
const chosen = candidates.find(c => !prevNormSet.has(String(c.suggestion || '').toLowerCase()))
|
|
925
|
+
|| candidates[prevList.length % candidates.length]
|
|
926
|
+
return chosen
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
const promptLines = [
|
|
930
|
+
`当前执行模式: ${effectiveMode === 'refine' ? 'refine(在用户已有核心目标文字上微调润色)' : 'guess(结合现场上下文猜想用户想要的核心目标,允许反复点建议继续猜)'}`,
|
|
931
|
+
`工作区当前已填核心目标: ${existingObj || '(空)'}`,
|
|
932
|
+
...(rawDraft ? [`用户输入框当前文字: ${rawDraft}`] : ['用户输入框当前文字: (空)']),
|
|
933
|
+
...(prevList.length > 0 ? [`已给过的建议(严禁重复或仅微调措辞,须从新角度继续猜):\n${prevList.map((p, i) => ` ${i + 1}. ${p}`).join('\n')}`] : []),
|
|
934
|
+
`主对话最近用户原始诉求: ${latestUser || '(暂未捕捉)'}`,
|
|
935
|
+
`小任务板 (Plan) 未完步骤: ${openPlan.slice(0, 4).map(s => clamp(s.text, 60)).join(';') || '(无)'}`,
|
|
936
|
+
`在手任务 (doing/blocked/todo): ${activeTasks.slice(0, 5).map(t => `[${t.status}] ${clamp(t.title, 48)}`).join(';') || '(无)'}`,
|
|
937
|
+
`必做事项 (allowed): ${(bounds.allowed || []).slice(0, 4).join(';') || '(无)'}`,
|
|
938
|
+
`禁止红线 (forbidden): ${(bounds.forbidden || []).slice(0, 4).join(';') || '(无)'}`,
|
|
939
|
+
`主对话现场摘要: ${leadEntry ? clamp(leadEntry.lastAssistant || '', 260) : '(无)'}`,
|
|
940
|
+
...(numberedFacts.length ? [`近期重要结论: ${numberedFacts.slice(-4).map(f => clamp(f.text, 90)).join(';')}`] : []),
|
|
941
|
+
]
|
|
942
|
+
|
|
943
|
+
let suggestion = ''
|
|
944
|
+
let rationale = ''
|
|
945
|
+
let llmUsed = false
|
|
946
|
+
|
|
947
|
+
try {
|
|
948
|
+
const llmRes = await callChiefLlm(deps, {
|
|
949
|
+
sessionId: rootId,
|
|
950
|
+
reasonKind: 'suggest_objective',
|
|
951
|
+
system: OBJECTIVE_SUGGEST_SYSTEM,
|
|
952
|
+
prompt: promptLines.join('\n'),
|
|
953
|
+
maxTokens: 320,
|
|
954
|
+
})
|
|
955
|
+
if (llmRes && llmRes.ok && llmRes.text) {
|
|
956
|
+
const parsed = extractJsonObject(llmRes.text)
|
|
957
|
+
if (parsed && typeof parsed.suggestion === 'string' && parsed.suggestion.trim()) {
|
|
958
|
+
const cleaned = cleanMultiline(stripToolCallMarkup(parsed.suggestion), 160).replace(/\s+/g, ' ').trim()
|
|
959
|
+
const isDuplicateGuess = effectiveMode === 'guess' && prevList.some(p => p.toLowerCase() === cleaned.toLowerCase())
|
|
960
|
+
if (cleaned && !isDuplicateGuess) {
|
|
961
|
+
suggestion = clamp(cleaned, 120)
|
|
962
|
+
rationale = clamp(String(parsed.rationale || '').trim(), 90)
|
|
963
|
+
llmUsed = true
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
} catch {}
|
|
968
|
+
|
|
969
|
+
if (!suggestion) {
|
|
970
|
+
const fb = buildFallbackCandidate()
|
|
971
|
+
suggestion = fb.suggestion
|
|
972
|
+
rationale = fb.rationale
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
return {
|
|
976
|
+
ok: true,
|
|
977
|
+
suggestion,
|
|
978
|
+
rationale: rationale || (effectiveMode === 'refine' ? '已在您原文基础上完成微调。' : '已结合当前对话态势为您揣摩建议。'),
|
|
979
|
+
mode: effectiveMode,
|
|
980
|
+
llmUsed,
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
|
|
984
|
+
/**
|
|
985
|
+
* Lead-to-Chief direct communication handler (`chief.request` / `mail.send({ target: 'chief' })`).
|
|
986
|
+
* Applies L0–L3 permission-tiered handling so Lead requests either queue advice + elevation (L0/L1),
|
|
987
|
+
* queue one-click user approval (L2), or execute & reply directly via Chief (L3).
|
|
988
|
+
*/
|
|
989
|
+
export async function handleLeadDirectRequestToChief(deps, {
|
|
990
|
+
fromSession = '',
|
|
991
|
+
fromLabel = '主对话 (@lead)',
|
|
992
|
+
subject = '',
|
|
993
|
+
text = '',
|
|
994
|
+
} = {}) {
|
|
995
|
+
const cleanBody = cleanMultiline(text, 2400)
|
|
996
|
+
if (!cleanBody) return { ok: false, error: '传话给参谋长的内容不能为空' }
|
|
997
|
+
const rootId = (deps && typeof deps.resolveRootSessionId === 'function' ? deps.resolveRootSessionId(fromSession) : '') || String(fromSession || 'global')
|
|
998
|
+
const state = loadChiefState()
|
|
999
|
+
const ownWs = ensureWorkspace(state, rootId)
|
|
1000
|
+
const effCfg = resolveWorkspaceConfig(state, rootId)
|
|
1001
|
+
const hasChiefRiskAck = hasValidChiefRiskAck(ownWs)
|
|
1002
|
+
const permissionMode = normalizePermissionMode(effCfg.permissionMode || DEFAULT_CHIEF_PERMISSION_MODE, {
|
|
1003
|
+
requireAck: true,
|
|
1004
|
+
hasChiefRiskAck,
|
|
1005
|
+
})
|
|
1006
|
+
const permRank = permissionRank(permissionMode)
|
|
1007
|
+
const summaryTitle = clamp(subject || cleanBody, 48)
|
|
1008
|
+
let ledgerTaskId = ''
|
|
1009
|
+
|
|
1010
|
+
// Rare path: Lead / Subagent reports an insurmountable dynamic guard-wall blocker -> read-only Chief evaluation first; any wall removal still requires explicit human approval across L0-L3
|
|
1011
|
+
const combinedReqText = `${subject || ''} ${cleanBody}`
|
|
1012
|
+
const isWallBlockerEscalation = /(?:撞墙阻断|物理驻墙|物理墙|无法绕过|事前物理拦截|guard_wall|wall-[a-z0-9]+)/i.test(combinedReqText)
|
|
1013
|
+
if (isWallBlockerEscalation) {
|
|
1014
|
+
const cwdNow = resolveSessionWorkspaceCwd(deps, rootId)
|
|
1015
|
+
const activeWallsNow = listGuardWalls({ cwd: cwdNow }).filter(w => w && w.scope !== 'paused')
|
|
1016
|
+
if (activeWallsNow.length > 0) {
|
|
1017
|
+
if (!askOrCommandChiefRunner) throw new Error('askOrCommandChief runner not registered')
|
|
1018
|
+
const evalRes = await askOrCommandChiefRunner(deps, {
|
|
1019
|
+
sessionId: rootId,
|
|
1020
|
+
text: `[来自 ${fromLabel} 的撞墙阻断上报 · ${subject || '物理墙评估'}]\n${cleanBody}`,
|
|
1021
|
+
_fromLeadRequest: true,
|
|
1022
|
+
_wallBlockerEscalation: true,
|
|
1023
|
+
})
|
|
1024
|
+
if (evalRes && Array.isArray(evalRes.wallRemovalProposals) && evalRes.wallRemovalProposals.length > 0) {
|
|
1025
|
+
return {
|
|
1026
|
+
ok: true,
|
|
1027
|
+
mode: permissionMode,
|
|
1028
|
+
actionTaken: 'wall_removal_requested',
|
|
1029
|
+
wallRemovalProposals: evalRes.wallRemovalProposals,
|
|
1030
|
+
reply: evalRes.reply || '',
|
|
1031
|
+
...(evalRes.view ? { view: evalRes.view } : {}),
|
|
1032
|
+
}
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
1035
|
+
}
|
|
1036
|
+
|
|
1037
|
+
mutateChiefState((s) => {
|
|
1038
|
+
const ws = ensureWorkspace(s, rootId)
|
|
1039
|
+
const entry = upsertTaskLedgerOnWs(ws, {
|
|
1040
|
+
kind: permRank < 2 ? 'elevation_resume' : (permRank === 2 ? 'approval_resume' : 'tool_execution'),
|
|
1041
|
+
status: permRank < 2 ? 'awaiting_elevation' : (permRank === 2 ? 'awaiting_approval' : 'running'),
|
|
1042
|
+
originalText: `[主对话直传求助 · ${fromLabel}] ${subject ? subject + ':' : ''}${cleanBody}`,
|
|
1043
|
+
forcedTarget: 'lead',
|
|
1044
|
+
lastReceipt: `收到 ${fromLabel} 直传协同请求,按 ${permissionMode} 权限处置中`,
|
|
1045
|
+
})
|
|
1046
|
+
if (entry) ledgerTaskId = entry.taskId
|
|
1047
|
+
})
|
|
1048
|
+
|
|
1049
|
+
// L0 (advisor) / L1 (assistant): queue readable advice + optional elevation request (never mutate workspace directly)
|
|
1050
|
+
if (permRank < 2) {
|
|
1051
|
+
const elv = requestChiefElevation(rootId, {
|
|
1052
|
+
fromMode: permissionMode,
|
|
1053
|
+
targetMode: 'strategist',
|
|
1054
|
+
reason: `主对话(${fromLabel})请求参谋长协同处置:${clamp(subject || cleanBody, 90)}`,
|
|
1055
|
+
requestedActionSummary: clamp(cleanBody, 160),
|
|
1056
|
+
by: 'chief',
|
|
1057
|
+
})
|
|
1058
|
+
mutateChiefState((s) => {
|
|
1059
|
+
const ws = ensureWorkspace(s, rootId)
|
|
1060
|
+
const sug = normalizeSuggestion({
|
|
1061
|
+
kind: 'advice',
|
|
1062
|
+
fromAgent: '📨 主对话直传求助',
|
|
1063
|
+
title: `参谋建议 · 响应主对话:${clamp(summaryTitle, 32)}`,
|
|
1064
|
+
reason: `主对话主动发起协同请示(当前 ${CHIEF_PERMISSION_META[permissionMode]?.level || permissionMode} 只读/参谋档),请您拍板或批准升档执行。`,
|
|
1065
|
+
target: 'lead',
|
|
1066
|
+
targetLabel: '主对话 (@lead)',
|
|
1067
|
+
mode: 'followup',
|
|
1068
|
+
draftText: clamp(`关于「${subject || '协同请求'}」的参谋建议:请先评估影响范围与验证方案;如已批准升档,我可进一步协调执行。原请求:${cleanBody}`, 420),
|
|
1069
|
+
})
|
|
1070
|
+
if (sug) {
|
|
1071
|
+
ws.suggestions.push(sug)
|
|
1072
|
+
if (ws.suggestions.length > SUGGESTIONS_CAP) ws.suggestions = ws.suggestions.slice(-SUGGESTIONS_CAP)
|
|
1073
|
+
}
|
|
1074
|
+
if (ledgerTaskId) {
|
|
1075
|
+
upsertTaskLedgerOnWs(ws, {
|
|
1076
|
+
id: ledgerTaskId,
|
|
1077
|
+
taskId: ledgerTaskId,
|
|
1078
|
+
kind: 'elevation_resume',
|
|
1079
|
+
status: 'awaiting_elevation',
|
|
1080
|
+
originalText: `[主对话直传求助 · ${fromLabel}] ${cleanBody}`,
|
|
1081
|
+
elevationId: elv ? elv.id : '',
|
|
1082
|
+
lastReceipt: `已生成参谋建议${elv ? '并发起 L2 提权请示' : ''}`,
|
|
1083
|
+
})
|
|
1084
|
+
}
|
|
1085
|
+
ws.chat.push({
|
|
1086
|
+
id: nextId('chat'),
|
|
1087
|
+
role: 'chief',
|
|
1088
|
+
kind: 'receipt',
|
|
1089
|
+
text: [
|
|
1090
|
+
`- 【📨 收到主对话直传请求(当前 ${CHIEF_PERMISSION_META[permissionMode]?.level || permissionMode})】来自 ${fromLabel}${subject ? ` · ${subject}` : ''}`,
|
|
1091
|
+
`- 【请求摘要】${clamp(cleanBody, 220)}`,
|
|
1092
|
+
`- 【处置结果】已生成参谋建议并${elv ? '向您发起「🔐 升至 L2 · 参谋模式」提权请示' : '记入建议栏'};您拍板或提权后即可向主对话投递执行批复。`,
|
|
1093
|
+
].join('\n'),
|
|
1094
|
+
actions: ['主对话直传求助', ...(elv ? ['🔐 请示提权 L2'] : ['💡 已呈报建议'])],
|
|
1095
|
+
at: Date.now(),
|
|
1096
|
+
})
|
|
1097
|
+
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
1098
|
+
})
|
|
1099
|
+
return {
|
|
1100
|
+
ok: true,
|
|
1101
|
+
mode: permissionMode,
|
|
1102
|
+
actionTaken: 'suggested_or_elevation_requested',
|
|
1103
|
+
taskId: ledgerTaskId,
|
|
1104
|
+
...(elv ? { elevationRequested: elv } : {}),
|
|
1105
|
+
}
|
|
1106
|
+
}
|
|
1107
|
+
|
|
1108
|
+
// L2 (strategist): queue actionable approval & suggestion for one-click human confirmation
|
|
1109
|
+
if (permRank === 2) {
|
|
1110
|
+
const replyDraft = `已核准来自主对话的协同请求(${subject || '协同处理'}):请按约定继续推进,并在完成后提交验证证据。`
|
|
1111
|
+
const apr = queueChiefApproval(rootId, {
|
|
1112
|
+
category: 'main_workflow',
|
|
1113
|
+
operationLabel: '响应主对话直接协同请求',
|
|
1114
|
+
targetLabel: '主对话 (@lead)',
|
|
1115
|
+
reason: clamp(subject || '主对话请求参谋长协同处置', 140),
|
|
1116
|
+
impact: '点击「允许本次操作」后,将向主对话投递参谋协同批复执行请求',
|
|
1117
|
+
preview: clamp(cleanBody, 240),
|
|
1118
|
+
kind: 'relay',
|
|
1119
|
+
capabilityScope: buildCapabilityScope({ kind: 'relay', tool: 'relay', target: 'lead' }),
|
|
1120
|
+
payload: {
|
|
1121
|
+
fromSession: rootId,
|
|
1122
|
+
fromLabel: 'DSH 参谋 (获批响应主对话)',
|
|
1123
|
+
target: 'lead',
|
|
1124
|
+
subject: subject || '参谋协同批复',
|
|
1125
|
+
text: replyDraft,
|
|
1126
|
+
mode: 'steer',
|
|
1127
|
+
envelopeKind: 'execution_request',
|
|
1128
|
+
taskId: ledgerTaskId,
|
|
1129
|
+
},
|
|
1130
|
+
by: 'chief',
|
|
1131
|
+
})
|
|
1132
|
+
mutateChiefState((s) => {
|
|
1133
|
+
const ws = ensureWorkspace(s, rootId)
|
|
1134
|
+
const sug = normalizeSuggestion({
|
|
1135
|
+
kind: 'relay',
|
|
1136
|
+
fromAgent: '📨 主对话直传求助',
|
|
1137
|
+
title: `批复主对话:${clamp(summaryTitle, 32)}`,
|
|
1138
|
+
reason: 'L2 参谋模式下已挂入逐项授权弹窗,也可直接点击上方「执行建议」批准投递。',
|
|
1139
|
+
target: 'lead',
|
|
1140
|
+
targetLabel: '主对话 (@lead)',
|
|
1141
|
+
mode: 'steer',
|
|
1142
|
+
draftText: replyDraft,
|
|
1143
|
+
})
|
|
1144
|
+
if (sug) {
|
|
1145
|
+
ws.suggestions.push(sug)
|
|
1146
|
+
if (ws.suggestions.length > SUGGESTIONS_CAP) ws.suggestions = ws.suggestions.slice(-SUGGESTIONS_CAP)
|
|
1147
|
+
}
|
|
1148
|
+
if (ledgerTaskId) {
|
|
1149
|
+
upsertTaskLedgerOnWs(ws, {
|
|
1150
|
+
id: ledgerTaskId,
|
|
1151
|
+
taskId: ledgerTaskId,
|
|
1152
|
+
kind: 'approval_resume',
|
|
1153
|
+
status: 'awaiting_approval',
|
|
1154
|
+
originalText: `[主对话直传求助 · ${fromLabel}] ${cleanBody}`,
|
|
1155
|
+
pendingApprovalIds: apr ? [apr.id] : [],
|
|
1156
|
+
lastReceipt: '已挂入 L2 待确认审批与参谋建议',
|
|
1157
|
+
})
|
|
1158
|
+
}
|
|
1159
|
+
ws.chat.push({
|
|
1160
|
+
id: nextId('chat'),
|
|
1161
|
+
role: 'chief',
|
|
1162
|
+
kind: 'receipt',
|
|
1163
|
+
text: [
|
|
1164
|
+
`- 【📨 收到主对话直传请求(L2 · 参谋逐项授权)】来自 ${fromLabel}${subject ? ` · ${subject}` : ''}`,
|
|
1165
|
+
`- 【请求摘要】${clamp(cleanBody, 220)}`,
|
|
1166
|
+
`- 【处置结果】已生成待确认动作${apr ? `(#${apr.id})` : ''}并弹出授权提示,您确认后将立刻投递给主对话。`,
|
|
1167
|
+
].join('\n'),
|
|
1168
|
+
actions: ['主对话直传求助', '🛡️ 待逐项确认'],
|
|
1169
|
+
at: Date.now(),
|
|
1170
|
+
})
|
|
1171
|
+
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
1172
|
+
})
|
|
1173
|
+
return {
|
|
1174
|
+
ok: true,
|
|
1175
|
+
mode: 'strategist',
|
|
1176
|
+
actionTaken: 'queued_for_approval',
|
|
1177
|
+
taskId: ledgerTaskId,
|
|
1178
|
+
approval: apr,
|
|
1179
|
+
}
|
|
1180
|
+
}
|
|
1181
|
+
|
|
1182
|
+
// L3 (chief): directly run Chief handling & reply back to @lead via execution_request
|
|
1183
|
+
if (!askOrCommandChiefRunner) throw new Error('askOrCommandChief runner not registered')
|
|
1184
|
+
const execRes = await askOrCommandChiefRunner(deps, {
|
|
1185
|
+
sessionId: rootId,
|
|
1186
|
+
text: `[来自 ${fromLabel} 的直接协同请求${subject ? ` · ${subject}` : ''}]\n${cleanBody}`,
|
|
1187
|
+
_fromLeadRequest: true,
|
|
1188
|
+
})
|
|
1189
|
+
const alreadyRelayed = Boolean(execRes && Array.isArray(execRes.relays) && execRes.relays.some(r => r && r.ok))
|
|
1190
|
+
if (!alreadyRelayed && execRes && execRes.reply) {
|
|
1191
|
+
try {
|
|
1192
|
+
await deliverCrossMessage(deps, {
|
|
1193
|
+
fromSession: rootId,
|
|
1194
|
+
fromLabel: 'DSH 参谋长 (L3 协同批复)',
|
|
1195
|
+
target: 'lead',
|
|
1196
|
+
subject: subject || '参谋长协同批复',
|
|
1197
|
+
text: execRes.reply,
|
|
1198
|
+
mode: 'steer',
|
|
1199
|
+
envelopeKind: 'execution_request',
|
|
1200
|
+
taskId: ledgerTaskId,
|
|
1201
|
+
})
|
|
1202
|
+
} catch {}
|
|
1203
|
+
}
|
|
1204
|
+
mutateChiefState((s) => {
|
|
1205
|
+
const ws = ensureWorkspace(s, rootId)
|
|
1206
|
+
if (ledgerTaskId) {
|
|
1207
|
+
upsertTaskLedgerOnWs(ws, {
|
|
1208
|
+
id: ledgerTaskId,
|
|
1209
|
+
taskId: ledgerTaskId,
|
|
1210
|
+
kind: 'tool_execution',
|
|
1211
|
+
status: execRes && execRes.ok === false ? 'failed' : 'completed',
|
|
1212
|
+
originalText: `[主对话直传求助 · ${fromLabel}] ${cleanBody}`,
|
|
1213
|
+
lastReceipt: clamp((execRes && (execRes.reply || execRes.error)) || 'L3 参谋长已完成处置', 220),
|
|
1214
|
+
resolvedAt: Date.now(),
|
|
1215
|
+
})
|
|
1216
|
+
}
|
|
1217
|
+
})
|
|
1218
|
+
return {
|
|
1219
|
+
ok: Boolean(execRes && execRes.ok !== false),
|
|
1220
|
+
mode: 'chief',
|
|
1221
|
+
actionTaken: 'executed_directly',
|
|
1222
|
+
taskId: ledgerTaskId,
|
|
1223
|
+
reply: (execRes && execRes.reply) || '',
|
|
1224
|
+
...(execRes && execRes.view ? { view: execRes.view } : {}),
|
|
1225
|
+
}
|
|
1226
|
+
}
|