dsh-chief 1.2.1 → 1.3.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 +47 -16
- package/README.en.md +5 -3
- package/README.md +5 -3
- package/api-routes.js +1274 -0
- package/archive-cabinets.js +766 -0
- package/archive-core.js +761 -0
- package/archive-dossiers.js +1185 -0
- package/archive-precipitated.js +428 -0
- package/archives.js +63 -2991
- package/board-actions.js +1879 -0
- package/board-schema.js +580 -0
- package/board-store.js +392 -0
- package/chief-approvals.js +841 -0
- package/chief-archives.js +905 -0
- package/chief-commands.js +2513 -0
- package/chief-compaction.js +591 -0
- package/chief-executor.js +196 -22
- package/chief-models.js +578 -0
- package/chief-network.js +720 -0
- package/chief-review.js +1064 -0
- package/chief-state.js +1777 -0
- package/chief-view.js +553 -0
- package/chief.js +94 -8541
- package/client.js +11834 -11638
- package/index.js +154 -6363
- package/model-tools.js +755 -0
- package/package.json +28 -1
- package/runtime-hooks.js +629 -0
- package/subagent-runtime.js +1399 -0
|
@@ -0,0 +1,2513 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* chief-commands.js
|
|
3
|
+
*
|
|
4
|
+
* Natural-language command execution, tool loop orchestration, boundary consolidation, and objective suggestion for DSH Chief.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import path from 'node:path'
|
|
8
|
+
import {
|
|
9
|
+
resolveProjectKey,
|
|
10
|
+
loadArchiveStore,
|
|
11
|
+
listArchiveHeaders,
|
|
12
|
+
getArchiveDetail,
|
|
13
|
+
searchArchives,
|
|
14
|
+
searchGlobalVaultForChief,
|
|
15
|
+
mutateArchive,
|
|
16
|
+
copyPrecipitatedToVault,
|
|
17
|
+
getFlippedOutPrecipitatedForSession,
|
|
18
|
+
listPrecipitatedHeaders,
|
|
19
|
+
mutatePrecipitated,
|
|
20
|
+
} from './archives.js'
|
|
21
|
+
import {
|
|
22
|
+
DEFAULT_CHIEF_PERMISSION_MODE,
|
|
23
|
+
CHIEF_PERMISSION_META,
|
|
24
|
+
normalizePermissionMode,
|
|
25
|
+
permissionRank,
|
|
26
|
+
getToolOpClass,
|
|
27
|
+
evaluateSafetyGuardHardRules,
|
|
28
|
+
evaluateChiefPermissionGate,
|
|
29
|
+
CHIEF_TOOLS_PROMPT_GUIDE,
|
|
30
|
+
runChiefAgenticLoop,
|
|
31
|
+
stripToolCallMarkup,
|
|
32
|
+
} from './chief-executor.js'
|
|
33
|
+
import {
|
|
34
|
+
FACTS_CAP,
|
|
35
|
+
FACT_TEXT_MAX,
|
|
36
|
+
CHAT_CAP,
|
|
37
|
+
SUGGESTIONS_CAP,
|
|
38
|
+
SUMMARY_MAX_TOKENS,
|
|
39
|
+
archiveTargetForRoot,
|
|
40
|
+
collectChiefVisibleArchives,
|
|
41
|
+
persistChiefImagesToWorkspace,
|
|
42
|
+
admitChiefImages,
|
|
43
|
+
nextId,
|
|
44
|
+
clamp,
|
|
45
|
+
cleanMultiline,
|
|
46
|
+
secretLike,
|
|
47
|
+
hasValidChiefRiskAck,
|
|
48
|
+
normalizeFact,
|
|
49
|
+
normalizeSuggestion,
|
|
50
|
+
resolveWorkspaceConfig,
|
|
51
|
+
appendChiefAuditLog,
|
|
52
|
+
queueChiefApproval,
|
|
53
|
+
requestChiefElevation,
|
|
54
|
+
upsertResumeTaskOnWs,
|
|
55
|
+
loadChiefState,
|
|
56
|
+
mutateChiefState,
|
|
57
|
+
getLinkedCluster,
|
|
58
|
+
setPeerLink,
|
|
59
|
+
ensureWorkspace,
|
|
60
|
+
clusterView,
|
|
61
|
+
shortAgentBriefName,
|
|
62
|
+
stripCheckpointNoise,
|
|
63
|
+
isInternalCheckpointNoise,
|
|
64
|
+
updateWorkspaceFlippedIds,
|
|
65
|
+
extractJsonObject,
|
|
66
|
+
} from './chief-state.js'
|
|
67
|
+
import { callChiefLlm } from './chief-models.js'
|
|
68
|
+
import { collectClusterPeerProgress, listPeerDirectory, deliverCrossMessage } from './chief-network.js'
|
|
69
|
+
import {
|
|
70
|
+
sanitizeConciseBriefText,
|
|
71
|
+
buildConciseSixLineReport,
|
|
72
|
+
summarizeSubagentsCompact,
|
|
73
|
+
getChiefView,
|
|
74
|
+
} from './chief-view.js'
|
|
75
|
+
import { organizeArchivesWithChief, distillSessionArchivesToGlobal, buildChiefArchiveUpsertFn } from './chief-archives.js'
|
|
76
|
+
import { buildChiefCompactFn } from './chief-compaction.js'
|
|
77
|
+
|
|
78
|
+
const ASK_CHIEF_SYSTEM = [
|
|
79
|
+
'你是「DSH 参谋长」(DSH Chief)——遵循四级权限安全架构(`L0 顾问 advisor` / `L1 助手 assistant` / `L2 参谋 strategist` / `L3 参谋长 chief`)的协同参谋中枢,新对话默认位于最低只读档 `L0 顾问模式`。',
|
|
80
|
+
'你**绝不只是**被动的记忆检索器或传话筒!在当前所处权限允许范围内,你既可以动用实权工具直接核验/执行(或申请提权),也实时掌握:',
|
|
81
|
+
'1) 主代理(@lead)与各子代理的**实时对话流快照**(刚刚说了什么、正在调什么工具、卡在哪里);',
|
|
82
|
+
'2) 参谋看板总目标、实时断点游标(cursor)、计划(plan)与任务拓扑(推进中 / 受阻 / 待办 / 已完成证据);',
|
|
83
|
+
'3) 双层工作边界(📌 定住全局跨任务共享边界 vs 仅当前任务边界)与持久记忆、便签、协同信箱。',
|
|
84
|
+
'',
|
|
85
|
+
'请精准洞悉用户意图——你的输入框就是用户的【全能许愿框】(态势汇报、只读核查、整理/维护看板与档案、修改工作区文件、调整主代理与子代理工作流、连接/断开协同网络或申请提权),并**只输出一个合法 JSON 对象**:',
|
|
86
|
+
'{',
|
|
87
|
+
' "reply": "必须【简明、结构化、分点作答】!用换行 `- 【标签】结论` 列出(优先使用语义清晰标签:如【总目标】【实测执行】【推进中】【已完】【已验证】【结论】【待办】【受阻】【禁止红线】【权限提示】【下一步建议】),直给干货,绝不说『记忆里没有这条』,绝不堆砌废话或暴露内部 sessionId",',
|
|
88
|
+
' "toolCalls": [',
|
|
89
|
+
' { "tool": "read_file|list_dir|search_files|write_file|edit_file|run_command|main_agent_control|subagent_dispatch|subagent_steer|subagent_interrupt|archive_write|session_compact|request_permission_elevation", "args": {} }',
|
|
90
|
+
' ],',
|
|
91
|
+
' "elevationRequest": {',
|
|
92
|
+
' "targetMode": "assistant|strategist|chief",',
|
|
93
|
+
' "reason": "说明为何需要用户批准提权",',
|
|
94
|
+
' "requestedActionSummary": "拟执行的核心动作简述"',
|
|
95
|
+
' },',
|
|
96
|
+
' "relays": [',
|
|
97
|
+
' { "target": "成员 key 或名字(如 lead / 子代理名 / session-xxx / all)", "mode": "steer|followup|silent", "subject": "简短事由", "text": "替用户转化好的清晰可执行指令" }',
|
|
98
|
+
' ],',
|
|
99
|
+
' "memoryChanges": [',
|
|
100
|
+
' { "op": "add", "category": "discipline|architecture|progress|preference|team", "text": "一句独立完整的持久事实或规矩(不超过200字,绝不存密钥密码)" },',
|
|
101
|
+
' { "op": "edit", "index": 2, "text": "替换第2条的新内容" },',
|
|
102
|
+
' { "op": "remove", "index": 3 }',
|
|
103
|
+
' ],',
|
|
104
|
+
' "boundProposals": [',
|
|
105
|
+
' {',
|
|
106
|
+
' "field": "forbidden|allowed|notes",',
|
|
107
|
+
' "item": "拟请示用户注入的一句话高密度边界条文",',
|
|
108
|
+
' "reason": "撞墙教训、提炼依据或浓缩说明",',
|
|
109
|
+
' "replaces": ["可选:当把多条零散边界浓缩合并成一条时,逐字列出被合并替代的原边界条文"],',
|
|
110
|
+
' "pinGlobal": false',
|
|
111
|
+
' }',
|
|
112
|
+
' ],',
|
|
113
|
+
' "boardOps": [',
|
|
114
|
+
' { "op": "objective.set", "objective": "新总目标" },',
|
|
115
|
+
' { "op": "task.add", "title": "任务名", "owner": "可选负责人", "priority": "high|normal|low" },',
|
|
116
|
+
' { "op": "task.update", "id": "已有任务ID", "status": "todo|doing|blocked|done", "note": "可选进展或阻塞说明", "evidence": "可选完成证据", "owner": "可选负责人" },',
|
|
117
|
+
' { "op": "task.remove", "id": "要删除的任务ID" },',
|
|
118
|
+
' { "op": "task.reset", "status": "可选(all|open|done),清空/重设任务列表", "resetPlan": false },',
|
|
119
|
+
' { "op": "graph.plan", "replace": false, "objective": "可选新目标", "tasks": [{ "id": "step1", "title": "重编任务", "owner": "", "priority": "high|normal|low", "blockedBy": [] }] },',
|
|
120
|
+
' { "op": "cursor.set", "step": "当前步骤", "next": "下一步具体动作", "blocked": "阻塞点(无则空串)" },',
|
|
121
|
+
' { "op": "bounds.set", "field": "forbidden|allowed|notes", "items": ["整列覆盖的新边界条文列表"] },',
|
|
122
|
+
' { "op": "bounds.forbid", "item": "用户明确下令立即写入的禁止红线", "pinGlobal": false },',
|
|
123
|
+
' { "op": "bounds.allow", "item": "用户明确下令立即写入的必做事项", "pinGlobal": false },',
|
|
124
|
+
' { "op": "bounds.note", "item": "用户明确下令立即写入的注意事项", "pinGlobal": false },',
|
|
125
|
+
' { "op": "bounds.remove", "field": "forbidden|allowed|notes", "item": "要移除的旧边界条文", "pinGlobal": false }',
|
|
126
|
+
' ],',
|
|
127
|
+
' "archiveOps": [',
|
|
128
|
+
' { "op": "organize", "vaultScope": "session|global", "scope": "unorganized|all", "instruction": "整理分类要求" },',
|
|
129
|
+
' { "op": "distill_to_global", "ids": ["可选:指定本局档案ID,留空自动筛选可复用本局经验"], "instruction": "提炼入全局要求" },',
|
|
130
|
+
' { "op": "take_out|put_back|mount_chief|unmount_chief|copy_to_global|copy_to_session|pull_precipitated|delete", "vaultScope": "session|global|precipitated", "id": "目标档案ID", "title": "或标题关键词", "targetScope": "session|global" },',
|
|
131
|
+
' { "op": "save", "vaultScope": "session|global", "title": "档案标题", "folder": "inbox|architecture|contracts|pitfalls|ops", "summary": "摘要", "body": "正文", "takeOut": false }',
|
|
132
|
+
' ],',
|
|
133
|
+
' "networkOps": [',
|
|
134
|
+
' { "op": "link|unlink", "targetSessionId": "目标独立会话ID或名称关键词" }',
|
|
135
|
+
' ]',
|
|
136
|
+
'}',
|
|
137
|
+
'',
|
|
138
|
+
'宰相参谋与行事准则:',
|
|
139
|
+
'- 【实权执行优先(禁止退化为纯传话筒)】:当用户要求你直接查文件、检查代码、修改补丁、跑测试/命令、直接派发/纠偏/中断子代理、记入档案或立即压缩时,务必先用 `toolCalls` 亲自执行并拿回真实结果后再汇报!只有用户明确要求转告 `@lead` / 其他窗口,或明确属主对话长程编码任务时,才使用 `relays` 递话。',
|
|
140
|
+
'- 【许愿框全权自治】:无论整理/分类/提炼档案入全局、上下桌面、设定/覆盖/清空边界、重设/重编任务(`task.reset`/`graph.plan`),还是连接/断开独立窗口协同网络(`networkOps`),只要用户开口许愿且符合当前权限,直接输出对应 JSON ops 执行到位(严禁越级让本局档案直接跳级沉淀,必须遵循 `本局 -> 全局 -> 沉淀` 梯度),绝不推辞让用户自己去点按钮!',
|
|
141
|
+
'- 【严守当前权限与禁止红线】:绝不越过当前权限等级上限,也绝不执行触发 `禁止红线 (forbidden)` 的写操作或高危命令。',
|
|
142
|
+
'- 【问进展 / 问步骤 / 问卡点 / 求建议】:当用户询问“现在在做什么 / 处于什么步骤 / 目前进度如何 / 卡在哪里”等态势问题时,你面前的上下文已经完整包含「实时对话流快照」+「小任务板 (Plan)」+「任务图」+「断点游标」!直接用简明人话分点作答并放进 JSON 的 `reply` 字段,**严禁退化成纯工具 XML/DSML 标签输出,更严禁盲目运行 `run_command` / `list_dir` 扫盘**!只有用户明确要求去核查具体源码文件/跑命令实测时,才在 JSON `toolCalls` 里调工具。',
|
|
143
|
+
'- 【代维护看板】:当用户让你「把某任务标为完成/受阻」「记一下下一步干啥」「改总目标」时,直接通过 `boardOps`(`task.update` / `cursor.set` / `objective.set` / `task.add`)落实(若强介入已锁定核心目标,则提示先解锁或关闭强介入)。',
|
|
144
|
+
'- 【边界奏请与零散浓缩】:',
|
|
145
|
+
' 1) 总结踩坑红线或必做要求时,生成 `boundProposals` 呈交用户拍板(若用户提到「全局定住/以后所有任务都生效」则设 `"pinGlobal": true`);只有用户明确下令「直接写进禁止/必做边界」时才用 `boardOps`。',
|
|
146
|
+
' 2) 当用户要求「把重要的零散边界总结成一条 / 合并重复边界」时,仔细阅读现有边界,保留关键命令名/路径/硬红线,浓缩为 1 条精炼总则放入 `boundProposals[0].item`,并把被它吸收替代的旧条文原样放进 `replaces` 数组(若被合并旧规中含 📌 全局定住项,则 `"pinGlobal": true`)。',
|
|
147
|
+
'- 【看图与带图拆话】:当用户附带上传图片时,请直接结合图片画面诊断 UI 样式、报错截图或架构图;若你在 relays 中向代理拆话派活,系统会自动把用户附带的图片一并转送给目标代理。',
|
|
148
|
+
].join('\n')
|
|
149
|
+
|
|
150
|
+
const CONCISE_BRIEF_ASK_EXTRA = [
|
|
151
|
+
'',
|
|
152
|
+
'⚡ 【极简战报模式已开启 — reply 字段强约束(六句话目标边界系列)】:',
|
|
153
|
+
'- 一切以目标为导向,说人话,拒绝任何文件/代码/命令/端口/数字/计数等事务细节!',
|
|
154
|
+
'- 总结现状或汇报进度时,优先按如下 6 条一句话边界结构输出:',
|
|
155
|
+
' ## 极简目标战报',
|
|
156
|
+
' - 【🎯 总目标】一句话说清最终目标',
|
|
157
|
+
' - 【🚀 当前推进目标】一句话说清正在推进的目标',
|
|
158
|
+
' - 【⛔ 受阻目标】一句话点明受阻处或“当前暂无受阻目标”',
|
|
159
|
+
' - 【🧰 需要什么】一句话说明还需什么条件或验证',
|
|
160
|
+
' - 【🙋 用户需要提供什么】一句话说明需用户提供/拍板的内容(或“暂无需您额外提供”)',
|
|
161
|
+
' - 【💡 参谋长建议】一句话给出明确建议',
|
|
162
|
+
].join('\n')
|
|
163
|
+
|
|
164
|
+
const CONSOLIDATE_BOUNDS_SYSTEM = [
|
|
165
|
+
'你是「DSH 参谋长」(宰相级边界治理中枢)。用户的边界列表中积累了多条零散、重复或同一主题的规则。',
|
|
166
|
+
'请将给定的多条零散边界**浓缩合并成唯一 1 条**高信息密度、表述清晰、可直接执行的精炼总则(不超过 180 字)。',
|
|
167
|
+
'硬性要求:',
|
|
168
|
+
'- 必须完整保留关键具象锚点(如禁止的具体命令 `git push` / `install_bundle`、具体目录路径、权限红线),绝不能浓缩成空洞套话!',
|
|
169
|
+
'- 用紧凑的分号或并列短句收纳核心约束,去除重复啰嗦的铺垫词。',
|
|
170
|
+
'- **只输出一个合法 JSON 对象**:',
|
|
171
|
+
'{',
|
|
172
|
+
' "item": "浓缩合并后的单条精炼边界总则(≤180字)",',
|
|
173
|
+
' "reason": "简述合并了哪几类零散约束(≤70字)"',
|
|
174
|
+
'}',
|
|
175
|
+
].join('\n')
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* Inspect live in-memory conversation streams (`agent.session.deriveMessages()`)
|
|
179
|
+
* across `@lead` and active/recent `@subagents` so DSH Chief has real-time
|
|
180
|
+
* situational awareness even before a turn settles into `board.tasks` or `board.memory`.
|
|
181
|
+
*/
|
|
182
|
+
function collectLiveConversationsDigest(deps, rootId, directory) {
|
|
183
|
+
const entries = []
|
|
184
|
+
const runtime = deps && deps.runtime
|
|
185
|
+
const agentsSvc = runtime ? runtime.get('agents') : null
|
|
186
|
+
if (!agentsSvc || typeof agentsSvc.get !== 'function') {
|
|
187
|
+
return { entries, summaryLines: [] }
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const allTargets = Array.isArray(directory && directory.targets) ? directory.targets : []
|
|
191
|
+
// Filter out idle internal checkpoint probes (`mnemon-review-*`) so real workers stand out
|
|
192
|
+
const meaningfulTargets = allTargets.filter(t => {
|
|
193
|
+
if (!t || !t.id) return false
|
|
194
|
+
if (t.kind === 'lead') return true
|
|
195
|
+
if (t.status === 'running') return true
|
|
196
|
+
return !/^mnemon-review/i.test(String(t.name || t.handle || ''))
|
|
197
|
+
})
|
|
198
|
+
|
|
199
|
+
// Prioritize: lead first, then running subagents/peers, then up to 4 recent workers
|
|
200
|
+
const ordered = [
|
|
201
|
+
...meaningfulTargets.filter(t => t.kind === 'lead'),
|
|
202
|
+
...meaningfulTargets.filter(t => t.kind !== 'lead' && t.status === 'running'),
|
|
203
|
+
...meaningfulTargets.filter(t => t.kind !== 'lead' && t.status !== 'running'),
|
|
204
|
+
].slice(0, 6)
|
|
205
|
+
|
|
206
|
+
if (!ordered.length && rootId) {
|
|
207
|
+
ordered.push({ key: 'lead', id: rootId, handle: 'lead', name: '主对话', kind: 'lead', status: 'idle', taskTitle: '' })
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
for (const peer of ordered) {
|
|
211
|
+
let agent = null
|
|
212
|
+
try {
|
|
213
|
+
agent = agentsSvc.get(peer.id)
|
|
214
|
+
} catch {}
|
|
215
|
+
if (!agent || !agent.session || typeof agent.session.deriveMessages !== 'function') continue
|
|
216
|
+
|
|
217
|
+
let msgs = []
|
|
218
|
+
try {
|
|
219
|
+
msgs = agent.session.deriveMessages() || []
|
|
220
|
+
} catch {
|
|
221
|
+
continue
|
|
222
|
+
}
|
|
223
|
+
if (!Array.isArray(msgs) || !msgs.length) continue
|
|
224
|
+
|
|
225
|
+
const liveStatus = agent.status === 'running' ? 'running' : (peer.status || 'idle')
|
|
226
|
+
let lastUser = ''
|
|
227
|
+
const recentAssistant = []
|
|
228
|
+
const recentTools = []
|
|
229
|
+
|
|
230
|
+
const tail = msgs.slice(-8)
|
|
231
|
+
for (const m of tail) {
|
|
232
|
+
if (!m || !m.role) continue
|
|
233
|
+
const isInjected = m.source && m.source.kind && m.source.kind !== 'user'
|
|
234
|
+
const blocks = Array.isArray(m.content)
|
|
235
|
+
? m.content
|
|
236
|
+
: (typeof m.content === 'string' ? [{ type: 'text', text: m.content }] : [])
|
|
237
|
+
|
|
238
|
+
const textParts = []
|
|
239
|
+
for (const b of blocks) {
|
|
240
|
+
if (!b || typeof b !== 'object') continue
|
|
241
|
+
if (b.type === 'text' && typeof b.text === 'string') {
|
|
242
|
+
textParts.push(b.text)
|
|
243
|
+
} else if ((b.type === 'tool_use' || b.type === 'tool-call' || b.type === 'toolCall') && (b.name || b.toolName)) {
|
|
244
|
+
const tName = String(b.name || b.toolName)
|
|
245
|
+
let argHint = ''
|
|
246
|
+
try {
|
|
247
|
+
const rawArgs = b.input || b.arguments || b.args
|
|
248
|
+
const obj = typeof rawArgs === 'string' ? JSON.parse(rawArgs) : rawArgs
|
|
249
|
+
if (obj && typeof obj === 'object') {
|
|
250
|
+
const keyVal = obj.command || obj.cmd || obj.action || obj.path || obj.file_path || obj.query || obj.url || obj.agent || obj.title || ''
|
|
251
|
+
if (keyVal && !secretLike(String(keyVal))) argHint = clamp(String(keyVal), 48)
|
|
252
|
+
}
|
|
253
|
+
} catch {}
|
|
254
|
+
recentTools.push(argHint ? `${tName}(${argHint})` : tName)
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
const txt = stripCheckpointNoise(textParts.join('\n').trim())
|
|
259
|
+
if (!txt || isInternalCheckpointNoise(txt) || secretLike(txt)) continue
|
|
260
|
+
|
|
261
|
+
if (m.role === 'user' && !isInjected) {
|
|
262
|
+
lastUser = clamp(txt, 260)
|
|
263
|
+
} else if (m.role === 'assistant') {
|
|
264
|
+
recentAssistant.push(clamp(txt, 380))
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
if (!lastUser && !recentAssistant.length && !recentTools.length) continue
|
|
269
|
+
entries.push({
|
|
270
|
+
key: peer.key,
|
|
271
|
+
handle: peer.handle || peer.name || peer.key,
|
|
272
|
+
kind: peer.kind,
|
|
273
|
+
status: liveStatus,
|
|
274
|
+
taskTitle: peer.taskTitle || '',
|
|
275
|
+
lastUser,
|
|
276
|
+
lastAssistant: recentAssistant.length ? recentAssistant[recentAssistant.length - 1] : '',
|
|
277
|
+
recentTools: recentTools.slice(-4),
|
|
278
|
+
})
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
const summaryLines = entries.map((e) => {
|
|
282
|
+
const parts = [`- **@${e.handle}** [${e.status === 'running' ? '🟢运行中' : '⚪空闲'}]${e.taskTitle ? '(负责:' + clamp(e.taskTitle, 48) + ')' : ''}`]
|
|
283
|
+
if (e.lastUser) parts.push(` · 最近用户指令:${e.lastUser}`)
|
|
284
|
+
if (e.recentTools.length) parts.push(` · 近期工具动作:${e.recentTools.join(' → ')}`)
|
|
285
|
+
if (e.lastAssistant) parts.push(` · 最新回复/进展:${e.lastAssistant}`)
|
|
286
|
+
return parts.join('\n')
|
|
287
|
+
})
|
|
288
|
+
|
|
289
|
+
return { entries, summaryLines }
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
export function applyFactChanges(ws, numberedFacts, changes, actor = 'user', meta = {}) {
|
|
293
|
+
const applied = []
|
|
294
|
+
if (!Array.isArray(changes) || !changes.length) return applied
|
|
295
|
+
const originRootId = typeof meta.originRootId === 'string' ? meta.originRootId : ''
|
|
296
|
+
const clusterRoots = Array.isArray(meta.peerRootIds) ? meta.peerRootIds : []
|
|
297
|
+
|
|
298
|
+
for (const ch of changes.slice(0, 12)) {
|
|
299
|
+
if (!ch || typeof ch !== 'object') continue
|
|
300
|
+
const op = String(ch.op || '').trim()
|
|
301
|
+
if (op === 'add') {
|
|
302
|
+
const category = ch.category || 'discipline'
|
|
303
|
+
const fact = normalizeFact({
|
|
304
|
+
text: ch.text,
|
|
305
|
+
category,
|
|
306
|
+
by: actor,
|
|
307
|
+
source: 'chief',
|
|
308
|
+
originRootId: originRootId && originRootId !== 'global' ? originRootId : '',
|
|
309
|
+
peerRootIds: category === 'team' ? clusterRoots : [],
|
|
310
|
+
})
|
|
311
|
+
if (!fact) continue
|
|
312
|
+
const dup = ws.facts.find(f => f.text === fact.text)
|
|
313
|
+
if (dup) {
|
|
314
|
+
dup.updatedAt = Date.now()
|
|
315
|
+
continue
|
|
316
|
+
}
|
|
317
|
+
ws.facts.push(fact)
|
|
318
|
+
if (ws.facts.length > FACTS_CAP) ws.facts = ws.facts.slice(-FACTS_CAP)
|
|
319
|
+
applied.push({ op: 'add', text: fact.text })
|
|
320
|
+
} else if (op === 'edit') {
|
|
321
|
+
const target = numberedFacts[Number(ch.index) - 1]
|
|
322
|
+
const nextText = clamp(ch.text, FACT_TEXT_MAX)
|
|
323
|
+
if (!target || !nextText || secretLike(nextText)) continue
|
|
324
|
+
const found = ws.facts.find(f => f.id === target.id)
|
|
325
|
+
if (found && !found.pinned) {
|
|
326
|
+
found.text = nextText
|
|
327
|
+
found.updatedAt = Date.now()
|
|
328
|
+
applied.push({ op: 'edit', text: nextText })
|
|
329
|
+
}
|
|
330
|
+
} else if (op === 'remove') {
|
|
331
|
+
const target = numberedFacts[Number(ch.index) - 1]
|
|
332
|
+
if (!target) continue
|
|
333
|
+
const idx = ws.facts.findIndex(f => f.id === target.id)
|
|
334
|
+
if (idx !== -1 && !ws.facts[idx].pinned) {
|
|
335
|
+
const [removed] = ws.facts.splice(idx, 1)
|
|
336
|
+
applied.push({ op: 'remove', text: removed.text })
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
return applied
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
export function applyBoardOps(deps, rootId, boardOps, opts = {}) {
|
|
344
|
+
const executed = []
|
|
345
|
+
if (!Array.isArray(boardOps) || !boardOps.length || !deps || typeof deps.runAction !== 'function') return executed
|
|
346
|
+
const forceSessionOnly = Boolean(opts && opts.forceSessionOnly)
|
|
347
|
+
const allowLockedObjectiveWrite = Boolean(opts && opts.allowLockedObjectiveWrite)
|
|
348
|
+
const effCfg = resolveWorkspaceConfig(loadChiefState(), rootId)
|
|
349
|
+
const objectiveLocked = Boolean(effCfg && effCfg.tacticalModes && effCfg.tacticalModes.intervention) && !allowLockedObjectiveWrite
|
|
350
|
+
|
|
351
|
+
for (const opItem of boardOps.slice(0, 10)) {
|
|
352
|
+
if (!opItem || typeof opItem !== 'object') continue
|
|
353
|
+
const op = String(opItem.op || '').trim()
|
|
354
|
+
if (op === 'objective.set' && opItem.objective) {
|
|
355
|
+
if (objectiveLocked) {
|
|
356
|
+
executed.push('核心目标已锁定(强介入进行中,跳过改写)')
|
|
357
|
+
continue
|
|
358
|
+
}
|
|
359
|
+
deps.runAction({ action: 'objective.set', objective: String(opItem.objective), session: rootId, by: 'chief' })
|
|
360
|
+
executed.push('更新目标:' + clamp(opItem.objective, 40))
|
|
361
|
+
} else if (op === 'task.add' && opItem.title) {
|
|
362
|
+
deps.runAction({
|
|
363
|
+
action: 'task.add',
|
|
364
|
+
title: String(opItem.title),
|
|
365
|
+
owner: opItem.owner ? String(opItem.owner) : '',
|
|
366
|
+
subagent: opItem.owner ? String(opItem.owner) : '',
|
|
367
|
+
priority: opItem.priority || 'normal',
|
|
368
|
+
session: rootId,
|
|
369
|
+
by: 'chief',
|
|
370
|
+
})
|
|
371
|
+
executed.push('新增任务:' + clamp(opItem.title, 40))
|
|
372
|
+
} else if (op === 'task.update' && (opItem.id || opItem.taskId)) {
|
|
373
|
+
const tid = String(opItem.id || opItem.taskId).trim()
|
|
374
|
+
const res = deps.runAction({
|
|
375
|
+
action: 'task.update',
|
|
376
|
+
id: tid,
|
|
377
|
+
...(typeof opItem.status === 'string' ? { status: opItem.status } : {}),
|
|
378
|
+
...(typeof opItem.note === 'string' ? { note: opItem.note } : {}),
|
|
379
|
+
...(typeof opItem.evidence === 'string' ? { evidence: opItem.evidence } : {}),
|
|
380
|
+
...(typeof opItem.owner === 'string' ? { owner: opItem.owner } : {}),
|
|
381
|
+
session: rootId,
|
|
382
|
+
by: 'chief',
|
|
383
|
+
})
|
|
384
|
+
if (res && res.ok) executed.push(`更新任务 #${tid}${opItem.status ? ' → ' + opItem.status : ''}`)
|
|
385
|
+
} else if (op === 'task.remove' && (opItem.id || opItem.taskId)) {
|
|
386
|
+
const tid = String(opItem.id || opItem.taskId).trim()
|
|
387
|
+
const res = deps.runAction({ action: 'task.remove', id: tid, session: rootId, by: 'chief' })
|
|
388
|
+
if (res && res.ok) executed.push(`移除任务 #${tid}`)
|
|
389
|
+
} else if (op === 'task.reset') {
|
|
390
|
+
const res = deps.runAction({
|
|
391
|
+
action: 'task.reset',
|
|
392
|
+
...(typeof opItem.status === 'string' ? { status: opItem.status } : {}),
|
|
393
|
+
...(opItem.resetPlan !== undefined ? { resetPlan: Boolean(opItem.resetPlan) } : {}),
|
|
394
|
+
session: rootId,
|
|
395
|
+
by: 'chief',
|
|
396
|
+
})
|
|
397
|
+
if (res && res.ok) executed.push(`重设任务看板(${res.removedCount ?? 0}项)`)
|
|
398
|
+
} else if ((op === 'graph.plan' || op === 'task.batch') && Array.isArray(opItem.tasks) && opItem.tasks.length > 0) {
|
|
399
|
+
const canSetObj = !objectiveLocked && typeof opItem.objective === 'string' && opItem.objective.trim()
|
|
400
|
+
const res = deps.runAction({
|
|
401
|
+
action: 'graph.plan',
|
|
402
|
+
tasks: opItem.tasks,
|
|
403
|
+
...(canSetObj ? { objective: opItem.objective } : {}),
|
|
404
|
+
...(opItem.replace !== undefined ? { replace: Boolean(opItem.replace) } : {}),
|
|
405
|
+
session: rootId,
|
|
406
|
+
by: 'chief',
|
|
407
|
+
})
|
|
408
|
+
if (res && res.ok) executed.push(`重编任务拓扑(${(res.tasks || opItem.tasks).length}项)`)
|
|
409
|
+
} else if (op === 'cursor.set') {
|
|
410
|
+
const res = deps.runAction({
|
|
411
|
+
action: 'cursor.set',
|
|
412
|
+
...(typeof opItem.step === 'string' ? { step: opItem.step } : {}),
|
|
413
|
+
...(typeof opItem.next === 'string' ? { next: opItem.next } : {}),
|
|
414
|
+
...(typeof opItem.blocked === 'string' ? { blocked: opItem.blocked } : {}),
|
|
415
|
+
session: rootId,
|
|
416
|
+
by: 'chief',
|
|
417
|
+
})
|
|
418
|
+
if (res && res.ok) executed.push('更新推进断点')
|
|
419
|
+
} else if (op === 'plan.resetForGoal') {
|
|
420
|
+
const res = deps.runAction({ action: 'plan.resetForGoal', session: rootId, by: 'chief' })
|
|
421
|
+
if (res && res.ok) executed.push('清空陈旧计划以便按新目标重编')
|
|
422
|
+
} else if (op === 'plan.set' && Array.isArray(opItem.steps)) {
|
|
423
|
+
const steps = opItem.steps.map(s => (typeof s === 'string' ? { text: s, done: false } : s)).filter(Boolean)
|
|
424
|
+
if (steps.length > 0) {
|
|
425
|
+
const res = deps.runAction({ action: 'plan.set', steps, session: rootId, by: 'chief' })
|
|
426
|
+
if (res && res.ok) executed.push(`更新计划共 ${steps.length} 步`)
|
|
427
|
+
}
|
|
428
|
+
} else if (op === 'goal.proposeApproval') {
|
|
429
|
+
const res = deps.runAction({
|
|
430
|
+
action: 'goal.proposeApproval',
|
|
431
|
+
objective: String(opItem.objective || ''),
|
|
432
|
+
summary: String(opItem.summary || ''),
|
|
433
|
+
evidence: String(opItem.evidence || ''),
|
|
434
|
+
session: rootId,
|
|
435
|
+
by: 'chief',
|
|
436
|
+
})
|
|
437
|
+
if (res && res.ok) executed.push('呈批目标结项')
|
|
438
|
+
} else if (op === 'bounds.set') {
|
|
439
|
+
const rawField = String(opItem.field || '').trim().toLowerCase()
|
|
440
|
+
const normField = rawField === 'must' ? 'allowed' : rawField
|
|
441
|
+
const col = ['forbidden', 'allowed', 'notes'].includes(normField) ? normField : ''
|
|
442
|
+
if (col && Array.isArray(opItem.items)) {
|
|
443
|
+
const items = opItem.items.map(x => clamp(x, 220)).filter(Boolean)
|
|
444
|
+
const res = deps.runAction({ action: 'bounds.set', field: col, items, session: rootId, by: 'chief' })
|
|
445
|
+
if (res && res.ok) executed.push(`覆写边界(${col})共 ${items.length} 条`)
|
|
446
|
+
} else if (Array.isArray(opItem.allowed) || Array.isArray(opItem.must) || Array.isArray(opItem.forbidden) || Array.isArray(opItem.notes)) {
|
|
447
|
+
const allowList = Array.isArray(opItem.allowed) ? opItem.allowed : opItem.must
|
|
448
|
+
const res = deps.runAction({
|
|
449
|
+
action: 'bounds.set',
|
|
450
|
+
...(Array.isArray(allowList) ? { allowed: allowList.map(x => clamp(x, 220)).filter(Boolean) } : {}),
|
|
451
|
+
...(Array.isArray(opItem.forbidden) ? { forbidden: opItem.forbidden.map(x => clamp(x, 220)).filter(Boolean) } : {}),
|
|
452
|
+
...(Array.isArray(opItem.notes) ? { notes: opItem.notes.map(x => clamp(x, 220)).filter(Boolean) } : {}),
|
|
453
|
+
session: rootId,
|
|
454
|
+
by: 'chief',
|
|
455
|
+
})
|
|
456
|
+
if (res && res.ok) executed.push('重置边界列表')
|
|
457
|
+
}
|
|
458
|
+
} else if ((op === 'bounds.forbid' || op === 'bounds.allow' || op === 'bounds.must' || op === 'bounds.note') && opItem.item) {
|
|
459
|
+
const field = op === 'bounds.forbid' ? 'forbidden' : (op === 'bounds.note' ? 'notes' : 'allowed')
|
|
460
|
+
const label = field === 'forbidden' ? '红线' : (field === 'notes' ? '注意' : '必做')
|
|
461
|
+
const val = clamp(opItem.item, 220)
|
|
462
|
+
const pinned = forceSessionOnly ? false : Boolean(opItem.pinGlobal)
|
|
463
|
+
if (val) {
|
|
464
|
+
const res = deps.runAction({
|
|
465
|
+
action: 'bounds.add',
|
|
466
|
+
field,
|
|
467
|
+
item: val,
|
|
468
|
+
pinned,
|
|
469
|
+
session: rootId,
|
|
470
|
+
by: 'chief',
|
|
471
|
+
})
|
|
472
|
+
if (res && res.ok) {
|
|
473
|
+
executed.push(`${pinned ? '📌全局' : '本任务'}${label}:${clamp(val, 30)}`)
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
} else if (op === 'bounds.remove' && opItem.item) {
|
|
477
|
+
const field = ['forbidden', 'allowed', 'notes'].includes(opItem.field) ? opItem.field : 'forbidden'
|
|
478
|
+
const val = clamp(opItem.item, 220)
|
|
479
|
+
const pinned = forceSessionOnly ? false : Boolean(opItem.pinGlobal)
|
|
480
|
+
if (val) {
|
|
481
|
+
const res = deps.runAction({
|
|
482
|
+
action: 'bounds.remove',
|
|
483
|
+
field,
|
|
484
|
+
item: val,
|
|
485
|
+
pinned,
|
|
486
|
+
session: rootId,
|
|
487
|
+
by: 'chief',
|
|
488
|
+
})
|
|
489
|
+
if (res && res.ok) {
|
|
490
|
+
executed.push(`移除边界:${clamp(val, 30)}`)
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
return executed
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
/**
|
|
499
|
+
* Execute Wishing-Box `archiveOps` across Session / Global / Precipitated vaults
|
|
500
|
+
* while strictly preserving the upward gradient (`session -> global -> precipitated`;
|
|
501
|
+
* direct session -> precipitated jump is forbidden).
|
|
502
|
+
*/
|
|
503
|
+
async function applyArchiveOps(deps, rootId, archiveOps, ctx = {}) {
|
|
504
|
+
const executed = []
|
|
505
|
+
if (!Array.isArray(archiveOps) || !archiveOps.length) return { executed, changed: false }
|
|
506
|
+
const sid = rootId && rootId !== 'global' ? String(rootId).trim() : ''
|
|
507
|
+
const globalOpt = archiveTargetForRoot(deps, sid || 'global', { vaultScope: 'global' })
|
|
508
|
+
const sessionOpt = sid ? archiveTargetForRoot(deps, sid, { vaultScope: 'session' }) : null
|
|
509
|
+
const projectKey = resolveProjectKey(globalOpt.cwd)
|
|
510
|
+
let changed = false
|
|
511
|
+
|
|
512
|
+
const resolveItemInScope = (scope, rawId, rawTitle) => {
|
|
513
|
+
const idQ = String(rawId || '').trim()
|
|
514
|
+
const titleQ = String(rawTitle || '').trim().toLowerCase()
|
|
515
|
+
if (scope === 'precipitated') {
|
|
516
|
+
const items = listPrecipitatedHeaders(projectKey, sid, globalOpt) || []
|
|
517
|
+
if (idQ) {
|
|
518
|
+
const exact = items.find(it => it.id === idQ)
|
|
519
|
+
if (exact) return exact.id
|
|
520
|
+
}
|
|
521
|
+
if (titleQ) {
|
|
522
|
+
const byTitle = items.find(it => String(it.title || '').toLowerCase().includes(titleQ))
|
|
523
|
+
if (byTitle) return byTitle.id
|
|
524
|
+
}
|
|
525
|
+
return idQ
|
|
526
|
+
}
|
|
527
|
+
const opt = scope === 'global' ? globalOpt : sessionOpt
|
|
528
|
+
if (!opt) return idQ
|
|
529
|
+
const store = loadArchiveStore(opt)
|
|
530
|
+
const items = Array.isArray(store.items) ? store.items : []
|
|
531
|
+
if (idQ) {
|
|
532
|
+
const exact = items.find(it => it.id === idQ)
|
|
533
|
+
if (exact) return exact.id
|
|
534
|
+
}
|
|
535
|
+
if (titleQ) {
|
|
536
|
+
const byTitle = items.find(it => String(it.title || '').toLowerCase().includes(titleQ))
|
|
537
|
+
if (byTitle) return byTitle.id
|
|
538
|
+
}
|
|
539
|
+
return idQ
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
for (const opItem of archiveOps.slice(0, 8)) {
|
|
543
|
+
if (!opItem || typeof opItem !== 'object') continue
|
|
544
|
+
const op = String(opItem.op || '').trim()
|
|
545
|
+
const scope = opItem.vaultScope === 'precipitated'
|
|
546
|
+
? 'precipitated'
|
|
547
|
+
: (opItem.vaultScope === 'global' ? 'global' : 'session')
|
|
548
|
+
|
|
549
|
+
if (op === 'organize') {
|
|
550
|
+
const orgScope = opItem.vaultScope === 'global' ? 'global' : 'session'
|
|
551
|
+
if (orgScope === 'session' && !sid) continue
|
|
552
|
+
const r = await organizeArchivesWithChief(deps, {
|
|
553
|
+
sessionId: sid || 'global',
|
|
554
|
+
vaultScope: orgScope,
|
|
555
|
+
ids: Array.isArray(opItem.ids) ? opItem.ids : [],
|
|
556
|
+
scope: opItem.scope === 'all' ? 'all' : 'unorganized',
|
|
557
|
+
instruction: String(opItem.instruction || ctx.input || ''),
|
|
558
|
+
}).catch(() => null)
|
|
559
|
+
if (r && r.ok) {
|
|
560
|
+
changed = true
|
|
561
|
+
executed.push(`整理${orgScope === 'global' ? '全局' : '本局'}档案 ×${r.updatedCount ?? 0}`)
|
|
562
|
+
}
|
|
563
|
+
} else if (op === 'distill_to_global' || op === 'distill') {
|
|
564
|
+
if (!sid) continue
|
|
565
|
+
const r = await distillSessionArchivesToGlobal(deps, {
|
|
566
|
+
sessionId: sid,
|
|
567
|
+
ids: Array.isArray(opItem.ids) ? opItem.ids : (opItem.id ? [opItem.id] : []),
|
|
568
|
+
instruction: String(opItem.instruction || ctx.input || ''),
|
|
569
|
+
}).catch(() => null)
|
|
570
|
+
if (r && r.ok) {
|
|
571
|
+
changed = true
|
|
572
|
+
executed.push(`提炼入全局 ×${r.createdCount ?? 0}`)
|
|
573
|
+
}
|
|
574
|
+
} else if (op === 'save' || op === 'create') {
|
|
575
|
+
if (scope === 'precipitated') continue // strict gradient: cannot write directly into precipitated
|
|
576
|
+
if (scope === 'session' && !sid) continue
|
|
577
|
+
const targetOpt = scope === 'global' ? globalOpt : sessionOpt
|
|
578
|
+
const r = mutateArchive({
|
|
579
|
+
op: 'save',
|
|
580
|
+
vaultScope: scope,
|
|
581
|
+
rootSessionId: sid,
|
|
582
|
+
folder: opItem.folder || 'inbox',
|
|
583
|
+
paperclip: ['gold', 'silver', 'copper'].includes(opItem.paperclip) ? opItem.paperclip : 'silver',
|
|
584
|
+
title: clamp(opItem.title || '参谋长工作归档', 160),
|
|
585
|
+
summary: clamp(opItem.summary || '', 400),
|
|
586
|
+
body: cleanMultiline(opItem.body || opItem.summary || opItem.title || '', 12000),
|
|
587
|
+
takeOutNow: Boolean(opItem.takeOut),
|
|
588
|
+
by: 'chief',
|
|
589
|
+
}, targetOpt)
|
|
590
|
+
if (r && r.ok) {
|
|
591
|
+
changed = true
|
|
592
|
+
executed.push(`存档(${scope === 'global' ? '全局' : '本局'}):《${clamp(opItem.title || '', 24)}》`)
|
|
593
|
+
}
|
|
594
|
+
} else if (op === 'take_out' || op === 'put_back') {
|
|
595
|
+
if (!sid) continue
|
|
596
|
+
const hitId = resolveItemInScope(scope, opItem.id || opItem.archiveId, opItem.title)
|
|
597
|
+
if (!hitId) continue
|
|
598
|
+
if (scope === 'precipitated') {
|
|
599
|
+
const pOp = op === 'take_out' ? 'flipOut' : 'sealBack'
|
|
600
|
+
const r = mutatePrecipitated(projectKey, { op: pOp, id: hitId, rootSessionId: sid }, { ...globalOpt, rootSessionId: sid })
|
|
601
|
+
if (r && r.ok) {
|
|
602
|
+
updateWorkspaceFlippedIds(sid, pOp === 'flipOut' ? { flippedId: hitId } : { sealId: hitId })
|
|
603
|
+
changed = true
|
|
604
|
+
executed.push(`${op === 'take_out' ? '摆上桌面(沉淀)' : '放回封存(沉淀)'} #${hitId}`)
|
|
605
|
+
}
|
|
606
|
+
} else {
|
|
607
|
+
const targetOpt = scope === 'global' ? globalOpt : sessionOpt
|
|
608
|
+
const r = mutateArchive({
|
|
609
|
+
op: op === 'take_out' ? 'takeOut' : 'putBack',
|
|
610
|
+
vaultScope: scope,
|
|
611
|
+
rootSessionId: sid,
|
|
612
|
+
id: hitId,
|
|
613
|
+
}, targetOpt)
|
|
614
|
+
if (r && r.ok) {
|
|
615
|
+
changed = true
|
|
616
|
+
executed.push(`${op === 'take_out' ? '摆上桌面' : '放回封存'} #${hitId}`)
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
} else if (op === 'mount_chief' || op === 'unmount_chief') {
|
|
620
|
+
if (!sid) continue
|
|
621
|
+
const hitId = resolveItemInScope('global', opItem.id || opItem.archiveId, opItem.title)
|
|
622
|
+
if (!hitId) continue
|
|
623
|
+
const r = mutateArchive({
|
|
624
|
+
op: op === 'mount_chief' ? 'mountChief' : 'unmountChief',
|
|
625
|
+
vaultScope: 'global',
|
|
626
|
+
rootSessionId: sid,
|
|
627
|
+
id: hitId,
|
|
628
|
+
}, globalOpt)
|
|
629
|
+
if (r && r.ok) {
|
|
630
|
+
changed = true
|
|
631
|
+
executed.push(`${op === 'mount_chief' ? '参阅全局档案' : '取消全局参阅'} #${hitId}`)
|
|
632
|
+
}
|
|
633
|
+
} else if (op === 'copy_to_global') {
|
|
634
|
+
if (!sid) continue
|
|
635
|
+
const hitId = resolveItemInScope('session', opItem.id || opItem.archiveId, opItem.title)
|
|
636
|
+
if (!hitId) continue
|
|
637
|
+
const r = mutateArchive({ op: 'copyToGlobal', vaultScope: 'session', rootSessionId: sid, id: hitId }, sessionOpt)
|
|
638
|
+
if (r && r.ok) {
|
|
639
|
+
changed = true
|
|
640
|
+
executed.push(`升入全局档案 #${hitId}`)
|
|
641
|
+
}
|
|
642
|
+
} else if (op === 'copy_to_session') {
|
|
643
|
+
if (!sid) continue
|
|
644
|
+
const hitId = resolveItemInScope('global', opItem.id || opItem.archiveId, opItem.title)
|
|
645
|
+
if (!hitId) continue
|
|
646
|
+
const r = mutateArchive({ op: 'copyToSession', vaultScope: 'global', rootSessionId: sid, id: hitId }, globalOpt)
|
|
647
|
+
if (r && r.ok) {
|
|
648
|
+
changed = true
|
|
649
|
+
executed.push(`全局调入本局 #${hitId}`)
|
|
650
|
+
}
|
|
651
|
+
} else if (op === 'pull_precipitated') {
|
|
652
|
+
const targetScope = opItem.targetScope === 'global' ? 'global' : 'session'
|
|
653
|
+
if (targetScope === 'session' && !sid) continue
|
|
654
|
+
const hitId = resolveItemInScope('precipitated', opItem.id || opItem.archiveId, opItem.title)
|
|
655
|
+
if (!hitId) continue
|
|
656
|
+
const r = copyPrecipitatedToVault(projectKey, {
|
|
657
|
+
id: hitId,
|
|
658
|
+
targetScope,
|
|
659
|
+
rootSessionId: sid,
|
|
660
|
+
takeOutNow: Boolean(opItem.takeOut),
|
|
661
|
+
}, { ...globalOpt, rootSessionId: sid })
|
|
662
|
+
if (r && r.ok) {
|
|
663
|
+
changed = true
|
|
664
|
+
executed.push(`沉淀无损调入${targetScope === 'global' ? '全局' : '本局'} #${hitId}`)
|
|
665
|
+
}
|
|
666
|
+
} else if (op === 'move_folder' && opItem.folder) {
|
|
667
|
+
if (scope === 'precipitated') continue
|
|
668
|
+
if (scope === 'session' && !sid) continue
|
|
669
|
+
const targetOpt = scope === 'global' ? globalOpt : sessionOpt
|
|
670
|
+
const hitId = resolveItemInScope(scope, opItem.id || opItem.archiveId, opItem.title)
|
|
671
|
+
if (!hitId) continue
|
|
672
|
+
const r = mutateArchive({ op: 'moveFolder', vaultScope: scope, rootSessionId: sid, id: hitId, folder: opItem.folder }, targetOpt)
|
|
673
|
+
if (r && r.ok) {
|
|
674
|
+
changed = true
|
|
675
|
+
executed.push(`移动档案分类 → ${opItem.folder}`)
|
|
676
|
+
}
|
|
677
|
+
} else if (op === 'delete' || op === 'remove') {
|
|
678
|
+
if (scope === 'precipitated') continue
|
|
679
|
+
if (scope === 'session' && !sid) continue
|
|
680
|
+
const targetOpt = scope === 'global' ? globalOpt : sessionOpt
|
|
681
|
+
const hitId = resolveItemInScope(scope, opItem.id || opItem.archiveId, opItem.title)
|
|
682
|
+
if (!hitId) continue
|
|
683
|
+
const r = mutateArchive({ op: 'delete', vaultScope: scope, rootSessionId: sid, id: hitId }, targetOpt)
|
|
684
|
+
if (r && r.ok) {
|
|
685
|
+
changed = true
|
|
686
|
+
executed.push(`移除${scope === 'global' ? '全局' : '本局'}档案 #${hitId}`)
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
return { executed, changed }
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
/** Execute Wishing-Box `networkOps` to link or unlink standalone DSH sessions. */
|
|
695
|
+
function applyNetworkOps(rootId, networkOps, directory) {
|
|
696
|
+
const executed = []
|
|
697
|
+
if (!Array.isArray(networkOps) || !networkOps.length || !rootId || rootId === 'global') return executed
|
|
698
|
+
const otherSessions = (directory && Array.isArray(directory.otherSessions)) ? directory.otherSessions : []
|
|
699
|
+
|
|
700
|
+
for (const opItem of networkOps.slice(0, 6)) {
|
|
701
|
+
if (!opItem || typeof opItem !== 'object') continue
|
|
702
|
+
const op = String(opItem.op || '').trim()
|
|
703
|
+
if (op !== 'link' && op !== 'unlink') continue
|
|
704
|
+
const rawQ = String(opItem.targetSessionId || opItem.target || opItem.sessionId || opItem.name || '').trim()
|
|
705
|
+
if (!rawQ) continue
|
|
706
|
+
const qLower = rawQ.toLowerCase()
|
|
707
|
+
const match = otherSessions.find(s =>
|
|
708
|
+
s.id === rawQ
|
|
709
|
+
|| String(s.id).toLowerCase().includes(qLower)
|
|
710
|
+
|| (s.name && String(s.name).toLowerCase().includes(qLower))
|
|
711
|
+
)
|
|
712
|
+
const targetSid = match ? match.id : (/^session-/i.test(rawQ) ? rawQ : '')
|
|
713
|
+
if (!targetSid || targetSid === rootId) continue
|
|
714
|
+
const r = setPeerLink(rootId, targetSid, op === 'link')
|
|
715
|
+
if (r && r.ok) {
|
|
716
|
+
executed.push(`${op === 'link' ? '连接协同窗口' : '断开协同窗口'}:${match ? match.name : targetSid.slice(0, 14)}`)
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
return executed
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
/** Detect pure beginner progress/status questions where all truth is already in live snapshot + board (zero disk/shell tools needed). */
|
|
723
|
+
function isPureStatusInquiry(rawText) {
|
|
724
|
+
const q = String(rawText || '').trim()
|
|
725
|
+
if (!q || q.length > 90) return false
|
|
726
|
+
if (/read_file|write_file|edit_file|run_command|list_dir|search_files|执行|运行|测试|跑一下|改一下|写一个|修一下|删除|新建|创建|安装|部署|派发|递话|转告|中断|清[空理]|重设|重置|提炼|浓缩|合并/.test(q)) {
|
|
727
|
+
return false
|
|
728
|
+
}
|
|
729
|
+
return /(?:现在在做什么|在做什么|在干嘛|在干什么|处于什么步骤|什么步骤|第几步|到哪一步|到哪了|做到哪|进度|进展|情况如何|怎么样了|当前状态|实时状态|团队在|主对话在|主代理在|子代理在)/.test(q)
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
/** Detect explicit user requests asking Chief to immediately compress/compact context. */
|
|
733
|
+
export function isExplicitCompactCommand(rawText) {
|
|
734
|
+
const q = String(rawText || '').trim()
|
|
735
|
+
if (!q || q.length > 80) return false
|
|
736
|
+
if (/不要压缩|别压缩|不用压缩|停止压缩|关闭压缩|取消压缩|为什么|为啥|没触发|未触发|不能|无法|报错|失败|是什么|原理|区别|开关|怎么(?:设置|用|开|关)/.test(q)) {
|
|
737
|
+
return false
|
|
738
|
+
}
|
|
739
|
+
if (/^\/compact(?:\s|$)/i.test(q)) return true
|
|
740
|
+
if (!/压缩/.test(q)) return false
|
|
741
|
+
if (/文件|图片|视频|音频|zip|tar|gzip|rar|7z|打包/i.test(q) && !/上下文|对话|会话|历史|记忆|session|context/i.test(q)) {
|
|
742
|
+
return false
|
|
743
|
+
}
|
|
744
|
+
return /^(?:请|麻烦|帮我|给我|你|可以|先|赶紧|立即|立刻|马上|现在|把[\u4e00-\u9fa5]{0,12})*(?:执行|触发|做一下|跑一下|开始|进行|归档并|抢救并)?(?:一键|手动|静默)?(?:当前|一下|下)?(?:上下文|对话|会话|历史|内容|内存)?压缩(?:当前|一下|下)?(?:上下文|对话|会话|历史|内存)?(?:吧|一下|下|呀|啊|哦|嘛|呢|好了|好吗|可以吗|!|!|。|\.)*$/i.test(q)
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
/**
|
|
748
|
+
* Holistic offline/fallback intelligence synthesizer so DSH Chief NEVER
|
|
749
|
+
* utters "记忆里没有这条" even if every configured LLM provider is unreachable.
|
|
750
|
+
*/
|
|
751
|
+
function buildSmartFallbackReply({ input, board, liveDigest, directory, facts = [], mailbox = [], conciseBrief = false }) {
|
|
752
|
+
const q = String(input || '').trim()
|
|
753
|
+
const qLower = q.toLowerCase()
|
|
754
|
+
const tasks = Array.isArray(board && board.tasks) ? board.tasks : []
|
|
755
|
+
const planSteps = Array.isArray(board && board.plan) ? board.plan.filter(Boolean) : []
|
|
756
|
+
const openPlan = planSteps.filter(s => !s.done)
|
|
757
|
+
const donePlan = planSteps.filter(s => s.done)
|
|
758
|
+
const doing = tasks.filter(t => t.status === 'doing')
|
|
759
|
+
const blocked = tasks.filter(t => t.status === 'blocked')
|
|
760
|
+
const todo = tasks.filter(t => t.status === 'todo')
|
|
761
|
+
const done = tasks.filter(t => t.status === 'done')
|
|
762
|
+
const cursor = (board && board.cursor) || {}
|
|
763
|
+
const bounds = (board && board.bounds) || { allowed: [], forbidden: [], notes: [] }
|
|
764
|
+
const pinnedBounds = (board && board.pinnedBounds) || { allowed: [], forbidden: [], notes: [] }
|
|
765
|
+
const workers = ((directory && directory.targets) || []).filter(t => t.kind === 'subagent')
|
|
766
|
+
const runningWorkers = workers.filter(w => w.status === 'running')
|
|
767
|
+
const liveEntries = (liveDigest && liveDigest.entries) || []
|
|
768
|
+
const leadLive = liveEntries.find(e => e.kind === 'lead') || liveEntries[0] || null
|
|
769
|
+
const cleanMem = (Array.isArray(board && board.memory) ? board.memory : [])
|
|
770
|
+
.filter(m => m && !isInternalCheckpointNoise(m.title || m.text))
|
|
771
|
+
|
|
772
|
+
if (conciseBrief) {
|
|
773
|
+
return buildConciseSixLineReport({ board, blocked, doing, todo, done, workers })
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
const asksBounds = /边界|红线|禁止|允许|必做|规矩|约束/.test(q)
|
|
777
|
+
const asksTeam = /子代理|团队|谁在|分工|成员|subagent|worker/i.test(qLower)
|
|
778
|
+
const asksBlocked = /卡在哪|受阻|阻塞|报错|问题|风险|撞墙|block/i.test(qLower)
|
|
779
|
+
const asksProgress = /进展|进度|怎么样|到哪|在做什么|在干嘛|干什么|处于什么步骤|什么步骤|第几步|情况|状态|汇报|总结|下一步|status|progress/i.test(qLower)
|
|
780
|
+
|
|
781
|
+
const bullets = []
|
|
782
|
+
|
|
783
|
+
if (asksBounds) {
|
|
784
|
+
const fList = bounds.forbidden || []
|
|
785
|
+
const aList = bounds.allowed || []
|
|
786
|
+
const nList = bounds.notes || []
|
|
787
|
+
const pinCount = (pinnedBounds.forbidden?.length || 0) + (pinnedBounds.allowed?.length || 0) + (pinnedBounds.notes?.length || 0)
|
|
788
|
+
bullets.push(`- 【生效边界概览】共 ${fList.length + aList.length + nList.length} 条生效(其中 📌 定住全局共享 ${pinCount} 条)。`)
|
|
789
|
+
if (fList.length) bullets.push(`- 【禁止红线】${fList.slice(0, 5).map(x => (pinnedBounds.forbidden?.includes(x) ? '📌' : '') + clamp(x, 60)).join(';')}`)
|
|
790
|
+
if (aList.length) bullets.push(`- 【必做事项】${aList.slice(0, 4).map(x => (pinnedBounds.allowed?.includes(x) ? '📌' : '') + clamp(x, 60)).join(';')}`)
|
|
791
|
+
if (nList.length) bullets.push(`- 【注意事项】${nList.slice(0, 3).map(x => (pinnedBounds.notes?.includes(x) ? '📌' : '') + clamp(x, 60)).join(';')}`)
|
|
792
|
+
if (!fList.length && !aList.length && !nList.length) {
|
|
793
|
+
bullets.push('- 【提示】当前尚未配置边界规则,可在「边界」页添加并点击 📌 定住为跨任务共享,或点「✦ 提炼新边界」。')
|
|
794
|
+
}
|
|
795
|
+
return bullets.join('\n')
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
if (asksTeam && !asksProgress) {
|
|
799
|
+
bullets.push(`- 【团队编制】${workers.length ? summarizeSubagentsCompact(workers) : '当前仅主代理(@lead)单线作业,尚未派生子代理。'}`)
|
|
800
|
+
for (const w of runningWorkers.slice(0, 5)) {
|
|
801
|
+
bullets.push(`- 【运行中 · @${shortAgentBriefName(w.handle)}】${w.taskTitle ? clamp(w.taskTitle, 80) : '正在执行委派任务'}`)
|
|
802
|
+
}
|
|
803
|
+
for (const e of liveEntries.filter(x => x.kind !== 'lead').slice(0, 3)) {
|
|
804
|
+
if (e.lastAssistant || e.recentTools.length) {
|
|
805
|
+
bullets.push(`- 【@${shortAgentBriefName(e.handle)} 现场】${e.recentTools.length ? '调用 ' + e.recentTools.join(' → ') + ';' : ''}${clamp(e.lastAssistant, 100)}`)
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
return bullets.join('\n')
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
// Keyword match across tasks, facts, notes, live stream, and memory if user asked a specific domain question
|
|
812
|
+
if (!asksProgress && !asksBlocked) {
|
|
813
|
+
const tokens = qLower
|
|
814
|
+
.replace(/[??!!。,,、::“”"'()()[\]【】]/g, ' ')
|
|
815
|
+
.split(/\s+/)
|
|
816
|
+
.filter(t => t.length >= 2 && !/^(现在|目前|什么|怎么|请问|帮我|一下|看看|告诉)$/.test(t))
|
|
817
|
+
|
|
818
|
+
const hits = []
|
|
819
|
+
for (const t of tasks) {
|
|
820
|
+
const hay = `${t.title} ${t.note || ''} ${t.evidence || ''}`.toLowerCase()
|
|
821
|
+
if (tokens.some(tk => hay.includes(tk))) {
|
|
822
|
+
hits.push(`- 【任务 #${t.id} · ${t.status}】${clamp(t.title, 65)}${t.evidence ? '(证据:' + clamp(t.evidence, 70) + ')' : t.note ? '(' + clamp(t.note, 70) + ')' : ''}`)
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
for (const f of facts) {
|
|
826
|
+
if (tokens.some(tk => String(f.text || '').toLowerCase().includes(tk))) {
|
|
827
|
+
hits.push(`- 【持久记录】${clamp(f.text, 120)}`)
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
for (const m of cleanMem.slice(-15)) {
|
|
831
|
+
const txt = stripCheckpointNoise(m.title || m.text)
|
|
832
|
+
if (tokens.some(tk => txt.toLowerCase().includes(tk))) {
|
|
833
|
+
hits.push(`- 【近期回合】${clamp(txt, 120)}`)
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
if (hits.length > 0) {
|
|
837
|
+
return hits.slice(0, 6).join('\n')
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
// Comprehensive Live Situation & Progress Briefing (default + asksProgress + asksBlocked)
|
|
842
|
+
if (board && board.objective) {
|
|
843
|
+
bullets.push(`- 【核心目标】${clamp(board.objective, 130)}`)
|
|
844
|
+
}
|
|
845
|
+
if (cursor.step || cursor.next || cursor.blocked) {
|
|
846
|
+
const curParts = []
|
|
847
|
+
if (cursor.step) curParts.push(`正在推进「${clamp(cursor.step, 70)}」`)
|
|
848
|
+
if (cursor.blocked) curParts.push(`卡点:${clamp(cursor.blocked, 80)}`)
|
|
849
|
+
if (cursor.next) curParts.push(`下一步:${clamp(cursor.next, 80)}`)
|
|
850
|
+
bullets.push(`- 【实时断点】${curParts.join(';')}`)
|
|
851
|
+
}
|
|
852
|
+
if (planSteps.length > 0) {
|
|
853
|
+
bullets.push(`- 【小任务板 (${donePlan.length}/${planSteps.length})】${openPlan.length ? '当前待推进:' + clamp(openPlan[0].text, 90) : '全部步骤已勾选完成'}${donePlan.length ? '(最近已完成:' + clamp(donePlan[donePlan.length - 1].text, 55) + ')' : ''}`)
|
|
854
|
+
}
|
|
855
|
+
if (tasks.length > 0) {
|
|
856
|
+
bullets.push(`- 【任务盘点】共 ${tasks.length} 项:🟢推进中 ${doing.length} · 🔴受阻 ${blocked.length} · ⏳待办 ${todo.length} · ✅已完成 ${done.length}`)
|
|
857
|
+
for (const b of blocked.slice(0, 3)) {
|
|
858
|
+
bullets.push(`- 【🔴 受阻卡点】#${b.id} ${clamp(b.title, 64)}${b.note ? ' — ' + clamp(b.note, 85) : ''}`)
|
|
859
|
+
}
|
|
860
|
+
for (const d of doing.slice(0, 3)) {
|
|
861
|
+
const ownerTag = d.subagent || d.owner ? `(@${shortAgentBriefName(d.subagent || d.owner)})` : ''
|
|
862
|
+
bullets.push(`- 【🟢 正在推进】#${d.id} ${clamp(d.title, 68)}${ownerTag}${d.note ? ':' + clamp(d.note, 65) : ''}`)
|
|
863
|
+
}
|
|
864
|
+
if (!doing.length && !blocked.length && done.length > 0) {
|
|
865
|
+
const lastDone = done[done.length - 1]
|
|
866
|
+
bullets.push(`- 【最近完工】#${lastDone.id} ${clamp(lastDone.title, 68)}${lastDone.evidence ? '(' + clamp(lastDone.evidence, 80) + ')' : ''}`)
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
if (runningWorkers.length > 0) {
|
|
870
|
+
bullets.push(`- 【活跃子代理】${runningWorkers.length} 名正在运行:${runningWorkers.slice(0, 4).map(w => '@' + shortAgentBriefName(w.handle) + (w.taskTitle ? '(' + clamp(w.taskTitle, 32) + ')' : '')).join('、')}`)
|
|
871
|
+
}
|
|
872
|
+
if (leadLive && (leadLive.lastAssistant || leadLive.recentTools.length || leadLive.lastUser)) {
|
|
873
|
+
const toolStr = leadLive.recentTools.length ? `刚执行 ${leadLive.recentTools.slice(-3).join(' → ')};` : ''
|
|
874
|
+
const msgStr = leadLive.lastAssistant
|
|
875
|
+
? clamp(leadLive.lastAssistant, 140)
|
|
876
|
+
: (leadLive.lastUser ? `收到指令「${clamp(leadLive.lastUser, 90)}」` : '')
|
|
877
|
+
bullets.push(`- 【主对话现场 (${leadLive.status === 'running' ? '运行中' : '就绪'})】${toolStr}${msgStr}`)
|
|
878
|
+
} else if (cleanMem.length > 0) {
|
|
879
|
+
const latest = stripCheckpointNoise(cleanMem[cleanMem.length - 1].title || cleanMem[cleanMem.length - 1].text)
|
|
880
|
+
if (latest) bullets.push(`- 【最新回合结论】${clamp(latest, 140)}`)
|
|
881
|
+
}
|
|
882
|
+
if (mailbox.length > 0) {
|
|
883
|
+
const lastMail = mailbox[mailbox.length - 1]
|
|
884
|
+
if (lastMail && lastMail.text) {
|
|
885
|
+
bullets.push(`- 【最新协同通信】${lastMail.from || '成员'} → @${lastMail.to || 'lead'}:${clamp(lastMail.text, 90)}`)
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
// Tactical next-step suggestion
|
|
890
|
+
if (blocked.length > 0) {
|
|
891
|
+
bullets.push(`- 【参谋建议】当前有 ${blocked.length} 项任务受阻,建议优先排障 #${blocked[0].id},或让我直接向主代理/对应子代理插话调整方案。`)
|
|
892
|
+
} else if (doing.length > 0 || runningWorkers.length > 0) {
|
|
893
|
+
bullets.push('- 【参谋建议】主线正在推进中;如需纠偏方向或补充约束,可直接告诉我「让 @某成员 注意……」,我立即替你插话传达。')
|
|
894
|
+
} else if (openPlan.length > 0) {
|
|
895
|
+
bullets.push(`- 【参谋建议】小任务板下一待办步骤为「${clamp(openPlan[0].text, 55)}」,可直接确认执行或让我转告主对话继续。`)
|
|
896
|
+
} else if (todo.length > 0) {
|
|
897
|
+
bullets.push(`- 【参谋建议】当前无运行中代理,尚有 ${todo.length} 项待办(首项:#${todo[0].id} ${clamp(todo[0].title, 40)}),可吩咐主对话继续推进。`)
|
|
898
|
+
} else if (!bullets.length) {
|
|
899
|
+
bullets.push('- 【当前态势】本会话尚未开始任务或记录目标;你可以直接在主对话下达任务,或在下方让我替你立目标、定边界、派分工。')
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
return bullets.join('\n')
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
function deterministicConsolidateClauses(items) {
|
|
906
|
+
const seen = new Set()
|
|
907
|
+
const clauses = []
|
|
908
|
+
for (const raw of items) {
|
|
909
|
+
const parts = String(raw || '')
|
|
910
|
+
.split(/[;;。\n]+/)
|
|
911
|
+
.map(s => s.replace(/^[•·\-*\d.)\s📌]+/, '').trim())
|
|
912
|
+
.filter(Boolean)
|
|
913
|
+
for (const p of parts) {
|
|
914
|
+
const norm = p.toLowerCase().replace(/\s+/g, '')
|
|
915
|
+
if (!norm || seen.has(norm)) continue
|
|
916
|
+
if ([...seen].some(existing => existing.includes(norm) || (norm.length > 6 && norm.includes(existing)))) {
|
|
917
|
+
if (norm.length > 6) {
|
|
918
|
+
for (const ex of [...seen]) {
|
|
919
|
+
if (norm.includes(ex) && norm !== ex) {
|
|
920
|
+
const idx = clauses.findIndex(c => c.toLowerCase().replace(/\s+/g, '') === ex)
|
|
921
|
+
if (idx !== -1) {
|
|
922
|
+
clauses[idx] = p
|
|
923
|
+
seen.delete(ex)
|
|
924
|
+
seen.add(norm)
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
continue
|
|
930
|
+
}
|
|
931
|
+
seen.add(norm)
|
|
932
|
+
clauses.push(p)
|
|
933
|
+
}
|
|
934
|
+
}
|
|
935
|
+
return clamp(clauses.join(';'), 220)
|
|
936
|
+
}
|
|
937
|
+
|
|
938
|
+
/**
|
|
939
|
+
* Consolidate multiple scattered/overlapping boundary rules into ONE concise master rule,
|
|
940
|
+
* creating a pending Prime Minister approval card (`replaces: sourceItems`) so the user
|
|
941
|
+
* can approve & optionally pin it globally (`📌 定住全局`).
|
|
942
|
+
*/
|
|
943
|
+
export async function consolidateBoundsWithChief(deps, {
|
|
944
|
+
sessionId = '',
|
|
945
|
+
field = '',
|
|
946
|
+
items = [],
|
|
947
|
+
instruction = '',
|
|
948
|
+
} = {}) {
|
|
949
|
+
const rootId = (deps.resolveRootSessionId && deps.resolveRootSessionId(sessionId)) || String(sessionId || 'global')
|
|
950
|
+
const board = deps.boardForSession && deps.boardFileFor
|
|
951
|
+
? deps.boardForSession(deps.boardFileFor(rootId))
|
|
952
|
+
: { bounds: { allowed: [], forbidden: [], notes: [] }, pinnedBounds: { allowed: [], forbidden: [], notes: [] } }
|
|
953
|
+
const bounds = (board && board.bounds) || { allowed: [], forbidden: [], notes: [] }
|
|
954
|
+
const pinnedBounds = (board && board.pinnedBounds) || { allowed: [], forbidden: [], notes: [] }
|
|
955
|
+
const BOUND_COL_LABEL = { forbidden: '禁止红线', allowed: '必做事项', notes: '注意事项' }
|
|
956
|
+
|
|
957
|
+
// Determine which column(s) to consolidate
|
|
958
|
+
const targetCols = []
|
|
959
|
+
const explicitItems = Array.isArray(items)
|
|
960
|
+
? items.map(x => String(x || '').trim()).filter(Boolean)
|
|
961
|
+
: []
|
|
962
|
+
|
|
963
|
+
const normField = String(field || '').trim().toLowerCase() === 'must' ? 'allowed' : field
|
|
964
|
+
if (['forbidden', 'allowed', 'notes'].includes(normField)) {
|
|
965
|
+
const colList = Array.isArray(bounds[normField]) ? bounds[normField] : []
|
|
966
|
+
const chosen = explicitItems.length >= 2
|
|
967
|
+
? colList.filter(x => explicitItems.includes(x))
|
|
968
|
+
: colList
|
|
969
|
+
if (chosen.length < 2) {
|
|
970
|
+
return { ok: false, error: `【${BOUND_COL_LABEL[normField]}】当前不足 2 条规则,无需浓缩合并。` }
|
|
971
|
+
}
|
|
972
|
+
targetCols.push({ col: normField, sourceItems: chosen })
|
|
973
|
+
} else if (explicitItems.length >= 2) {
|
|
974
|
+
// Infer column with most matches, default forbidden
|
|
975
|
+
let bestCol = 'forbidden'
|
|
976
|
+
let bestHits = -1
|
|
977
|
+
for (const c of ['forbidden', 'allowed', 'notes']) {
|
|
978
|
+
const hits = (bounds[c] || []).filter(x => explicitItems.includes(x)).length
|
|
979
|
+
if (hits > bestHits) {
|
|
980
|
+
bestHits = hits
|
|
981
|
+
bestCol = c
|
|
982
|
+
}
|
|
983
|
+
}
|
|
984
|
+
targetCols.push({ col: bestCol, sourceItems: explicitItems })
|
|
985
|
+
} else {
|
|
986
|
+
for (const c of ['forbidden', 'allowed', 'notes']) {
|
|
987
|
+
const colList = Array.isArray(bounds[c]) ? bounds[c] : []
|
|
988
|
+
if (colList.length >= 2) {
|
|
989
|
+
targetCols.push({ col: c, sourceItems: colList })
|
|
990
|
+
}
|
|
991
|
+
}
|
|
992
|
+
if (!targetCols.length) {
|
|
993
|
+
return { ok: false, error: '当前各边界分栏均不足 2 条零散规则,暂时无需合并。' }
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
|
|
997
|
+
const createdProposals = []
|
|
998
|
+
for (const { col, sourceItems } of targetCols) {
|
|
999
|
+
const colLabel = BOUND_COL_LABEL[col] || '禁止红线'
|
|
1000
|
+
const hadPinned = sourceItems.some(x => (pinnedBounds[col] || []).includes(x))
|
|
1001
|
+
const prompt = [
|
|
1002
|
+
`目标边界分栏:【${colLabel}】(${col})`,
|
|
1003
|
+
instruction ? `用户额外要求:${clamp(instruction, 200)}` : '',
|
|
1004
|
+
`待浓缩合并的 ${sourceItems.length} 条零散边界:`,
|
|
1005
|
+
...sourceItems.map((it, idx) => `${idx + 1}. ${(pinnedBounds[col] || []).includes(it) ? '[📌全局定住] ' : ''}${it}`),
|
|
1006
|
+
'',
|
|
1007
|
+
'请将以上零散规则浓缩合并为唯一 1 条高密度总则(保留具体命令、路径与硬红线),只输出 JSON:',
|
|
1008
|
+
].filter(Boolean).join('\n')
|
|
1009
|
+
|
|
1010
|
+
const llmRes = await callChiefLlm(deps, {
|
|
1011
|
+
sessionId: rootId,
|
|
1012
|
+
system: CONSOLIDATE_BOUNDS_SYSTEM,
|
|
1013
|
+
prompt,
|
|
1014
|
+
maxTokens: SUMMARY_MAX_TOKENS,
|
|
1015
|
+
})
|
|
1016
|
+
|
|
1017
|
+
const parsed = llmRes.ok ? extractJsonObject(llmRes.text) : null
|
|
1018
|
+
const mergedText = clamp(
|
|
1019
|
+
(parsed && (parsed.item || parsed.draftText || parsed.text)) || deterministicConsolidateClauses(sourceItems),
|
|
1020
|
+
220,
|
|
1021
|
+
)
|
|
1022
|
+
const mergedReason = clamp(
|
|
1023
|
+
(parsed && parsed.reason) || `已将【${colLabel}】下 ${sourceItems.length} 条零散边界浓缩合成为 1 条总则,批准后自动替换原零散条目。`,
|
|
1024
|
+
180,
|
|
1025
|
+
)
|
|
1026
|
+
|
|
1027
|
+
if (!mergedText || secretLike(mergedText)) continue
|
|
1028
|
+
|
|
1029
|
+
mutateChiefState((s) => {
|
|
1030
|
+
const ws = ensureWorkspace(s, rootId)
|
|
1031
|
+
// Dismiss older pending consolidation proposals for the exact same column to avoid clutter
|
|
1032
|
+
for (const existing of ws.suggestions) {
|
|
1033
|
+
if (existing.status === 'pending' && existing.kind === 'bound' && existing.boundField === col && Array.isArray(existing.replaces) && existing.replaces.length > 0) {
|
|
1034
|
+
existing.status = 'dismissed'
|
|
1035
|
+
}
|
|
1036
|
+
}
|
|
1037
|
+
const sug = normalizeSuggestion({
|
|
1038
|
+
kind: 'bound',
|
|
1039
|
+
boundField: col,
|
|
1040
|
+
fromAgent: '✦ 参谋长浓缩',
|
|
1041
|
+
title: `${colLabel} ${sourceItems.length} 合 1:${clamp(mergedText, 26)}`,
|
|
1042
|
+
reason: mergedReason,
|
|
1043
|
+
target: 'bounds',
|
|
1044
|
+
targetLabel: colLabel,
|
|
1045
|
+
mode: 'silent',
|
|
1046
|
+
draftText: mergedText,
|
|
1047
|
+
replaces: sourceItems,
|
|
1048
|
+
pinGlobal: hadPinned,
|
|
1049
|
+
})
|
|
1050
|
+
if (sug) {
|
|
1051
|
+
ws.suggestions.push(sug)
|
|
1052
|
+
createdProposals.push(sug)
|
|
1053
|
+
}
|
|
1054
|
+
})
|
|
1055
|
+
}
|
|
1056
|
+
|
|
1057
|
+
if (!createdProposals.length) {
|
|
1058
|
+
return { ok: false, error: '未能生成浓缩边界,请稍后重试。' }
|
|
1059
|
+
}
|
|
1060
|
+
|
|
1061
|
+
const replyLines = createdProposals.map(p =>
|
|
1062
|
+
`- 【${p.targetLabel} · ${p.replaces.length} 合 1】${p.draftText}(可在上方请示卡片选「📌 定住全局」或「仅本任务」一键替换)`,
|
|
1063
|
+
)
|
|
1064
|
+
|
|
1065
|
+
return {
|
|
1066
|
+
ok: true,
|
|
1067
|
+
proposals: createdProposals,
|
|
1068
|
+
reply: replyLines.join('\n'),
|
|
1069
|
+
view: await getChiefView(deps, rootId, { autoSummarize: false }),
|
|
1070
|
+
}
|
|
1071
|
+
}
|
|
1072
|
+
|
|
1073
|
+
export async function askOrCommandChief(deps, {
|
|
1074
|
+
sessionId = '',
|
|
1075
|
+
text = '',
|
|
1076
|
+
forcedTarget = '',
|
|
1077
|
+
forcedMode = 'steer',
|
|
1078
|
+
images = [],
|
|
1079
|
+
_resumeCtx = null,
|
|
1080
|
+
}) {
|
|
1081
|
+
const rawInput = cleanMultiline(text, 2000)
|
|
1082
|
+
const rawImages = Array.isArray(images) ? images : []
|
|
1083
|
+
if (!rawInput && !rawImages.length) {
|
|
1084
|
+
return { ok: false, error: '请输入要询问或吩咐参谋长的内容或上传图片' }
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
const rootId = deps.resolveRootSessionId(sessionId) || String(sessionId || 'global')
|
|
1088
|
+
const resumeTaskId = _resumeCtx && typeof _resumeCtx.resumeTaskId === 'string' ? _resumeCtx.resumeTaskId : ''
|
|
1089
|
+
const resumeDepth = _resumeCtx && Number.isFinite(_resumeCtx.resumeDepth) ? Number(_resumeCtx.resumeDepth) : 0
|
|
1090
|
+
const isResumeTurn = Boolean(resumeTaskId)
|
|
1091
|
+
const canAttachResume = resumeDepth < 2
|
|
1092
|
+
|
|
1093
|
+
const savedImagePaths = rawImages.length > 0
|
|
1094
|
+
? persistChiefImagesToWorkspace(deps, rootId, rawImages)
|
|
1095
|
+
: (_resumeCtx && Array.isArray(_resumeCtx.savedImagePaths) ? _resumeCtx.savedImagePaths : [])
|
|
1096
|
+
let imageBlocks = []
|
|
1097
|
+
if (rawImages.length > 0) {
|
|
1098
|
+
try {
|
|
1099
|
+
imageBlocks = await admitChiefImages(deps, rawImages)
|
|
1100
|
+
} catch (err) {
|
|
1101
|
+
if (!savedImagePaths.length) {
|
|
1102
|
+
return { ok: false, error: String(err && err.message ? err.message : err) }
|
|
1103
|
+
}
|
|
1104
|
+
imageBlocks = []
|
|
1105
|
+
}
|
|
1106
|
+
}
|
|
1107
|
+
|
|
1108
|
+
const effectiveImgCount = Math.max(imageBlocks.length, savedImagePaths.length)
|
|
1109
|
+
const input = rawInput || '请结合我上传的图片进行分析处理。'
|
|
1110
|
+
const userDisplayText = rawInput || `[上传图片 ×${effectiveImgCount}]`
|
|
1111
|
+
const imgMeta = effectiveImgCount > 0 ? { imageCount: effectiveImgCount } : {}
|
|
1112
|
+
|
|
1113
|
+
const directory = await listPeerDirectory(deps, rootId)
|
|
1114
|
+
const board = deps.boardForSession(deps.boardFileFor(rootId))
|
|
1115
|
+
const state = loadChiefState()
|
|
1116
|
+
const effCfg = resolveWorkspaceConfig(state, rootId)
|
|
1117
|
+
const ownWs = ensureWorkspace(state, rootId)
|
|
1118
|
+
const hasChiefRiskAck = hasValidChiefRiskAck(ownWs)
|
|
1119
|
+
const permissionMode = normalizePermissionMode(effCfg.permissionMode || DEFAULT_CHIEF_PERMISSION_MODE, {
|
|
1120
|
+
requireAck: true,
|
|
1121
|
+
hasChiefRiskAck,
|
|
1122
|
+
})
|
|
1123
|
+
const permRank = permissionRank(permissionMode)
|
|
1124
|
+
const isConciseBrief = Boolean(effCfg.tacticalModes && effCfg.tacticalModes.conciseBrief)
|
|
1125
|
+
const view = clusterView(state, rootId)
|
|
1126
|
+
const targetOpt = archiveTargetForRoot(deps, rootId)
|
|
1127
|
+
const peerProgress = Array.isArray(directory.cluster) && directory.cluster.length > 1
|
|
1128
|
+
? collectClusterPeerProgress(deps, directory.cluster, rootId)
|
|
1129
|
+
: []
|
|
1130
|
+
|
|
1131
|
+
const persistTurnChatAndResume = (ws, {
|
|
1132
|
+
chiefText,
|
|
1133
|
+
actions = [],
|
|
1134
|
+
elevationObj = null,
|
|
1135
|
+
pendingApprovalList = [],
|
|
1136
|
+
target = '',
|
|
1137
|
+
forceReceipt = false,
|
|
1138
|
+
}) => {
|
|
1139
|
+
const cleanActions = Array.isArray(actions) ? actions.filter(Boolean) : []
|
|
1140
|
+
const isReceipt = Boolean(isResumeTurn || forceReceipt || elevationObj || pendingApprovalList.length > 0 || cleanActions.length > 0)
|
|
1141
|
+
const finalActions = isResumeTurn
|
|
1142
|
+
? [...new Set(['⚡ 授权自动续跑', ...cleanActions])].slice(0, 8)
|
|
1143
|
+
: cleanActions.slice(0, 8)
|
|
1144
|
+
if (!isResumeTurn) {
|
|
1145
|
+
ws.chat.push({
|
|
1146
|
+
id: nextId('chat'),
|
|
1147
|
+
role: 'user',
|
|
1148
|
+
text: userDisplayText,
|
|
1149
|
+
...(target ? { target } : {}),
|
|
1150
|
+
...imgMeta,
|
|
1151
|
+
actions: [],
|
|
1152
|
+
at: Date.now(),
|
|
1153
|
+
})
|
|
1154
|
+
}
|
|
1155
|
+
let attachedTaskId = resumeTaskId
|
|
1156
|
+
if (canAttachResume && (elevationObj || pendingApprovalList.length > 0)) {
|
|
1157
|
+
const aprIds = pendingApprovalList.map(a => a && a.id).filter(Boolean)
|
|
1158
|
+
const task = upsertResumeTaskOnWs(ws, {
|
|
1159
|
+
...(resumeTaskId ? { id: resumeTaskId } : {}),
|
|
1160
|
+
status: aprIds.length > 0 ? 'awaiting_approval' : 'awaiting_elevation',
|
|
1161
|
+
originalText: input,
|
|
1162
|
+
forcedTarget,
|
|
1163
|
+
forcedMode,
|
|
1164
|
+
savedImagePaths,
|
|
1165
|
+
resumeDepth,
|
|
1166
|
+
elevationId: elevationObj ? elevationObj.id : '',
|
|
1167
|
+
pendingApprovalIds: aprIds,
|
|
1168
|
+
...(_resumeCtx && _resumeCtx.executedSummary ? { appendCompletedAction: _resumeCtx.executedSummary } : {}),
|
|
1169
|
+
})
|
|
1170
|
+
if (task) {
|
|
1171
|
+
attachedTaskId = task.id
|
|
1172
|
+
if (elevationObj) {
|
|
1173
|
+
elevationObj.resumeTaskId = task.id
|
|
1174
|
+
if (task.expiresAt) elevationObj.expiresAt = task.expiresAt
|
|
1175
|
+
if (ws.pendingElevation && ws.pendingElevation.id === elevationObj.id) {
|
|
1176
|
+
ws.pendingElevation.resumeTaskId = task.id
|
|
1177
|
+
if (task.expiresAt) ws.pendingElevation.expiresAt = task.expiresAt
|
|
1178
|
+
}
|
|
1179
|
+
}
|
|
1180
|
+
if (aprIds.length > 0) {
|
|
1181
|
+
const idSet = new Set(aprIds)
|
|
1182
|
+
for (const listRef of [pendingApprovalList, ws.pendingApprovals]) {
|
|
1183
|
+
if (!Array.isArray(listRef)) continue
|
|
1184
|
+
for (const apr of listRef) {
|
|
1185
|
+
if (apr && idSet.has(apr.id)) {
|
|
1186
|
+
apr.resumeTaskId = task.id
|
|
1187
|
+
if (task.expiresAt && !apr.expiresAt) apr.expiresAt = task.expiresAt
|
|
1188
|
+
}
|
|
1189
|
+
}
|
|
1190
|
+
}
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
}
|
|
1194
|
+
ws.chat.push({
|
|
1195
|
+
id: nextId('chat'),
|
|
1196
|
+
role: 'chief',
|
|
1197
|
+
kind: isReceipt ? 'receipt' : 'qa',
|
|
1198
|
+
...(attachedTaskId ? { resumeTaskId: attachedTaskId } : {}),
|
|
1199
|
+
text: chiefText,
|
|
1200
|
+
actions: finalActions,
|
|
1201
|
+
at: Date.now(),
|
|
1202
|
+
})
|
|
1203
|
+
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
1204
|
+
return attachedTaskId
|
|
1205
|
+
}
|
|
1206
|
+
|
|
1207
|
+
const denyChiefSystemInAdvisor = async (opName, reasonText) => {
|
|
1208
|
+
const elev = requestChiefElevation(rootId, {
|
|
1209
|
+
fromMode: permissionMode,
|
|
1210
|
+
targetMode: 'assistant',
|
|
1211
|
+
reason: reasonText,
|
|
1212
|
+
requestedActionSummary: clamp(input, 160),
|
|
1213
|
+
by: 'chief',
|
|
1214
|
+
})
|
|
1215
|
+
appendChiefAuditLog(rootId, {
|
|
1216
|
+
mode: permissionMode,
|
|
1217
|
+
stage: 'permission_gate',
|
|
1218
|
+
decision: 'deny_mode',
|
|
1219
|
+
operation: opName,
|
|
1220
|
+
target: 'chief_system',
|
|
1221
|
+
reason: reasonText,
|
|
1222
|
+
outcome: 'denied',
|
|
1223
|
+
by: 'chief',
|
|
1224
|
+
})
|
|
1225
|
+
const denyReply = `- 【🔒 权限受限(当前 L0 顾问只读)】${reasonText}\n- 【🔐 已发起提权请示】请点击顶部「🔐 同意提权至 L1 · 助手模式」弹窗后再执行参谋系统维护。`
|
|
1226
|
+
mutateChiefState((s) => {
|
|
1227
|
+
const ws = ensureWorkspace(s, rootId)
|
|
1228
|
+
persistTurnChatAndResume(ws, {
|
|
1229
|
+
chiefText: denyReply,
|
|
1230
|
+
actions: ['🔒 L0 顾问只读', ...(elev ? ['🔐 请示提权 L1'] : [])],
|
|
1231
|
+
elevationObj: elev,
|
|
1232
|
+
forceReceipt: true,
|
|
1233
|
+
})
|
|
1234
|
+
})
|
|
1235
|
+
return {
|
|
1236
|
+
ok: true,
|
|
1237
|
+
deniedByMode: true,
|
|
1238
|
+
elevationRequested: elev,
|
|
1239
|
+
reply: denyReply,
|
|
1240
|
+
relays: [],
|
|
1241
|
+
memoryChanges: [],
|
|
1242
|
+
boardOps: [],
|
|
1243
|
+
actionBadges: ['🔒 L0 顾问只读', ...(elev ? ['🔐 请示提权 L1'] : [])],
|
|
1244
|
+
view: await getChiefView(deps, rootId, { autoSummarize: false }),
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
|
|
1248
|
+
// Fast path: if user explicitly picked a concrete target pill AND used direct relay mode without asking chief to decompose
|
|
1249
|
+
if (forcedTarget && forcedTarget !== 'auto') {
|
|
1250
|
+
const delivery = await deliverCrossMessage(deps, {
|
|
1251
|
+
fromSession: rootId,
|
|
1252
|
+
fromLabel: '用户 (经 DSH 参谋长)',
|
|
1253
|
+
target: forcedTarget,
|
|
1254
|
+
text: rawInput || '请查看随信附带的图片与落盘路径。',
|
|
1255
|
+
mode: ['steer', 'followup', 'silent'].includes(forcedMode) ? forcedMode : 'steer',
|
|
1256
|
+
imageBlocks,
|
|
1257
|
+
savedImagePaths,
|
|
1258
|
+
})
|
|
1259
|
+
const reply = delivery.ok
|
|
1260
|
+
? `已按你的指定向 ${delivery.target || forcedTarget} ${forcedMode === 'steer' ? '插话' : forcedMode === 'silent' ? '投递备忘纸条' : '递话'}${effectiveImgCount ? `(附带 ${effectiveImgCount} 张图片,原图已落盘)` : ''}${delivery.note ? '(' + delivery.note + ')' : '。'}`
|
|
1261
|
+
: `投递失败:${delivery.error}`
|
|
1262
|
+
|
|
1263
|
+
mutateChiefState((s) => {
|
|
1264
|
+
const ws = ensureWorkspace(s, rootId)
|
|
1265
|
+
persistTurnChatAndResume(ws, {
|
|
1266
|
+
chiefText: reply,
|
|
1267
|
+
target: forcedTarget,
|
|
1268
|
+
actions: [delivery.ok ? `→ ${delivery.target || forcedTarget}` : '投递失败'],
|
|
1269
|
+
forceReceipt: true,
|
|
1270
|
+
})
|
|
1271
|
+
})
|
|
1272
|
+
|
|
1273
|
+
return {
|
|
1274
|
+
ok: delivery.ok,
|
|
1275
|
+
reply,
|
|
1276
|
+
relays: [delivery],
|
|
1277
|
+
savedImagePaths,
|
|
1278
|
+
memoryChanges: [],
|
|
1279
|
+
boardOps: [],
|
|
1280
|
+
view: await getChiefView(deps, rootId, { autoSummarize: false }),
|
|
1281
|
+
}
|
|
1282
|
+
}
|
|
1283
|
+
|
|
1284
|
+
// Direct natural-language command to organize/curate the Engineering Archive Cabinet (`整理档案` / `收纳档案`)
|
|
1285
|
+
if (!forcedTarget || forcedTarget === 'auto') {
|
|
1286
|
+
if (/(?:档案|卷宗|老笔记)/.test(input) && /(?:整理|收纳|归类|分拣|拆解)/.test(input)) {
|
|
1287
|
+
if (permRank < 1) {
|
|
1288
|
+
return denyChiefSystemInAdvisor('整理参谋档案', '整理与归类档案库属于「参谋系统维护」操作,需「L1 · 助手模式」及以上权限。')
|
|
1289
|
+
}
|
|
1290
|
+
const orgScope = /全局/.test(input) ? 'global' : 'session'
|
|
1291
|
+
const orgRes = await organizeArchivesWithChief(deps, {
|
|
1292
|
+
sessionId: rootId,
|
|
1293
|
+
vaultScope: orgScope,
|
|
1294
|
+
scope: /全部|所有|全柜/.test(input) ? 'all' : 'unorganized',
|
|
1295
|
+
instruction: input,
|
|
1296
|
+
})
|
|
1297
|
+
if (orgRes.ok) {
|
|
1298
|
+
appendChiefAuditLog(rootId, {
|
|
1299
|
+
mode: permissionMode,
|
|
1300
|
+
stage: 'executor',
|
|
1301
|
+
decision: 'executed',
|
|
1302
|
+
operation: '整理参谋档案',
|
|
1303
|
+
target: orgScope,
|
|
1304
|
+
reason: clamp(input, 120),
|
|
1305
|
+
outcome: 'ok',
|
|
1306
|
+
by: 'chief',
|
|
1307
|
+
})
|
|
1308
|
+
if (isResumeTurn) {
|
|
1309
|
+
mutateChiefState((s) => {
|
|
1310
|
+
const ws = ensureWorkspace(s, rootId)
|
|
1311
|
+
persistTurnChatAndResume(ws, {
|
|
1312
|
+
chiefText: orgRes.reply,
|
|
1313
|
+
actions: [`收纳档案 ${orgRes.updatedCount} 卷`],
|
|
1314
|
+
forceReceipt: true,
|
|
1315
|
+
})
|
|
1316
|
+
})
|
|
1317
|
+
}
|
|
1318
|
+
return {
|
|
1319
|
+
ok: true,
|
|
1320
|
+
reply: orgRes.reply,
|
|
1321
|
+
relays: [],
|
|
1322
|
+
memoryChanges: [],
|
|
1323
|
+
boardOps: [`收纳档案 ${orgRes.updatedCount} 卷`],
|
|
1324
|
+
archives: orgRes.archives,
|
|
1325
|
+
view: orgRes.view,
|
|
1326
|
+
}
|
|
1327
|
+
}
|
|
1328
|
+
}
|
|
1329
|
+
}
|
|
1330
|
+
|
|
1331
|
+
// 0-Token Precipitated Vault Contract: ONLY read precipitated vault if this session EXPLICITLY flipped entries out!
|
|
1332
|
+
const flippedIds = Array.isArray(ownWs.flippedPrecipitatedIds) ? ownWs.flippedPrecipitatedIds : []
|
|
1333
|
+
const flippedVaultLines = []
|
|
1334
|
+
if (flippedIds.length > 0) {
|
|
1335
|
+
const projectKey = resolveProjectKey(targetOpt.cwd)
|
|
1336
|
+
const flippedItems = getFlippedOutPrecipitatedForSession(projectKey, rootId, true, targetOpt)
|
|
1337
|
+
if (flippedItems.length > 0) {
|
|
1338
|
+
flippedVaultLines.push('', '## 8. 本会话已显式翻出的跨会话沉淀经验(仅包含用户显式翻出授权的条目)')
|
|
1339
|
+
for (const entry of flippedItems) {
|
|
1340
|
+
flippedVaultLines.push(`- 🏛️ [沉淀/${entry.category}] 《${entry.title}》:${entry.summary}`)
|
|
1341
|
+
if (Array.isArray(entry.points) && entry.points.length > 0) {
|
|
1342
|
+
for (const pt of entry.points.slice(0, 4)) {
|
|
1343
|
+
flippedVaultLines.push(` * ${pt.title}:${clamp(pt.detail || pt.cue, 200)}`)
|
|
1344
|
+
}
|
|
1345
|
+
} else if (entry.body) {
|
|
1346
|
+
flippedVaultLines.push(` * 正文:${clamp(entry.body, 280)}`)
|
|
1347
|
+
}
|
|
1348
|
+
}
|
|
1349
|
+
}
|
|
1350
|
+
}
|
|
1351
|
+
|
|
1352
|
+
// Watch all 3 archive vaults in background (sealed items NEVER leak to Lead unless placed onto desk!)
|
|
1353
|
+
const visibleArchives = collectChiefVisibleArchives(deps, rootId, state)
|
|
1354
|
+
const watchLines = []
|
|
1355
|
+
const fmtWatchTag = (label, it) => `[${label}${it.id ? ` | id=${it.id}` : ''}] 《${clamp(it.title, 36)}》:${clamp(it.summary, 80)}`
|
|
1356
|
+
const watchEntries = [
|
|
1357
|
+
...visibleArchives.deskSessionItems.map(it => fmtWatchTag('桌面·本局(主可见)', it)),
|
|
1358
|
+
...visibleArchives.deskGlobalItems.map(it => fmtWatchTag('桌面·全局(主可见)', it)),
|
|
1359
|
+
...visibleArchives.deskFlippedItems.map(it => fmtWatchTag('桌面·沉淀(主可见)', it)),
|
|
1360
|
+
...visibleArchives.mountedGlobalItems.map(it => fmtWatchTag('全局参阅·主隐', it)),
|
|
1361
|
+
...((visibleArchives.sealedWatch && visibleArchives.sealedWatch.sessionSealed) || []).map(it => fmtWatchTag('本局封存·主隐', it)),
|
|
1362
|
+
...((visibleArchives.sealedWatch && visibleArchives.sealedWatch.globalSealed) || []).map(it => fmtWatchTag('全局封存·主隐', it)),
|
|
1363
|
+
...((visibleArchives.sealedWatch && visibleArchives.sealedWatch.precipSealed) || []).map(it => fmtWatchTag('沉淀封存·主隐', it)),
|
|
1364
|
+
]
|
|
1365
|
+
if (watchEntries.length > 0) {
|
|
1366
|
+
watchLines.push('', '## 9. 参谋长三库档案全览(封存项仅参谋长关注、未注入主对话;上桌面备选项主对话亦重点看到;支持许愿框 archiveOps)', ...watchEntries.map(x => '- ' + x))
|
|
1367
|
+
}
|
|
1368
|
+
|
|
1369
|
+
// On-demand lazy archive lookup ONLY when the user explicitly asks Chief about archives (Chief searches Session + System Global Cold Vault on demand)
|
|
1370
|
+
const asksArchiveExplicitly = /(?:档案|卷宗|归档|以前|历史记录|工程坐标|老笔记|全局|沉淀|查一下.*(?:怎么|路径|命令|配置))/.test(input)
|
|
1371
|
+
const onDemandArchiveLines = []
|
|
1372
|
+
if (asksArchiveExplicitly) {
|
|
1373
|
+
const sessionTarget = rootId && rootId !== 'global' ? archiveTargetForRoot(deps, rootId, { vaultScope: 'session' }) : null
|
|
1374
|
+
const globalTarget = archiveTargetForRoot(deps, rootId, { vaultScope: 'global' })
|
|
1375
|
+
const foundSess = sessionTarget ? searchArchives(input, { limit: 3, vaultScope: 'session' }, sessionTarget) : { ok: true, hits: [] }
|
|
1376
|
+
const foundGlob = searchGlobalVaultForChief(input, { limit: 3 }, globalTarget)
|
|
1377
|
+
const combinedHits = [
|
|
1378
|
+
...(Array.isArray(foundSess.hits) ? foundSess.hits.map(h => ({ ...h, _scopeLabel: '本会话档案', _target: sessionTarget })) : []),
|
|
1379
|
+
...(Array.isArray(foundGlob.hits) ? foundGlob.hits.map(h => ({ ...h, _scopeLabel: '系统全局档案', _target: globalTarget })) : []),
|
|
1380
|
+
]
|
|
1381
|
+
if (combinedHits.length > 0) {
|
|
1382
|
+
onDemandArchiveLines.push('', '## 7. 按需调取的档案柜卷宗(含本会话档案柜与参谋长专属全局档案柜,仅参谋长侧检索)')
|
|
1383
|
+
for (let i = 0; i < combinedHits.length; i += 1) {
|
|
1384
|
+
const hit = combinedHits[i]
|
|
1385
|
+
onDemandArchiveLines.push(`- 📎 [${hit._scopeLabel}/${hit.folderLabel}] 《${hit.title}》:${hit.summary}`)
|
|
1386
|
+
if (i < 3) {
|
|
1387
|
+
const det = getArchiveDetail(hit.id, rootId, hit._target)
|
|
1388
|
+
if (det.ok && det.item && Array.isArray(det.item.points)) {
|
|
1389
|
+
for (const pt of det.item.points.slice(0, 4)) {
|
|
1390
|
+
onDemandArchiveLines.push(` * ${pt.title}:${clamp(pt.detail || pt.cue, 180)}`)
|
|
1391
|
+
}
|
|
1392
|
+
}
|
|
1393
|
+
}
|
|
1394
|
+
}
|
|
1395
|
+
}
|
|
1396
|
+
}
|
|
1397
|
+
|
|
1398
|
+
// Gather real-time conversation stream + cursor + dual-tier bounds + task breakdown
|
|
1399
|
+
const liveDigest = collectLiveConversationsDigest(deps, rootId, directory)
|
|
1400
|
+
const numberedFacts = view.facts.slice()
|
|
1401
|
+
const tasks = Array.isArray(board && board.tasks) ? board.tasks : []
|
|
1402
|
+
const doingTasks = tasks.filter(t => t.status === 'doing')
|
|
1403
|
+
const blockedTasks = tasks.filter(t => t.status === 'blocked')
|
|
1404
|
+
const todoTasks = tasks.filter(t => t.status === 'todo')
|
|
1405
|
+
const doneTasks = tasks.filter(t => t.status === 'done')
|
|
1406
|
+
const cursor = (board && board.cursor) || {}
|
|
1407
|
+
const pinnedBounds = (board && board.pinnedBounds) || { allowed: [], forbidden: [], notes: [] }
|
|
1408
|
+
const allBounds = (board && board.bounds) || { allowed: [], forbidden: [], notes: [] }
|
|
1409
|
+
const fmtBoundCol = (col) => {
|
|
1410
|
+
const list = allBounds[col] || []
|
|
1411
|
+
if (!list.length) return '(无)'
|
|
1412
|
+
const pinSet = new Set(pinnedBounds[col] || [])
|
|
1413
|
+
return list.map(x => `${pinSet.has(x) ? '📌[全局定住] ' : '[本任务] '}${x}`).join(';')
|
|
1414
|
+
}
|
|
1415
|
+
|
|
1416
|
+
const meaningfulPeers = directory.targets.filter(
|
|
1417
|
+
t => t.kind === 'lead' || t.status === 'running' || !/^mnemon-review/i.test(String(t.name || t.handle || '')),
|
|
1418
|
+
)
|
|
1419
|
+
const hiddenIdleProbes = Math.max(0, directory.targets.length - meaningfulPeers.length)
|
|
1420
|
+
|
|
1421
|
+
const promptLines = [
|
|
1422
|
+
'## 1. 当前可通信成员名录 (Peers)',
|
|
1423
|
+
...(meaningfulPeers.length
|
|
1424
|
+
? meaningfulPeers.slice(0, 16).map(t => `- key="${t.key}" | 名称="${t.handle}" | 类型=${t.kind} | 状态=${t.status}${t.taskTitle ? ' | 当前负责: ' + t.taskTitle : ''}`)
|
|
1425
|
+
: ['- key="lead" | 名称="主对话" | 类型=lead']),
|
|
1426
|
+
...(hiddenIdleProbes > 0 ? [`(另有 ${hiddenIdleProbes} 个已空闲后台检查点探针已折叠)`] : []),
|
|
1427
|
+
...((directory.otherSessions && directory.otherSessions.length > 0)
|
|
1428
|
+
? [
|
|
1429
|
+
'',
|
|
1430
|
+
'## 1.5 本机其他独立会话窗口(可用许愿框 networkOps 连接 link / 断开 unlink)',
|
|
1431
|
+
...directory.otherSessions.slice(0, 12).map(s => `- sessionId="${s.id}" | 名称="${s.name}" | 状态=${s.status} | 已互联=${s.linked ? '是' : '否'}${s.objective ? ' | 目标=' + clamp(s.objective, 50) : ''}`),
|
|
1432
|
+
]
|
|
1433
|
+
: []),
|
|
1434
|
+
'',
|
|
1435
|
+
'## 2. 主对话与子代理【实时对话流现场快照】(Live Transcripts)',
|
|
1436
|
+
...(liveDigest.summaryLines.length
|
|
1437
|
+
? liveDigest.summaryLines
|
|
1438
|
+
: ['(当前暂无活跃对话流消息)']),
|
|
1439
|
+
'',
|
|
1440
|
+
'## 3. 参谋看板目标、断点游标与任务图态势',
|
|
1441
|
+
`- 总目标: ${board.objective || '(未设)'}`,
|
|
1442
|
+
`- 实时断点游标 (Cursor): 当前步骤="${cursor.step || '无'}" | 下一步="${cursor.next || '无'}" | 阻塞点="${cursor.blocked || '无'}"`,
|
|
1443
|
+
`- 计划步骤 (Plan): ${((board.plan || []).slice(0, 8).map(s => `${s.done ? '[✓]' : '[ ]'} ${clamp(s.text, 60)}`).join(';')) || '(无)'}`,
|
|
1444
|
+
`- 🔴 受阻任务 (${blockedTasks.length} 项): ${blockedTasks.slice(0, 6).map(t => `#${t.id} ${t.title}${t.owner ? '(@' + shortAgentBriefName(t.owner) + ')' : ''}${t.note ? ' [原因:' + clamp(t.note, 80) + ']' : ''}`).join(';') || '(无)'}`,
|
|
1445
|
+
`- 🔵 推进中任务 (${doingTasks.length} 项): ${doingTasks.slice(0, 6).map(t => `#${t.id} ${t.title}${t.owner ? '(@' + shortAgentBriefName(t.owner) + ')' : ''}${t.note ? ' [' + clamp(t.note, 60) + ']' : ''}`).join(';') || '(无)'}`,
|
|
1446
|
+
`- ⚪ 待办任务 (${todoTasks.length} 项): ${todoTasks.slice(0, 6).map(t => `#${t.id} ${t.title}${t.owner ? '(@' + shortAgentBriefName(t.owner) + ')' : ''}`).join(';') || '(无)'}`,
|
|
1447
|
+
`- ✅ 最近完成 (${doneTasks.length} 项): ${doneTasks.slice(-5).map(t => `#${t.id} ${t.title}${t.evidence ? ' [证据:' + clamp(t.evidence, 60) + ']' : ''}`).join(';') || '(无)'}`,
|
|
1448
|
+
'',
|
|
1449
|
+
'## 4. 当前生效边界(📌全局定住 vs 本任务)',
|
|
1450
|
+
`- 禁止红线 (forbidden): ${fmtBoundCol('forbidden')}`,
|
|
1451
|
+
`- 必做事项 (allowed): ${fmtBoundCol('allowed')}`,
|
|
1452
|
+
`- 注意事项 (notes): ${fmtBoundCol('notes')}`,
|
|
1453
|
+
'',
|
|
1454
|
+
'## 5. 编号持久记忆条目 (Facts)',
|
|
1455
|
+
...(numberedFacts.length
|
|
1456
|
+
? numberedFacts.map((f, idx) => `[${idx + 1}] (${f.category}) ${f.text}`)
|
|
1457
|
+
: ['(暂无条目)']),
|
|
1458
|
+
'',
|
|
1459
|
+
'## 6. 近期回合摘要与协同信箱参考',
|
|
1460
|
+
...((board.memory || [])
|
|
1461
|
+
.filter(m => m && !isInternalCheckpointNoise(m.title || m.text))
|
|
1462
|
+
.slice(-6)
|
|
1463
|
+
.map(m => `- [回合/${m.section}] ${clamp(stripCheckpointNoise(m.title || m.text), 150)}`)),
|
|
1464
|
+
...(peerProgress.length > 0
|
|
1465
|
+
? [
|
|
1466
|
+
'',
|
|
1467
|
+
'## 6.5 当前互通协同网络邻居实时进度(已共享进度)',
|
|
1468
|
+
...peerProgress.map(p => `- 🌐 [${p.title}] ${p.objective ? `目标="${p.objective}" | ` : ''}${p.progressSummary || '暂无板卡进度'}${p.cursorStep ? ` | 当前="${p.cursorStep}"` : ''}`),
|
|
1469
|
+
]
|
|
1470
|
+
: []),
|
|
1471
|
+
...(view.mailbox.slice(-4).map(m => `- [信箱 ${m.from} → @${m.to}] ${clamp(m.text, 120)}`)),
|
|
1472
|
+
...onDemandArchiveLines,
|
|
1473
|
+
...flippedVaultLines,
|
|
1474
|
+
...watchLines,
|
|
1475
|
+
'',
|
|
1476
|
+
`## 参谋长执行权限与显示模式:permissionMode=${permissionMode}${isConciseBrief ? ' | 极简战报=开启' : ''}`,
|
|
1477
|
+
describeThreePartyBoundariesForPrompt(permissionMode),
|
|
1478
|
+
'## 用户刚刚对你说的话:',
|
|
1479
|
+
input,
|
|
1480
|
+
...(_resumeCtx && _resumeCtx.resumeTaskId
|
|
1481
|
+
? [
|
|
1482
|
+
'',
|
|
1483
|
+
`## ⚡ 系统授权恢复执行上下文(自动续跑事务 #${_resumeCtx.resumeTaskId},当前权限:${permissionMode})`,
|
|
1484
|
+
_resumeCtx.triggerKind === 'elevation'
|
|
1485
|
+
? '- 用户已刚刚批准上述权限升级请求!现在请直接基于用户原始指令调用所需实权工具或动作继续完成任务、核验结果并输出总结回执(切勿只回复“收到”或重复申请刚才的提权)。'
|
|
1486
|
+
: `- 用户已逐项批准并执行完成上一步受控操作:\n${_resumeCtx.executedSummary || '(已执行完成)'}\n- **严禁重复调用刚才已执行完毕的同一写操作/终端命令**!请立即核验当前状态、继续执行用户原指令中尚未完成的后续步骤(若有),完成后输出清晰的结构化结项回执。`,
|
|
1487
|
+
]
|
|
1488
|
+
: []),
|
|
1489
|
+
...(savedImagePaths.length > 0
|
|
1490
|
+
? [
|
|
1491
|
+
'',
|
|
1492
|
+
`🖼️ 用户随信上传了 ${savedImagePaths.length} 张原图(已真实落盘到工作区):`,
|
|
1493
|
+
...savedImagePaths.map(p => `- ${p.path}`),
|
|
1494
|
+
'(重要提示:若当前参谋长模型不支持视觉看图,请把任务与上述绝对路径直接调度/递话给支持看图或读文件工具的主对话 @lead / 子代理处理,严禁臆造图内细节!)',
|
|
1495
|
+
]
|
|
1496
|
+
: []),
|
|
1497
|
+
]
|
|
1498
|
+
|
|
1499
|
+
const isBlankContext = liveDigest.summaryLines.length === 0 && !board.objective && !(board.plan || []).length
|
|
1500
|
+
const resolvedCwd = deps && typeof deps.getSessionCwd === 'function' ? deps.getSessionCwd(rootId) : ''
|
|
1501
|
+
const explicitCompactReq = !imageBlocks.length && isExplicitCompactCommand(input)
|
|
1502
|
+
const statusOnlyInquiry = !imageBlocks.length && !explicitCompactReq && isPureStatusInquiry(input)
|
|
1503
|
+
|
|
1504
|
+
const effectiveSystem = [
|
|
1505
|
+
ASK_CHIEF_SYSTEM,
|
|
1506
|
+
...(isConciseBrief ? [CONCISE_BRIEF_ASK_EXTRA] : []),
|
|
1507
|
+
...(isBlankContext
|
|
1508
|
+
? [
|
|
1509
|
+
'',
|
|
1510
|
+
'🌱 【当前处于空白新上下文(主对话尚未开聊)】:',
|
|
1511
|
+
resolvedCwd ? `- 当前已解析工作区根目录:${resolvedCwd}` : '',
|
|
1512
|
+
'- 若用户让你查找/分析/修改当前工作区项目文件,请依据当前 permissionMode 直接调用你的真实 JSON `toolCalls` 工具(如 `list_dir` / `search_files` / `read_file` / `edit_file` / `run_command`)处理并如实汇报;绝对禁止直接向用户输出 `<|DSML|calls>` 等原始工具调用标签!',
|
|
1513
|
+
'- 若尚无主对话历史,除非用户明确命令且会话已存在,不要无故调用 `session_compact`;若用户明确想把任务留给主对话开场接手,可放进 `relays`(`target: "lead"`)由系统自动暂存待领交接包。',
|
|
1514
|
+
].filter(Boolean)
|
|
1515
|
+
: []),
|
|
1516
|
+
...(statusOnlyInquiry
|
|
1517
|
+
? [
|
|
1518
|
+
'',
|
|
1519
|
+
'⚡ 【当前问题属于「主对话/团队实时态势询问」快速通道】:',
|
|
1520
|
+
'- 严禁调用任何工具,严禁输出任何 XML/DSML 工具标签(如 `<|DSML|calls>`),严禁扫盘或运行 Shell!',
|
|
1521
|
+
'- 请直接根据上下文里已经给出的「实时对话流快照」「小任务板 (Plan)」「任务图」「断点游标」与「协同邻居进度」,输出唯一合法 JSON(仅填 `"reply"`,`"toolCalls": []`)。',
|
|
1522
|
+
]
|
|
1523
|
+
: []),
|
|
1524
|
+
'',
|
|
1525
|
+
CHIEF_TOOLS_PROMPT_GUIDE,
|
|
1526
|
+
].join('\n')
|
|
1527
|
+
|
|
1528
|
+
const upsertArchiveFn = buildChiefArchiveUpsertFn(deps, rootId)
|
|
1529
|
+
const compactNowFn = buildChiefCompactFn(deps, rootId)
|
|
1530
|
+
|
|
1531
|
+
const loopRes = await runChiefAgenticLoop(deps, {
|
|
1532
|
+
rootId,
|
|
1533
|
+
sessionId: rootId,
|
|
1534
|
+
system: effectiveSystem,
|
|
1535
|
+
initialPrompt: promptLines.join('\n'),
|
|
1536
|
+
imageBlocks,
|
|
1537
|
+
allowTextFallbackOnVisionMiss: savedImagePaths.length > 0,
|
|
1538
|
+
permissionMode,
|
|
1539
|
+
hasChiefRiskAck,
|
|
1540
|
+
board,
|
|
1541
|
+
maxSteps: statusOnlyInquiry ? 1 : 4,
|
|
1542
|
+
readOnlyToolsOnly: false,
|
|
1543
|
+
disableTools: statusOnlyInquiry,
|
|
1544
|
+
callLlmFn: (callOpts) => callChiefLlm(deps, { ...callOpts, maxTokens: SUMMARY_MAX_TOKENS }),
|
|
1545
|
+
extractJsonFn: extractJsonObject,
|
|
1546
|
+
upsertArchiveFn,
|
|
1547
|
+
compactNowFn,
|
|
1548
|
+
queueApprovalFn: (item) => queueChiefApproval(rootId, item),
|
|
1549
|
+
requestElevationFn: (req) => requestChiefElevation(rootId, req),
|
|
1550
|
+
recordAuditFn: (entry) => appendChiefAuditLog(rootId, entry),
|
|
1551
|
+
})
|
|
1552
|
+
|
|
1553
|
+
const llmRes = (loopRes && loopRes.llmRes) || { ok: false, error: 'agentic loop no response' }
|
|
1554
|
+
if (imageBlocks.length > 0 && !llmRes.ok && !savedImagePaths.length) {
|
|
1555
|
+
return {
|
|
1556
|
+
ok: false,
|
|
1557
|
+
error: llmRes.error || '当前参谋长模型无法识别图片,请在右上角切换支持视觉的多模态模型后重试',
|
|
1558
|
+
}
|
|
1559
|
+
}
|
|
1560
|
+
|
|
1561
|
+
let parsed = (loopRes && loopRes.parsed) || (llmRes.ok ? extractJsonObject(llmRes.text) : null)
|
|
1562
|
+
const loopBadges = Array.isArray(loopRes && loopRes.toolBadges) ? [...loopRes.toolBadges] : []
|
|
1563
|
+
const loopToolRecords = Array.isArray(loopRes && loopRes.toolRecords) ? loopRes.toolRecords : []
|
|
1564
|
+
const queuedApprovals = Array.isArray(loopRes && loopRes.pendingApprovals) ? [...loopRes.pendingApprovals] : []
|
|
1565
|
+
const queuedElevations = Array.isArray(loopRes && loopRes.elevationRequests) ? [...loopRes.elevationRequests] : []
|
|
1566
|
+
const compactToolRec = loopToolRecords.find(r => r && r.tool === 'session_compact') || null
|
|
1567
|
+
let forcedCompactOut = null
|
|
1568
|
+
let workflowBlockedNeedsElevation = false
|
|
1569
|
+
let chiefSystemBlockedNeedsElevation = false
|
|
1570
|
+
|
|
1571
|
+
if (explicitCompactReq && !compactToolRec) {
|
|
1572
|
+
const compactGuard = evaluateSafetyGuardHardRules({ tool: 'session_compact', opClass: 'workflow', board })
|
|
1573
|
+
if (compactGuard.blocked) {
|
|
1574
|
+
forcedCompactOut = { ok: false, blockedBySafetyGuard: true, error: compactGuard.reason }
|
|
1575
|
+
loopBadges.push(compactGuard.badge || '🛡️ 卫兵拦截压缩')
|
|
1576
|
+
appendChiefAuditLog(rootId, { mode: permissionMode, stage: 'safety_guard', decision: 'blocked', operation: '压缩主对话', target: 'current', reason: compactGuard.reason, outcome: 'blocked', by: 'chief' })
|
|
1577
|
+
} else {
|
|
1578
|
+
const compactGate = evaluateChiefPermissionGate({ permissionMode, hasChiefRiskAck, opClass: 'workflow', tool: 'session_compact' })
|
|
1579
|
+
if (compactGate.decision === 'deny_mode' || compactGate.decision === 'deny_unacknowledged_l3') {
|
|
1580
|
+
workflowBlockedNeedsElevation = true
|
|
1581
|
+
forcedCompactOut = { ok: false, deniedByMode: true, error: compactGate.error }
|
|
1582
|
+
loopBadges.push(compactGate.badge || '🔒 权限禁压')
|
|
1583
|
+
appendChiefAuditLog(rootId, { mode: permissionMode, stage: 'permission_gate', decision: compactGate.decision, operation: '压缩主对话', target: 'current', reason: compactGate.error, outcome: 'denied', by: 'chief' })
|
|
1584
|
+
} else if (compactGate.decision === 'require_approval') {
|
|
1585
|
+
const apr = queueChiefApproval(rootId, {
|
|
1586
|
+
category: 'main_workflow',
|
|
1587
|
+
operationLabel: '压缩主对话上下文 (/compact)',
|
|
1588
|
+
targetLabel: '当前主会话',
|
|
1589
|
+
reason: clamp(input, 140),
|
|
1590
|
+
impact: '会触发主会话历史压缩,先抢救细节入本会话档案柜再压缩裁剪历史上下文',
|
|
1591
|
+
kind: 'compact',
|
|
1592
|
+
payload: { reason: `用户指令触发:${input}` },
|
|
1593
|
+
by: 'chief',
|
|
1594
|
+
})
|
|
1595
|
+
if (apr) queuedApprovals.push(apr)
|
|
1596
|
+
forcedCompactOut = { ok: false, pendingApproval: true, error: '当前处于「L2 · 参谋模式」,压缩主对话请求已提交操作授权弹窗,请点击「允许本次操作」后执行。' }
|
|
1597
|
+
loopBadges.push('🛡️ 待确认 /compact')
|
|
1598
|
+
appendChiefAuditLog(rootId, { mode: permissionMode, stage: 'permission_gate', decision: 'pending_approval', operation: '压缩主对话', target: 'current', reason: clamp(input, 120), outcome: 'pending', by: 'chief' })
|
|
1599
|
+
} else {
|
|
1600
|
+
forcedCompactOut = await compactNowFn(`用户指令触发:${input}`).catch(err => ({
|
|
1601
|
+
ok: false,
|
|
1602
|
+
error: (err && err.message) || String(err || '压缩执行失败'),
|
|
1603
|
+
}))
|
|
1604
|
+
appendChiefAuditLog(rootId, {
|
|
1605
|
+
mode: permissionMode,
|
|
1606
|
+
stage: 'executor',
|
|
1607
|
+
decision: 'executed',
|
|
1608
|
+
operation: '压缩主对话',
|
|
1609
|
+
target: 'current',
|
|
1610
|
+
reason: clamp(input, 120),
|
|
1611
|
+
outcome: forcedCompactOut && forcedCompactOut.ok ? 'ok' : 'error',
|
|
1612
|
+
by: 'chief',
|
|
1613
|
+
})
|
|
1614
|
+
if (forcedCompactOut && forcedCompactOut.ok) {
|
|
1615
|
+
loopBadges.push(forcedCompactOut.noop ? '🗄️ 已归档(免压)' : '🗜 完成抢救压缩')
|
|
1616
|
+
} else {
|
|
1617
|
+
loopBadges.push('⚠️ 压缩未完成')
|
|
1618
|
+
}
|
|
1619
|
+
}
|
|
1620
|
+
}
|
|
1621
|
+
}
|
|
1622
|
+
|
|
1623
|
+
// Graceful intelligent fallback if LLM is offline / unconfigured / returned non-JSON
|
|
1624
|
+
if (!parsed) {
|
|
1625
|
+
// 1) Explicit @peer relay syntax
|
|
1626
|
+
const mentionMatch = input.match(/^@([^\s::,,]+)[::,,\s]+([\s\S]+)$/)
|
|
1627
|
+
if (mentionMatch) {
|
|
1628
|
+
const targetName = mentionMatch[1]
|
|
1629
|
+
const msgBody = mentionMatch[2].trim()
|
|
1630
|
+
const delivery = await deliverCrossMessage(deps, {
|
|
1631
|
+
fromSession: rootId,
|
|
1632
|
+
fromLabel: '用户 (经 DSH 参谋长)',
|
|
1633
|
+
target: targetName,
|
|
1634
|
+
text: msgBody,
|
|
1635
|
+
mode: 'steer',
|
|
1636
|
+
imageBlocks,
|
|
1637
|
+
savedImagePaths,
|
|
1638
|
+
})
|
|
1639
|
+
const fallbackReply = delivery.ok
|
|
1640
|
+
? `- 【已递话】已向 @${delivery.target} 插话传达指令${savedImagePaths.length ? `(附原图路径 ×${savedImagePaths.length})` : ''}。`
|
|
1641
|
+
: `- 【投递失败】未找到目标 ${targetName}(${delivery.error})`
|
|
1642
|
+
mutateChiefState((s) => {
|
|
1643
|
+
const ws = ensureWorkspace(s, rootId)
|
|
1644
|
+
persistTurnChatAndResume(ws, {
|
|
1645
|
+
chiefText: fallbackReply,
|
|
1646
|
+
actions: [delivery.ok ? `→ ${delivery.target || targetName}` : '投递失败'],
|
|
1647
|
+
forceReceipt: true,
|
|
1648
|
+
})
|
|
1649
|
+
})
|
|
1650
|
+
return {
|
|
1651
|
+
ok: delivery.ok,
|
|
1652
|
+
reply: fallbackReply,
|
|
1653
|
+
relays: [delivery],
|
|
1654
|
+
savedImagePaths,
|
|
1655
|
+
memoryChanges: [],
|
|
1656
|
+
boardOps: [],
|
|
1657
|
+
view: await getChiefView(deps, rootId, { autoSummarize: false }),
|
|
1658
|
+
}
|
|
1659
|
+
}
|
|
1660
|
+
|
|
1661
|
+
// 2) Natural-language request to consolidate scattered boundaries into one
|
|
1662
|
+
if (!imageBlocks.length && /边界|红线/.test(input) && /总结成一条|合并成一条|浓缩|合一|整合/.test(input)) {
|
|
1663
|
+
if (permRank < 1) {
|
|
1664
|
+
return denyChiefSystemInAdvisor('浓缩呈批工作边界', '总结与呈批工作边界需要「L1 · 助手模式」及以上权限。')
|
|
1665
|
+
}
|
|
1666
|
+
const targetCol = /允许|必做/.test(input) ? 'allowed' : /注意/.test(input) ? 'notes' : ''
|
|
1667
|
+
const consRes = await consolidateBoundsWithChief(deps, {
|
|
1668
|
+
sessionId: rootId,
|
|
1669
|
+
field: targetCol,
|
|
1670
|
+
instruction: input,
|
|
1671
|
+
})
|
|
1672
|
+
if (consRes.ok) {
|
|
1673
|
+
mutateChiefState((s) => {
|
|
1674
|
+
const ws = ensureWorkspace(s, rootId)
|
|
1675
|
+
persistTurnChatAndResume(ws, {
|
|
1676
|
+
chiefText: consRes.reply,
|
|
1677
|
+
actions: ['呈批浓缩边界'],
|
|
1678
|
+
forceReceipt: true,
|
|
1679
|
+
})
|
|
1680
|
+
})
|
|
1681
|
+
return {
|
|
1682
|
+
ok: true,
|
|
1683
|
+
reply: consRes.reply,
|
|
1684
|
+
relays: [],
|
|
1685
|
+
memoryChanges: [],
|
|
1686
|
+
boardOps: [],
|
|
1687
|
+
boundProposals: consRes.proposals,
|
|
1688
|
+
view: consRes.view,
|
|
1689
|
+
}
|
|
1690
|
+
}
|
|
1691
|
+
}
|
|
1692
|
+
|
|
1693
|
+
// 2.5) Wishing Box offline shortcuts: distill to global / reset tasks / unlink peer sessions
|
|
1694
|
+
if (!imageBlocks.length && /(?:提炼|摘取|抽取|总结)/.test(input) && /全局/.test(input)) {
|
|
1695
|
+
if (permRank < 1) {
|
|
1696
|
+
return denyChiefSystemInAdvisor('提炼入全局档案', '提炼经验写入全局冷库需要「L1 · 助手模式」及以上权限。')
|
|
1697
|
+
}
|
|
1698
|
+
const distRes = await distillSessionArchivesToGlobal(deps, {
|
|
1699
|
+
sessionId: rootId,
|
|
1700
|
+
instruction: input,
|
|
1701
|
+
})
|
|
1702
|
+
if (distRes.ok) {
|
|
1703
|
+
mutateChiefState((s) => {
|
|
1704
|
+
const ws = ensureWorkspace(s, rootId)
|
|
1705
|
+
persistTurnChatAndResume(ws, {
|
|
1706
|
+
chiefText: distRes.reply,
|
|
1707
|
+
actions: [`提炼入全局 ×${distRes.createdCount || 0}`],
|
|
1708
|
+
forceReceipt: true,
|
|
1709
|
+
})
|
|
1710
|
+
})
|
|
1711
|
+
return {
|
|
1712
|
+
ok: true,
|
|
1713
|
+
reply: distRes.reply,
|
|
1714
|
+
relays: [],
|
|
1715
|
+
memoryChanges: [],
|
|
1716
|
+
boardOps: [],
|
|
1717
|
+
archiveOps: [`提炼入全局 ×${distRes.createdCount || 0}`],
|
|
1718
|
+
archives: distRes.archives,
|
|
1719
|
+
view: distRes.view,
|
|
1720
|
+
}
|
|
1721
|
+
}
|
|
1722
|
+
}
|
|
1723
|
+
|
|
1724
|
+
if (!imageBlocks.length && /(?:清空|重设|重置)/.test(input) && /(?:任务|看板)/.test(input)) {
|
|
1725
|
+
if (permRank < 1) {
|
|
1726
|
+
return denyChiefSystemInAdvisor('重设任务看板', '修改或重设参谋看板任务需要「L1 · 助手模式」及以上权限。')
|
|
1727
|
+
}
|
|
1728
|
+
const resetRes = deps.runAction
|
|
1729
|
+
? deps.runAction({ action: 'task.reset', status: 'all', resetPlan: /计划|全部/.test(input), session: rootId, by: 'chief' })
|
|
1730
|
+
: { ok: false }
|
|
1731
|
+
if (resetRes && resetRes.ok) {
|
|
1732
|
+
const msg = '- 【已重设任务看板】已按你的要求清空重设本会话任务列表。'
|
|
1733
|
+
mutateChiefState((s) => {
|
|
1734
|
+
const ws = ensureWorkspace(s, rootId)
|
|
1735
|
+
persistTurnChatAndResume(ws, {
|
|
1736
|
+
chiefText: msg,
|
|
1737
|
+
actions: ['重设任务看板'],
|
|
1738
|
+
forceReceipt: true,
|
|
1739
|
+
})
|
|
1740
|
+
})
|
|
1741
|
+
return {
|
|
1742
|
+
ok: true,
|
|
1743
|
+
reply: msg,
|
|
1744
|
+
relays: [],
|
|
1745
|
+
memoryChanges: [],
|
|
1746
|
+
boardOps: ['重设任务看板'],
|
|
1747
|
+
board: resetRes.board,
|
|
1748
|
+
view: await getChiefView(deps, rootId, { autoSummarize: false }),
|
|
1749
|
+
}
|
|
1750
|
+
}
|
|
1751
|
+
}
|
|
1752
|
+
|
|
1753
|
+
if (!imageBlocks.length && /(?:断开|取消|解除)/.test(input) && /(?:协同|网络|连接|关联)/.test(input)) {
|
|
1754
|
+
if (permRank < 1) {
|
|
1755
|
+
return denyChiefSystemInAdvisor('调整协同网络', '连接或断开跨窗口协同网络需要「L1 · 助手模式」及以上权限。')
|
|
1756
|
+
}
|
|
1757
|
+
const linkedPeers = ((directory && directory.otherSessions) || []).filter(p => p.linked)
|
|
1758
|
+
const qLower = input.toLowerCase()
|
|
1759
|
+
const targetsToUnlink = /全部|所有/.test(input)
|
|
1760
|
+
? linkedPeers
|
|
1761
|
+
: linkedPeers.filter(p => qLower.includes(String(p.id).toLowerCase()) || (p.name && qLower.includes(String(p.name).toLowerCase())))
|
|
1762
|
+
const chosen = targetsToUnlink.length > 0 ? targetsToUnlink : (linkedPeers.length === 1 ? linkedPeers : [])
|
|
1763
|
+
if (chosen.length > 0) {
|
|
1764
|
+
const badges = []
|
|
1765
|
+
for (const p of chosen) {
|
|
1766
|
+
const r = setPeerLink(rootId, p.id, false)
|
|
1767
|
+
if (r && r.ok) badges.push(`断开协同:${p.name}`)
|
|
1768
|
+
}
|
|
1769
|
+
if (badges.length > 0) {
|
|
1770
|
+
const msg = `- 【已断开协同网络】${badges.join(';')}`
|
|
1771
|
+
mutateChiefState((s) => {
|
|
1772
|
+
const ws = ensureWorkspace(s, rootId)
|
|
1773
|
+
persistTurnChatAndResume(ws, {
|
|
1774
|
+
chiefText: msg,
|
|
1775
|
+
actions: badges,
|
|
1776
|
+
forceReceipt: true,
|
|
1777
|
+
})
|
|
1778
|
+
})
|
|
1779
|
+
return {
|
|
1780
|
+
ok: true,
|
|
1781
|
+
reply: msg,
|
|
1782
|
+
relays: [],
|
|
1783
|
+
memoryChanges: [],
|
|
1784
|
+
boardOps: [],
|
|
1785
|
+
networkOps: badges,
|
|
1786
|
+
view: await getChiefView(deps, rootId, { autoSummarize: false }),
|
|
1787
|
+
}
|
|
1788
|
+
}
|
|
1789
|
+
}
|
|
1790
|
+
}
|
|
1791
|
+
|
|
1792
|
+
// 2.5) Deterministic reply when user explicitly requested compaction
|
|
1793
|
+
if (forcedCompactOut) {
|
|
1794
|
+
const compactMsg = forcedCompactOut.ok
|
|
1795
|
+
? (forcedCompactOut.noop
|
|
1796
|
+
? `- 【已归档(免压)】已抢救当前现场记录入本会话档案柜${forcedCompactOut.harvestId ? `(#${forcedCompactOut.harvestId})` : ''};当前主对话历史暂无需压缩。`
|
|
1797
|
+
: `- 【已完成抢救与上下文压缩】已将关键细节抢救入本会话档案柜${forcedCompactOut.harvestId ? `(#${forcedCompactOut.harvestId})` : ''},并完成主对话上下文静默压缩。`)
|
|
1798
|
+
: (forcedCompactOut.pendingApproval
|
|
1799
|
+
? `- 【🛡️ 待逐项确认】${forcedCompactOut.error}`
|
|
1800
|
+
: forcedCompactOut.deniedByMode
|
|
1801
|
+
? `- 【🔒 权限受限】${forcedCompactOut.error}`
|
|
1802
|
+
: `- 【压缩未完成】${forcedCompactOut.error || '当前暂无可压缩历史或宿主压缩服务暂未就绪。'}`)
|
|
1803
|
+
let autoElevOut = null
|
|
1804
|
+
if (workflowBlockedNeedsElevation && !queuedElevations.length) {
|
|
1805
|
+
autoElevOut = requestChiefElevation(rootId, {
|
|
1806
|
+
fromMode: permissionMode,
|
|
1807
|
+
targetMode: 'strategist',
|
|
1808
|
+
reason: '执行主对话上下文压缩 (/compact) 需要「L2 · 参谋模式(逐项确认)」或以上权限',
|
|
1809
|
+
requestedActionSummary: clamp(input, 140),
|
|
1810
|
+
by: 'chief',
|
|
1811
|
+
})
|
|
1812
|
+
}
|
|
1813
|
+
mutateChiefState((s) => {
|
|
1814
|
+
const ws = ensureWorkspace(s, rootId)
|
|
1815
|
+
persistTurnChatAndResume(ws, {
|
|
1816
|
+
chiefText: compactMsg,
|
|
1817
|
+
actions: loopBadges,
|
|
1818
|
+
elevationObj: autoElevOut,
|
|
1819
|
+
pendingApprovalList: queuedApprovals,
|
|
1820
|
+
forceReceipt: true,
|
|
1821
|
+
})
|
|
1822
|
+
})
|
|
1823
|
+
return {
|
|
1824
|
+
ok: true,
|
|
1825
|
+
reply: compactMsg,
|
|
1826
|
+
relays: [],
|
|
1827
|
+
memoryChanges: [],
|
|
1828
|
+
boardOps: [],
|
|
1829
|
+
actionBadges: loopBadges,
|
|
1830
|
+
toolRecords: loopToolRecords,
|
|
1831
|
+
pendingApprovals: queuedApprovals,
|
|
1832
|
+
...(autoElevOut ? { elevationRequested: autoElevOut } : {}),
|
|
1833
|
+
view: await getChiefView(deps, rootId, { autoSummarize: false }),
|
|
1834
|
+
}
|
|
1835
|
+
}
|
|
1836
|
+
|
|
1837
|
+
// 3) Fallback summary + auto-elevation if a read-only/assistant tool wall occurred
|
|
1838
|
+
const deniedToolRec = loopToolRecords.find(r => r && r.result && r.result.deniedByMode)
|
|
1839
|
+
let fallbackElev = queuedElevations[0] || null
|
|
1840
|
+
if (deniedToolRec && !fallbackElev) {
|
|
1841
|
+
fallbackElev = requestChiefElevation(rootId, {
|
|
1842
|
+
fromMode: permissionMode,
|
|
1843
|
+
targetMode: deniedToolRec.result.requiredMode || 'strategist',
|
|
1844
|
+
reason: deniedToolRec.result.error || '执行请求的操作需要更高权限',
|
|
1845
|
+
requestedActionSummary: clamp(input, 160),
|
|
1846
|
+
by: 'chief',
|
|
1847
|
+
})
|
|
1848
|
+
}
|
|
1849
|
+
const strippedPlain = llmRes.ok && llmRes.text ? stripToolCallMarkup(llmRes.text).trim() : ''
|
|
1850
|
+
const usablePlainLlm = strippedPlain && !strippedPlain.startsWith('{') && strippedPlain.length >= 6
|
|
1851
|
+
? cleanMultiline(strippedPlain, 900)
|
|
1852
|
+
: ''
|
|
1853
|
+
const archiveFallback = onDemandArchiveLines.length > 1
|
|
1854
|
+
? ['- 【已从沉淀档案柜按需检索到以下卷宗】', ...onDemandArchiveLines.slice(2)].join('\n')
|
|
1855
|
+
: ''
|
|
1856
|
+
const rawFallbackReply = usablePlainLlm || archiveFallback || buildSmartFallbackReply({
|
|
1857
|
+
input,
|
|
1858
|
+
board,
|
|
1859
|
+
liveDigest,
|
|
1860
|
+
directory,
|
|
1861
|
+
facts: numberedFacts,
|
|
1862
|
+
mailbox: view.mailbox,
|
|
1863
|
+
conciseBrief: isConciseBrief,
|
|
1864
|
+
})
|
|
1865
|
+
const replyText = isConciseBrief ? sanitizeConciseBriefText(rawFallbackReply) : rawFallbackReply
|
|
1866
|
+
|
|
1867
|
+
mutateChiefState((s) => {
|
|
1868
|
+
const ws = ensureWorkspace(s, rootId)
|
|
1869
|
+
persistTurnChatAndResume(ws, {
|
|
1870
|
+
chiefText: replyText,
|
|
1871
|
+
actions: loopBadges,
|
|
1872
|
+
elevationObj: fallbackElev,
|
|
1873
|
+
pendingApprovalList: queuedApprovals,
|
|
1874
|
+
})
|
|
1875
|
+
})
|
|
1876
|
+
return {
|
|
1877
|
+
ok: true,
|
|
1878
|
+
reply: replyText,
|
|
1879
|
+
relays: [],
|
|
1880
|
+
memoryChanges: [],
|
|
1881
|
+
boardOps: [],
|
|
1882
|
+
actionBadges: loopBadges,
|
|
1883
|
+
toolRecords: loopToolRecords,
|
|
1884
|
+
pendingApprovals: queuedApprovals,
|
|
1885
|
+
...(fallbackElev ? { elevationRequested: fallbackElev } : {}),
|
|
1886
|
+
view: await getChiefView(deps, rootId, { autoSummarize: false }),
|
|
1887
|
+
}
|
|
1888
|
+
}
|
|
1889
|
+
|
|
1890
|
+
// Execute decomposed relays with strict 4-tier workflow permission gating
|
|
1891
|
+
const relayResults = []
|
|
1892
|
+
const actionBadges = [...loopBadges]
|
|
1893
|
+
const relayGate = evaluateChiefPermissionGate({
|
|
1894
|
+
permissionMode,
|
|
1895
|
+
hasChiefRiskAck,
|
|
1896
|
+
opClass: 'workflow',
|
|
1897
|
+
tool: 'relay',
|
|
1898
|
+
})
|
|
1899
|
+
|
|
1900
|
+
for (const r of (Array.isArray(parsed.relays) ? parsed.relays : []).slice(0, 8)) {
|
|
1901
|
+
if (!r || !r.text) continue
|
|
1902
|
+
const targetName = r.target || 'lead'
|
|
1903
|
+
const isLeadTarget = /^(?:lead|main|主对话)$/i.test(String(targetName).trim())
|
|
1904
|
+
const relayMode = ['steer', 'followup', 'silent'].includes(r.mode) ? r.mode : 'steer'
|
|
1905
|
+
|
|
1906
|
+
const relayGuard = evaluateSafetyGuardHardRules({ tool: 'relay', opClass: 'workflow', command: r.text, board })
|
|
1907
|
+
if (relayGuard.blocked) {
|
|
1908
|
+
actionBadges.push(relayGuard.badge || '🛡️ 卫兵拦递话')
|
|
1909
|
+
relayResults.push({ ok: false, target: targetName, blockedBySafetyGuard: true, error: relayGuard.reason })
|
|
1910
|
+
appendChiefAuditLog(rootId, { mode: permissionMode, stage: 'safety_guard', decision: 'blocked', operation: '工作流递话', target: String(targetName), reason: relayGuard.reason, outcome: 'blocked', by: 'chief' })
|
|
1911
|
+
continue
|
|
1912
|
+
}
|
|
1913
|
+
|
|
1914
|
+
if (relayGate.decision === 'deny_mode' || relayGate.decision === 'deny_unacknowledged_l3') {
|
|
1915
|
+
workflowBlockedNeedsElevation = true
|
|
1916
|
+
actionBadges.push(relayGate.badge || '🔒 权限禁调工作流')
|
|
1917
|
+
relayResults.push({ ok: false, target: targetName, deniedByMode: true, error: relayGate.error })
|
|
1918
|
+
appendChiefAuditLog(rootId, { mode: permissionMode, stage: 'permission_gate', decision: relayGate.decision, operation: isLeadTarget ? '调整主对话工作流' : '调整子代理工作流', target: String(targetName), reason: relayGate.error, outcome: 'denied', by: 'chief' })
|
|
1919
|
+
continue
|
|
1920
|
+
}
|
|
1921
|
+
|
|
1922
|
+
if (relayGate.decision === 'require_approval') {
|
|
1923
|
+
const apr = queueChiefApproval(rootId, {
|
|
1924
|
+
category: isLeadTarget ? 'main_workflow' : 'subagent_workflow',
|
|
1925
|
+
operationLabel: isLeadTarget ? '调整主对话工作流(投递指令)' : '调整子代理工作流(投递指令)',
|
|
1926
|
+
targetLabel: isLeadTarget ? '主对话 (@lead)' : `@${targetName}`,
|
|
1927
|
+
reason: clamp(r.subject || '参谋建议向代理投递工作流指令', 140),
|
|
1928
|
+
impact: isLeadTarget ? '将向主对话注入工作流指令并触发继续推进' : '将唤醒或引导子代理执行新任务指令',
|
|
1929
|
+
preview: clamp(r.text, 240),
|
|
1930
|
+
kind: 'relay',
|
|
1931
|
+
payload: {
|
|
1932
|
+
fromSession: rootId,
|
|
1933
|
+
fromLabel: 'DSH 参谋 (逐项授权)',
|
|
1934
|
+
target: targetName,
|
|
1935
|
+
subject: r.subject || '',
|
|
1936
|
+
text: r.text,
|
|
1937
|
+
mode: relayMode,
|
|
1938
|
+
imageBlocks,
|
|
1939
|
+
savedImagePaths,
|
|
1940
|
+
isBlankContext,
|
|
1941
|
+
},
|
|
1942
|
+
by: 'chief',
|
|
1943
|
+
})
|
|
1944
|
+
if (apr) queuedApprovals.push(apr)
|
|
1945
|
+
actionBadges.push(`🛡️ 待确认递话 → ${isLeadTarget ? '主对话' : targetName}`)
|
|
1946
|
+
relayResults.push({ ok: false, pendingApproval: true, approvalId: apr && apr.id, target: targetName })
|
|
1947
|
+
appendChiefAuditLog(rootId, { mode: permissionMode, stage: 'permission_gate', decision: 'pending_approval', operation: isLeadTarget ? '主对话工作流递话' : '子代理工作流递话', target: String(targetName), reason: clamp(r.subject || r.text, 120), outcome: 'pending', by: 'chief' })
|
|
1948
|
+
continue
|
|
1949
|
+
}
|
|
1950
|
+
|
|
1951
|
+
// L3 Chief mode: execute directly
|
|
1952
|
+
const deliv = await deliverCrossMessage(deps, {
|
|
1953
|
+
fromSession: rootId,
|
|
1954
|
+
fromLabel: 'DSH 参谋长 (代用户传达)',
|
|
1955
|
+
target: targetName,
|
|
1956
|
+
subject: r.subject || '',
|
|
1957
|
+
text: r.text,
|
|
1958
|
+
mode: relayMode,
|
|
1959
|
+
imageBlocks,
|
|
1960
|
+
savedImagePaths,
|
|
1961
|
+
})
|
|
1962
|
+
if (isLeadTarget && (!deliv.ok || (isBlankContext && !deliv.deliveredPhysical)) && typeof deps.stagePendingTransfer === 'function') {
|
|
1963
|
+
const staged = deps.stagePendingTransfer(
|
|
1964
|
+
`[DSH 参谋长预派发指令${r.subject ? ' · ' + r.subject : ''}]\n${r.text}`,
|
|
1965
|
+
rootId,
|
|
1966
|
+
{ by: 'chief', subject: r.subject || '' },
|
|
1967
|
+
)
|
|
1968
|
+
if (staged) {
|
|
1969
|
+
relayResults.push({ ...deliv, ok: true, target: '主对话(待领)', mode: 'pending-transfer', stagedPending: true })
|
|
1970
|
+
actionBadges.push('暂存待领 → 主对话')
|
|
1971
|
+
appendChiefAuditLog(rootId, { mode: permissionMode, stage: 'executor', decision: 'executed', operation: '主对话待领递话', target: '主对话', reason: clamp(r.subject || r.text, 120), outcome: 'ok', by: 'chief' })
|
|
1972
|
+
continue
|
|
1973
|
+
}
|
|
1974
|
+
}
|
|
1975
|
+
relayResults.push(deliv)
|
|
1976
|
+
appendChiefAuditLog(rootId, { mode: permissionMode, stage: 'executor', decision: 'executed', operation: isLeadTarget ? '主对话递话' : '子代理递话', target: String(deliv.target || targetName), reason: clamp(r.subject || r.text, 120), outcome: deliv.ok ? 'ok' : 'error', by: 'chief' })
|
|
1977
|
+
if (deliv.ok) actionBadges.push(`${relayMode === 'steer' ? '插话' : '递话'} → ${deliv.target}`)
|
|
1978
|
+
}
|
|
1979
|
+
|
|
1980
|
+
// Execute Chief-system ops (L1 Assistant+ required; strictly denied in L0 Advisor)
|
|
1981
|
+
const hasSystemOps = Boolean(
|
|
1982
|
+
(Array.isArray(parsed.boardOps) && parsed.boardOps.length > 0)
|
|
1983
|
+
|| (Array.isArray(parsed.archiveOps) && parsed.archiveOps.length > 0)
|
|
1984
|
+
|| (Array.isArray(parsed.networkOps) && parsed.networkOps.length > 0)
|
|
1985
|
+
|| (Array.isArray(parsed.memoryChanges) && parsed.memoryChanges.length > 0)
|
|
1986
|
+
|| (Array.isArray(parsed.boundProposals) && parsed.boundProposals.length > 0),
|
|
1987
|
+
)
|
|
1988
|
+
const systemGate = evaluateChiefPermissionGate({
|
|
1989
|
+
permissionMode,
|
|
1990
|
+
hasChiefRiskAck,
|
|
1991
|
+
opClass: 'chief_system',
|
|
1992
|
+
tool: 'chief_system',
|
|
1993
|
+
})
|
|
1994
|
+
|
|
1995
|
+
let executedBoardOps = []
|
|
1996
|
+
let executedArchiveOps = []
|
|
1997
|
+
let executedNetworkOps = []
|
|
1998
|
+
let appliedFacts = []
|
|
1999
|
+
const proposedBounds = []
|
|
2000
|
+
const existingBounds = (board && board.bounds) || { allowed: [], forbidden: [], notes: [] }
|
|
2001
|
+
const rawBoundProposals = Array.isArray(parsed.boundProposals) ? parsed.boundProposals.slice(0, 4) : []
|
|
2002
|
+
|
|
2003
|
+
if (hasSystemOps && systemGate.decision === 'deny_mode') {
|
|
2004
|
+
chiefSystemBlockedNeedsElevation = true
|
|
2005
|
+
actionBadges.push(systemGate.badge || '🔒 L0禁改参谋系统')
|
|
2006
|
+
appendChiefAuditLog(rootId, {
|
|
2007
|
+
mode: permissionMode,
|
|
2008
|
+
stage: 'permission_gate',
|
|
2009
|
+
decision: 'deny_mode',
|
|
2010
|
+
operation: '修改参谋系统(看板/记忆/档案)',
|
|
2011
|
+
target: 'chief_system',
|
|
2012
|
+
reason: systemGate.error,
|
|
2013
|
+
outcome: 'denied',
|
|
2014
|
+
by: 'chief',
|
|
2015
|
+
})
|
|
2016
|
+
} else if (hasSystemOps) {
|
|
2017
|
+
executedBoardOps = applyBoardOps(deps, rootId, parsed.boardOps)
|
|
2018
|
+
for (const b of executedBoardOps) actionBadges.push(b)
|
|
2019
|
+
|
|
2020
|
+
const archiveExec = await applyArchiveOps(deps, rootId, parsed.archiveOps, { input })
|
|
2021
|
+
executedArchiveOps = archiveExec.executed || []
|
|
2022
|
+
for (const a of executedArchiveOps) actionBadges.push(a)
|
|
2023
|
+
|
|
2024
|
+
executedNetworkOps = applyNetworkOps(rootId, parsed.networkOps, directory)
|
|
2025
|
+
for (const n of executedNetworkOps) actionBadges.push(n)
|
|
2026
|
+
|
|
2027
|
+
if (executedBoardOps.length || executedArchiveOps.length || executedNetworkOps.length) {
|
|
2028
|
+
appendChiefAuditLog(rootId, {
|
|
2029
|
+
mode: permissionMode,
|
|
2030
|
+
stage: 'executor',
|
|
2031
|
+
decision: 'executed',
|
|
2032
|
+
operation: '维护参谋系统',
|
|
2033
|
+
target: [...executedBoardOps, ...executedArchiveOps, ...executedNetworkOps].slice(0, 3).join(';'),
|
|
2034
|
+
reason: clamp(input, 120),
|
|
2035
|
+
outcome: 'ok',
|
|
2036
|
+
by: 'chief',
|
|
2037
|
+
})
|
|
2038
|
+
}
|
|
2039
|
+
}
|
|
2040
|
+
|
|
2041
|
+
// Handle explicit model elevationRequest OR auto-generate when an action hit mode wall
|
|
2042
|
+
let finalElevation = queuedElevations[0] || null
|
|
2043
|
+
if (parsed.elevationRequest && typeof parsed.elevationRequest === 'object' && parsed.elevationRequest.targetMode) {
|
|
2044
|
+
const reqTarget = normalizePermissionMode(parsed.elevationRequest.targetMode)
|
|
2045
|
+
if (permissionRank(reqTarget) > permRank) {
|
|
2046
|
+
const elv = requestChiefElevation(rootId, {
|
|
2047
|
+
fromMode: permissionMode,
|
|
2048
|
+
targetMode: reqTarget,
|
|
2049
|
+
reason: clamp(parsed.elevationRequest.reason || '完成用户当前任务需要提升参谋权限', 240),
|
|
2050
|
+
requestedActionSummary: clamp(parsed.elevationRequest.requestedActionSummary || input, 180),
|
|
2051
|
+
by: 'chief',
|
|
2052
|
+
})
|
|
2053
|
+
if (elv) {
|
|
2054
|
+
finalElevation = elv
|
|
2055
|
+
actionBadges.push(`🔐 请示提权 ${CHIEF_PERMISSION_META[reqTarget].level}`)
|
|
2056
|
+
}
|
|
2057
|
+
}
|
|
2058
|
+
} else if (!finalElevation) {
|
|
2059
|
+
const deniedToolRec = loopToolRecords.find(r => r && r.result && r.result.deniedByMode)
|
|
2060
|
+
const neededMode = (deniedToolRec && deniedToolRec.result && deniedToolRec.result.requiredMode)
|
|
2061
|
+
|| (workflowBlockedNeedsElevation ? 'strategist' : (chiefSystemBlockedNeedsElevation ? 'assistant' : ''))
|
|
2062
|
+
if (neededMode && permissionRank(neededMode) > permRank) {
|
|
2063
|
+
const elv = requestChiefElevation(rootId, {
|
|
2064
|
+
fromMode: permissionMode,
|
|
2065
|
+
targetMode: neededMode,
|
|
2066
|
+
reason: neededMode === 'assistant'
|
|
2067
|
+
? '该操作需要维护参谋看板、记忆或档案(需「L1 · 助手模式」及以上)'
|
|
2068
|
+
: '该操作需要修改工作区或调度主对话/子代理工作流(需「L2 · 参谋模式」或以上)',
|
|
2069
|
+
requestedActionSummary: clamp(input, 180),
|
|
2070
|
+
by: 'chief',
|
|
2071
|
+
})
|
|
2072
|
+
if (elv) {
|
|
2073
|
+
finalElevation = elv
|
|
2074
|
+
actionBadges.push(`🔐 请示提权 ${CHIEF_PERMISSION_META[neededMode].level}`)
|
|
2075
|
+
}
|
|
2076
|
+
}
|
|
2077
|
+
}
|
|
2078
|
+
|
|
2079
|
+
const cleanedParsedReply = stripToolCallMarkup(parsed.reply || '').trim()
|
|
2080
|
+
const compactOutcomeNote = forcedCompactOut
|
|
2081
|
+
? (forcedCompactOut.ok
|
|
2082
|
+
? (forcedCompactOut.noop
|
|
2083
|
+
? `【已归档(免压)】已将本轮现场记录存入本会话档案柜${forcedCompactOut.harvestId ? `(#${forcedCompactOut.harvestId})` : ''},宿主历史暂无需进一步压缩。`
|
|
2084
|
+
: `【已完成抢救与上下文压缩】已将关键细节存入本会话档案柜${forcedCompactOut.harvestId ? `(#${forcedCompactOut.harvestId})` : ''},并完成主对话静默压缩。`)
|
|
2085
|
+
: (forcedCompactOut.pendingApproval
|
|
2086
|
+
? `【🛡️ 待逐项确认】${forcedCompactOut.error}`
|
|
2087
|
+
: `【压缩未完成】${forcedCompactOut.error || '宿主压缩服务未就绪'}`))
|
|
2088
|
+
: (compactToolRec && compactToolRec.ok === false && !compactToolRec.pendingApproval
|
|
2089
|
+
? `(⚠️ 实测压缩提示:${compactToolRec.error || '压缩未完成'})`
|
|
2090
|
+
: '')
|
|
2091
|
+
const permissionStatusNotes = []
|
|
2092
|
+
if (queuedApprovals.length > 0 && !/操作授权|允许本次操作/.test(cleanedParsedReply)) {
|
|
2093
|
+
permissionStatusNotes.push(`- 【🛡️ 待逐项确认】已为您弹出「操作授权请求」弹窗(共 ${queuedApprovals.length} 项受控操作),点击「允许本次操作」后才会实际执行。`)
|
|
2094
|
+
}
|
|
2095
|
+
if (finalElevation && !/提权/.test(cleanedParsedReply)) {
|
|
2096
|
+
const tgtMeta = CHIEF_PERMISSION_META[finalElevation.targetMode] || {}
|
|
2097
|
+
permissionStatusNotes.push(`- 【🔐 已申请提权】当前为「${CHIEF_PERMISSION_META[permissionMode].level} · ${CHIEF_PERMISSION_META[permissionMode].title}」,已向您发起提权至「${tgtMeta.level || ''} · ${tgtMeta.title || finalElevation.targetMode}」的申请弹窗。`)
|
|
2098
|
+
}
|
|
2099
|
+
const baseParsedReply = cleanedParsedReply || buildSmartFallbackReply({ input, board, liveDigest, directory, facts: numberedFacts, mailbox: view.mailbox, conciseBrief: isConciseBrief }) || '- 【已执行】已按你的吩咐安排妥当。'
|
|
2100
|
+
const combinedParsedReply = [
|
|
2101
|
+
compactOutcomeNote,
|
|
2102
|
+
baseParsedReply,
|
|
2103
|
+
...permissionStatusNotes,
|
|
2104
|
+
].filter(Boolean).join('\n')
|
|
2105
|
+
const rawReplyText = cleanMultiline(combinedParsedReply, 1100)
|
|
2106
|
+
const replyText = isConciseBrief ? sanitizeConciseBriefText(rawReplyText) : rawReplyText
|
|
2107
|
+
|
|
2108
|
+
const BOUND_COL_LABEL = { forbidden: '禁止红线', allowed: '必做事项', notes: '注意事项' }
|
|
2109
|
+
|
|
2110
|
+
mutateChiefState((s) => {
|
|
2111
|
+
const ws = ensureWorkspace(s, rootId)
|
|
2112
|
+
if (systemGate.decision === 'allow') {
|
|
2113
|
+
const activeCluster = getLinkedCluster(s, rootId)
|
|
2114
|
+
appliedFacts = applyFactChanges(ws, numberedFacts, parsed.memoryChanges, 'user', {
|
|
2115
|
+
originRootId: rootId,
|
|
2116
|
+
peerRootIds: activeCluster.filter(id => id !== rootId),
|
|
2117
|
+
})
|
|
2118
|
+
for (const f of appliedFacts) {
|
|
2119
|
+
actionBadges.push((f.op === 'add' ? '记入:' : f.op === 'edit' ? '修订:' : '移除:') + clamp(f.text, 24))
|
|
2120
|
+
}
|
|
2121
|
+
|
|
2122
|
+
for (const bp of rawBoundProposals) {
|
|
2123
|
+
if (!bp || typeof bp !== 'object') continue
|
|
2124
|
+
const rawBpField = String(bp.field || '').trim().toLowerCase()
|
|
2125
|
+
const normBpField = rawBpField === 'must' ? 'allowed' : rawBpField
|
|
2126
|
+
const col = ['forbidden', 'allowed', 'notes'].includes(normBpField) ? normBpField : 'forbidden'
|
|
2127
|
+
const itemText = clamp(bp.item || bp.draftText || bp.text || '', 220)
|
|
2128
|
+
if (!itemText || secretLike(itemText)) continue
|
|
2129
|
+
const replaces = Array.isArray(bp.replaces)
|
|
2130
|
+
? bp.replaces.filter(x => typeof x === 'string' && x.trim()).map(x => x.trim().slice(0, 240)).slice(0, 20)
|
|
2131
|
+
: []
|
|
2132
|
+
const colExisting = Array.isArray(existingBounds[col]) ? existingBounds[col] : []
|
|
2133
|
+
if (!replaces.length && colExisting.some(x => String(x).trim() === itemText)) continue
|
|
2134
|
+
const dupPending = ws.suggestions.some(
|
|
2135
|
+
existing => existing.status === 'pending' && existing.kind === 'bound' && existing.draftText === itemText,
|
|
2136
|
+
)
|
|
2137
|
+
if (dupPending) continue
|
|
2138
|
+
const colLabel = BOUND_COL_LABEL[col] || '禁止红线'
|
|
2139
|
+
const hadPinnedInReplaces = replaces.some(r => ((board.pinnedBounds && board.pinnedBounds[col]) || []).includes(r))
|
|
2140
|
+
const sug = normalizeSuggestion({
|
|
2141
|
+
kind: 'bound',
|
|
2142
|
+
boundField: col,
|
|
2143
|
+
fromAgent: replaces.length ? '✦ 参谋长浓缩' : '✦ 参谋长提炼',
|
|
2144
|
+
title: replaces.length
|
|
2145
|
+
? `${colLabel} ${replaces.length} 合 1:${clamp(itemText, 26)}`
|
|
2146
|
+
: `拟入${colLabel}:${clamp(itemText, 30)}`,
|
|
2147
|
+
reason: clamp(
|
|
2148
|
+
bp.reason || (replaces.length
|
|
2149
|
+
? `将 ${replaces.length} 条零散边界浓缩合成为 1 条,请拍板替换。`
|
|
2150
|
+
: '根据会话上下文总结的工作边界,请拍板注入。'),
|
|
2151
|
+
180,
|
|
2152
|
+
),
|
|
2153
|
+
target: 'bounds',
|
|
2154
|
+
targetLabel: colLabel,
|
|
2155
|
+
mode: 'silent',
|
|
2156
|
+
draftText: itemText,
|
|
2157
|
+
replaces,
|
|
2158
|
+
pinGlobal: Boolean(bp.pinGlobal) || hadPinnedInReplaces,
|
|
2159
|
+
})
|
|
2160
|
+
if (sug) {
|
|
2161
|
+
ws.suggestions.push(sug)
|
|
2162
|
+
proposedBounds.push(sug)
|
|
2163
|
+
actionBadges.push(`${replaces.length ? '浓缩' : '呈批'}${colLabel}:${clamp(itemText, 18)}`)
|
|
2164
|
+
}
|
|
2165
|
+
}
|
|
2166
|
+
}
|
|
2167
|
+
|
|
2168
|
+
persistTurnChatAndResume(ws, {
|
|
2169
|
+
chiefText: replyText,
|
|
2170
|
+
actions: actionBadges,
|
|
2171
|
+
elevationObj: finalElevation,
|
|
2172
|
+
pendingApprovalList: queuedApprovals,
|
|
2173
|
+
forceReceipt: Boolean(
|
|
2174
|
+
relayResults.length > 0
|
|
2175
|
+
|| appliedFacts.length > 0
|
|
2176
|
+
|| executedBoardOps.length > 0
|
|
2177
|
+
|| executedArchiveOps.length > 0
|
|
2178
|
+
|| executedNetworkOps.length > 0
|
|
2179
|
+
|| loopToolRecords.some(r => {
|
|
2180
|
+
const tName = r && ((r.call && (r.call.tool || r.call.name)) || (r.result && r.result.tool) || r.tool || '')
|
|
2181
|
+
return Boolean(tName && getToolOpClass(tName) !== 'read')
|
|
2182
|
+
})
|
|
2183
|
+
),
|
|
2184
|
+
})
|
|
2185
|
+
})
|
|
2186
|
+
|
|
2187
|
+
// Refresh narrative summary in background if facts, board, archives, or network changed
|
|
2188
|
+
const shouldRefreshNarrative = appliedFacts.length > 0
|
|
2189
|
+
|| executedBoardOps.length > 0
|
|
2190
|
+
|| executedArchiveOps.length > 0
|
|
2191
|
+
|| executedNetworkOps.length > 0
|
|
2192
|
+
const freshView = await getChiefView(deps, rootId, { autoSummarize: shouldRefreshNarrative })
|
|
2193
|
+
const freshBoard = executedBoardOps.length > 0 && deps.boardForSession && deps.boardFileFor
|
|
2194
|
+
? deps.boardForSession(deps.boardFileFor(rootId))
|
|
2195
|
+
: undefined
|
|
2196
|
+
let freshArchives
|
|
2197
|
+
if (executedArchiveOps.length > 0) {
|
|
2198
|
+
try {
|
|
2199
|
+
const sc = rootId && rootId !== 'global' ? 'session' : 'global'
|
|
2200
|
+
const opt = archiveTargetForRoot(deps, rootId, { vaultScope: sc })
|
|
2201
|
+
const flIds = (freshView && freshView.flippedPrecipitatedIds) || []
|
|
2202
|
+
freshArchives = listArchiveHeaders(rootId, { vaultScope: sc, includePrecipitated: true, flippedIds: flIds }, opt)
|
|
2203
|
+
} catch {}
|
|
2204
|
+
}
|
|
2205
|
+
|
|
2206
|
+
return {
|
|
2207
|
+
ok: true,
|
|
2208
|
+
reply: replyText,
|
|
2209
|
+
relays: relayResults,
|
|
2210
|
+
actionBadges,
|
|
2211
|
+
memoryChanges: appliedFacts,
|
|
2212
|
+
boardOps: executedBoardOps,
|
|
2213
|
+
archiveOps: executedArchiveOps,
|
|
2214
|
+
networkOps: executedNetworkOps,
|
|
2215
|
+
boundProposals: proposedBounds,
|
|
2216
|
+
toolRecords: loopToolRecords,
|
|
2217
|
+
pendingApprovals: queuedApprovals,
|
|
2218
|
+
...(finalElevation ? { elevationRequested: finalElevation } : {}),
|
|
2219
|
+
permissionMode,
|
|
2220
|
+
...(freshBoard ? { board: freshBoard } : {}),
|
|
2221
|
+
...(freshArchives ? { archives: freshArchives } : {}),
|
|
2222
|
+
view: freshView,
|
|
2223
|
+
}
|
|
2224
|
+
}
|
|
2225
|
+
|
|
2226
|
+
function describeThreePartyBoundariesForPrompt(permissionMode) {
|
|
2227
|
+
const mode = normalizePermissionMode(permissionMode)
|
|
2228
|
+
if (mode === 'advisor') {
|
|
2229
|
+
return '- 四级权限当前档 [L0 · 顾问模式 READ ONLY · 默认模式]:仅允许读取看板与允许访问的项目状态、分析与建言;严禁修改工作区文件、运行系统命令、修改参谋系统或调整主对话/子代理工作流(需要时可调用 request_permission_elevation 申请提权)。'
|
|
2230
|
+
}
|
|
2231
|
+
if (mode === 'assistant') {
|
|
2232
|
+
return '- 四级权限当前档 [L1 · 助手模式 ASSISTANT]:允许只读查证项目,并自主维护参谋系统(记忆、档案柜、看板配置、边界呈批);严禁直接修改项目工作区或接管主对话/子代理工作流(需要时可申请提权至 L2/L3)。'
|
|
2233
|
+
}
|
|
2234
|
+
if (mode === 'strategist') {
|
|
2235
|
+
return '- 四级权限当前档 [L2 · 参谋模式 ADVISOR WITH APPROVAL · 逐项授权]:可自主维护参谋系统;涉及修改工作区文件、执行系统命令或调整主对话/子代理工作流时,每项受控操作均会弹窗等待用户逐项点击「允许本次操作」后方可执行。'
|
|
2236
|
+
}
|
|
2237
|
+
return '- 四级权限当前档 [L3 · 参谋长模式 CHIEF OF STAFF · 主动风险知悉]:已获用户勾选确认风险,允许在安全卫兵硬性规则与禁止红线护栏内直接读写工作区、执行命令、切换或协调主对话及子代理工作流并完成维护与压缩。'
|
|
2238
|
+
}
|
|
2239
|
+
|
|
2240
|
+
/**
|
|
2241
|
+
* Prime Minister Boundary Proposal API (`chief_board` action `"bounds.propose"`).
|
|
2242
|
+
* Lead or subagents submit wall-hits / boundary lessons here instead of silently mutating global bounds;
|
|
2243
|
+
* DSH Chief curates them and prompts the user for approval before injecting into `board.bounds`.
|
|
2244
|
+
*/
|
|
2245
|
+
export function proposeBoundToChief(deps, { sessionId, callerAgent, by, field, item, items, reason }) {
|
|
2246
|
+
const sid = String(sessionId || (callerAgent && callerAgent.id) || '').trim()
|
|
2247
|
+
const rootId = (deps.resolveRootSessionId && deps.resolveRootSessionId(sid, callerAgent)) || sid || 'global'
|
|
2248
|
+
const identity = deps.resolveAgentIdentity ? deps.resolveAgentIdentity(deps.runtime, sid, callerAgent) : null
|
|
2249
|
+
const speaker = identity && identity.isChild
|
|
2250
|
+
? `@${identity.self}`
|
|
2251
|
+
: (by && by !== 'agent' ? String(by) : '@lead')
|
|
2252
|
+
|
|
2253
|
+
const rawCol = String(field || '').trim().toLowerCase()
|
|
2254
|
+
const normCol = rawCol === 'must' ? 'allowed' : rawCol
|
|
2255
|
+
const col = ['forbidden', 'allowed', 'notes'].includes(normCol) ? normCol : 'forbidden'
|
|
2256
|
+
const BOUND_COL_LABEL = { forbidden: '禁止红线', allowed: '必做事项', notes: '注意事项' }
|
|
2257
|
+
const colLabel = BOUND_COL_LABEL[col] || '禁止红线'
|
|
2258
|
+
|
|
2259
|
+
const rawItems = []
|
|
2260
|
+
if (typeof item === 'string' && item.trim()) rawItems.push(item.trim())
|
|
2261
|
+
if (Array.isArray(items)) {
|
|
2262
|
+
for (const entry of items) {
|
|
2263
|
+
if (typeof entry === 'string' && entry.trim()) rawItems.push(entry.trim())
|
|
2264
|
+
}
|
|
2265
|
+
}
|
|
2266
|
+
if (!rawItems.length) {
|
|
2267
|
+
return { ok: false, error: 'bounds.propose requires item (string) or items (string[])' }
|
|
2268
|
+
}
|
|
2269
|
+
|
|
2270
|
+
const board = deps.boardForSession && deps.boardFileFor && rootId !== 'global'
|
|
2271
|
+
? deps.boardForSession(deps.boardFileFor(rootId))
|
|
2272
|
+
: null
|
|
2273
|
+
const existingCol = Array.isArray(board?.bounds?.[col]) ? board.bounds[col] : []
|
|
2274
|
+
|
|
2275
|
+
const proposed = []
|
|
2276
|
+
const skippedDuplicates = []
|
|
2277
|
+
|
|
2278
|
+
mutateChiefState((state) => {
|
|
2279
|
+
const ws = ensureWorkspace(state, rootId)
|
|
2280
|
+
for (const rawRule of rawItems.slice(0, 6)) {
|
|
2281
|
+
const ruleText = clamp(rawRule, 220)
|
|
2282
|
+
if (!ruleText || secretLike(ruleText)) continue
|
|
2283
|
+
if (existingCol.some(x => String(x).trim() === ruleText)) {
|
|
2284
|
+
skippedDuplicates.push(ruleText)
|
|
2285
|
+
continue
|
|
2286
|
+
}
|
|
2287
|
+
const dupPending = ws.suggestions.some(
|
|
2288
|
+
s => s.status === 'pending' && s.kind === 'bound' && s.draftText === ruleText,
|
|
2289
|
+
)
|
|
2290
|
+
if (dupPending) {
|
|
2291
|
+
skippedDuplicates.push(ruleText)
|
|
2292
|
+
continue
|
|
2293
|
+
}
|
|
2294
|
+
const sug = normalizeSuggestion({
|
|
2295
|
+
kind: 'bound',
|
|
2296
|
+
boundField: col,
|
|
2297
|
+
fromAgent: speaker,
|
|
2298
|
+
title: `拟入${colLabel}:${clamp(ruleText, 30)}`,
|
|
2299
|
+
reason: clamp(reason || `${speaker} 在执行中上报的边界约束,请批准后注入全局边界。`, 180),
|
|
2300
|
+
target: 'bounds',
|
|
2301
|
+
targetLabel: colLabel,
|
|
2302
|
+
mode: 'silent',
|
|
2303
|
+
draftText: ruleText,
|
|
2304
|
+
})
|
|
2305
|
+
if (sug) {
|
|
2306
|
+
const pendingNonBound = ws.suggestions.filter(s => s.status === 'pending' && s.kind !== 'bound')
|
|
2307
|
+
const pendingAll = ws.suggestions.filter(s => s.status === 'pending')
|
|
2308
|
+
if (pendingAll.length >= SUGGESTIONS_CAP && pendingNonBound.length > 0) {
|
|
2309
|
+
pendingNonBound[0].status = 'dismissed'
|
|
2310
|
+
}
|
|
2311
|
+
ws.suggestions.push(sug)
|
|
2312
|
+
proposed.push(sug)
|
|
2313
|
+
}
|
|
2314
|
+
}
|
|
2315
|
+
})
|
|
2316
|
+
|
|
2317
|
+
if (proposed.length && typeof deps.appendBoardLog === 'function' && rootId !== 'global') {
|
|
2318
|
+
deps.appendBoardLog(
|
|
2319
|
+
rootId,
|
|
2320
|
+
`🏛 收到边界奏请 (${colLabel}):${proposed.map(p => clamp(p.draftText, 40)).join(';')}`,
|
|
2321
|
+
speaker,
|
|
2322
|
+
)
|
|
2323
|
+
}
|
|
2324
|
+
|
|
2325
|
+
return {
|
|
2326
|
+
ok: true,
|
|
2327
|
+
proposed: proposed.map(p => ({ id: p.id, field: p.boundField, item: p.draftText, from: p.fromAgent })),
|
|
2328
|
+
skippedDuplicates,
|
|
2329
|
+
message: proposed.length
|
|
2330
|
+
? `已呈交 DSH 参谋长(共 ${proposed.length} 条),参谋长正请示用户批准后注入全局【${colLabel}】。`
|
|
2331
|
+
: '该边界已在全局边界或待批请示列表中,无需重复上报。',
|
|
2332
|
+
}
|
|
2333
|
+
}
|
|
2334
|
+
|
|
2335
|
+
/* -------------------------------------------------------------------------- */
|
|
2336
|
+
/* Post-Turn Silent Review & Proactive Suggestion Pills */
|
|
2337
|
+
/* -------------------------------------------------------------------------- */
|
|
2338
|
+
|
|
2339
|
+
const OBJECTIVE_SUGGEST_SYSTEM = [
|
|
2340
|
+
'你是「DSH 参谋长」(宰相级总目标顾问)。用户正准备开启「主动强介入模式」,需要锁定一条「核心目标」作为所有后续参谋介入判断与验收的唯一最终目的地。',
|
|
2341
|
+
'有两种协作模式,请严格遵循:',
|
|
2342
|
+
'1. `mode = "refine"`(微调已有文字):输入框中已有用户自己写下的核心目标草案。你必须在**严格尊重保留用户原有核心意图、主语、约束和具象锚点**的前提下,将其微调润色为一条表述更凝练、验收标准更清晰、适合强介入持续核验的一句话核心目标(不超过 120 字),严禁推翻或另起炉灶。',
|
|
2343
|
+
'2. `mode = "guess"`(建议 / 反复揣摩用户意图):用户未填写核心目标,或认为上一轮建议还不够贴切并**继续点击「建议」让你重新猜**。请综合当前主对话与子代理实时流、最新用户原始诉求、小任务板(Plan)、任务表、必做事项与近期结论,猜出用户此刻最核心的真实落地目标;**严禁与 `已给过的建议列表 (previousSuggestions)` 重复或仅换一两个虚词**,每次重猜都应尝试更贴合场景、不同切入维度或更具体可验收的表述(不超过 120 字)。',
|
|
2344
|
+
'',
|
|
2345
|
+
'只输出一个合法 JSON 对象:',
|
|
2346
|
+
'{',
|
|
2347
|
+
' "suggestion": "建议或微调后的核心目标一句话(≤120字,不要加引号或序号)",',
|
|
2348
|
+
' "rationale": "一句简明大白话说明为何这样拟定/微调(≤55字)"',
|
|
2349
|
+
'}',
|
|
2350
|
+
].join('\n')
|
|
2351
|
+
|
|
2352
|
+
/**
|
|
2353
|
+
* Suggest (with repeated intent guessing) or micro-tune an existing draft Core Objective
|
|
2354
|
+
* when enabling Strong Intervention mode.
|
|
2355
|
+
*/
|
|
2356
|
+
export async function suggestCoreObjectiveWithChief(deps, {
|
|
2357
|
+
sessionId = '',
|
|
2358
|
+
draft = '',
|
|
2359
|
+
mode = 'auto',
|
|
2360
|
+
previousSuggestions = [],
|
|
2361
|
+
} = {}) {
|
|
2362
|
+
const rootId = (deps && typeof deps.resolveRootSessionId === 'function' ? deps.resolveRootSessionId(sessionId) : sessionId) || String(sessionId || 'global')
|
|
2363
|
+
const rawDraft = String(draft || '').replace(/\s+/g, ' ').trim()
|
|
2364
|
+
const prevList = (Array.isArray(previousSuggestions) ? previousSuggestions : [])
|
|
2365
|
+
.map(x => String(x || '').replace(/\s+/g, ' ').trim())
|
|
2366
|
+
.filter(Boolean)
|
|
2367
|
+
.slice(-12)
|
|
2368
|
+
|
|
2369
|
+
const normalizedDraft = rawDraft.toLowerCase()
|
|
2370
|
+
const isCycleOfPreviousAi = Boolean(
|
|
2371
|
+
rawDraft && prevList.some(p => p.toLowerCase() === normalizedDraft),
|
|
2372
|
+
)
|
|
2373
|
+
const effectiveMode = (mode === 'refine' || (mode === 'auto' && rawDraft && !isCycleOfPreviousAi))
|
|
2374
|
+
? 'refine'
|
|
2375
|
+
: 'guess'
|
|
2376
|
+
|
|
2377
|
+
const directory = await listPeerDirectory(deps, rootId)
|
|
2378
|
+
const board = deps && deps.boardForSession && deps.boardFileFor
|
|
2379
|
+
? deps.boardForSession(deps.boardFileFor(rootId))
|
|
2380
|
+
: null
|
|
2381
|
+
const liveDigest = collectLiveConversationsDigest(deps, rootId, directory)
|
|
2382
|
+
const state = loadChiefState()
|
|
2383
|
+
const view = clusterView(state, rootId)
|
|
2384
|
+
const numberedFacts = view.facts.slice(-8)
|
|
2385
|
+
const planSteps = Array.isArray(board && board.plan) ? board.plan.filter(Boolean) : []
|
|
2386
|
+
const openPlan = planSteps.filter(s => !s.done)
|
|
2387
|
+
const tasks = Array.isArray(board && board.tasks) ? board.tasks : []
|
|
2388
|
+
const activeTasks = tasks.filter(t => t && (t.status === 'doing' || t.status === 'todo' || t.status === 'blocked'))
|
|
2389
|
+
const bounds = (board && board.bounds) || { allowed: [], forbidden: [], notes: [] }
|
|
2390
|
+
const leadEntry = (liveDigest.entries || []).find(e => e.kind === 'lead') || (liveDigest.entries || [])[0] || null
|
|
2391
|
+
const latestUser = (leadEntry && leadEntry.lastUser) ? leadEntry.lastUser : ''
|
|
2392
|
+
const existingObj = board && board.objective ? String(board.objective).trim() : ''
|
|
2393
|
+
|
|
2394
|
+
// Build non-repeating deterministic fallback candidates ordered by attempt index
|
|
2395
|
+
const buildFallbackCandidate = () => {
|
|
2396
|
+
if (effectiveMode === 'refine' && rawDraft) {
|
|
2397
|
+
const cleanDraft = clamp(rawDraft.replace(/[。;;]+$/, ''), 96)
|
|
2398
|
+
const refined = /完成|实现|通过|验证|修复|交付|生成|输出/.test(cleanDraft)
|
|
2399
|
+
? `${cleanDraft},确保可实测验收后收尾`
|
|
2400
|
+
: `完成「${cleanDraft}」并完成实测核验`
|
|
2401
|
+
return {
|
|
2402
|
+
suggestion: clamp(refined, 120),
|
|
2403
|
+
rationale: '已保留您原有核心意图,并补充清晰的可验收收口标准。',
|
|
2404
|
+
}
|
|
2405
|
+
}
|
|
2406
|
+
|
|
2407
|
+
const candidates = []
|
|
2408
|
+
if (latestUser) {
|
|
2409
|
+
candidates.push({
|
|
2410
|
+
suggestion: clamp(`彻底完成用户当前诉求「${clamp(latestUser, 72)}」并经实测核验交付`, 120),
|
|
2411
|
+
rationale: '根据主对话最近一次真实诉求提炼的核心目标。',
|
|
2412
|
+
})
|
|
2413
|
+
}
|
|
2414
|
+
if (openPlan.length > 0) {
|
|
2415
|
+
candidates.push({
|
|
2416
|
+
suggestion: clamp(`按小任务板推进完成:${openPlan.slice(0, 2).map(s => clamp(s.text, 38)).join(' → ')}`, 120),
|
|
2417
|
+
rationale: '聚焦小任务板当前尚未勾选的待办节点。',
|
|
2418
|
+
})
|
|
2419
|
+
}
|
|
2420
|
+
if (activeTasks.length > 0) {
|
|
2421
|
+
candidates.push({
|
|
2422
|
+
suggestion: clamp(`攻克在手关键任务(${activeTasks.slice(0, 2).map(t => clamp(t.title, 36)).join('、')})并通过验证`, 120),
|
|
2423
|
+
rationale: '围绕目前推进中与待办的核心任务收敛目标。',
|
|
2424
|
+
})
|
|
2425
|
+
}
|
|
2426
|
+
if (existingObj) {
|
|
2427
|
+
candidates.push({
|
|
2428
|
+
suggestion: clamp(`${existingObj.replace(/[。;;]+$/, '')},完成全部必做事项与实证验收`, 120),
|
|
2429
|
+
rationale: '在当前规划核心目标基础上强化完结验收基准。',
|
|
2430
|
+
})
|
|
2431
|
+
}
|
|
2432
|
+
if (bounds.allowed && bounds.allowed.length > 0) {
|
|
2433
|
+
candidates.push({
|
|
2434
|
+
suggestion: clamp(`推进完成本轮主线研发与交付(必做:${clamp(bounds.allowed[0], 55)})`, 120),
|
|
2435
|
+
rationale: '结合当前必做事项清单拟定的可监督落地目标。',
|
|
2436
|
+
})
|
|
2437
|
+
}
|
|
2438
|
+
if (leadEntry && leadEntry.lastAssistant) {
|
|
2439
|
+
candidates.push({
|
|
2440
|
+
suggestion: clamp(`收口当前主线工作(${clamp(leadEntry.lastAssistant, 68)})并验证通过`, 120),
|
|
2441
|
+
rationale: '结合主对话最新工作现场推断的收尾目标。',
|
|
2442
|
+
})
|
|
2443
|
+
}
|
|
2444
|
+
candidates.push(
|
|
2445
|
+
{
|
|
2446
|
+
suggestion: '完整实现本轮设定功能需求、完成自测校验并清晰交付最终结果',
|
|
2447
|
+
rationale: '通用端到端实现与实测交付目标。',
|
|
2448
|
+
},
|
|
2449
|
+
{
|
|
2450
|
+
suggestion: '排查解决当前阻断卡点与遗留缺陷,确保系统运行稳定并通过复测',
|
|
2451
|
+
rationale: '偏向排查修复与稳定收口的兜底目标。',
|
|
2452
|
+
},
|
|
2453
|
+
)
|
|
2454
|
+
|
|
2455
|
+
const prevNormSet = new Set(prevList.map(x => x.toLowerCase()))
|
|
2456
|
+
const chosen = candidates.find(c => !prevNormSet.has(String(c.suggestion || '').toLowerCase()))
|
|
2457
|
+
|| candidates[prevList.length % candidates.length]
|
|
2458
|
+
return chosen
|
|
2459
|
+
}
|
|
2460
|
+
|
|
2461
|
+
const promptLines = [
|
|
2462
|
+
`当前执行模式: ${effectiveMode === 'refine' ? 'refine(在用户已有核心目标文字上微调润色)' : 'guess(结合现场上下文猜想用户想要的核心目标,允许反复点建议继续猜)'}`,
|
|
2463
|
+
`工作区当前已填核心目标: ${existingObj || '(空)'}`,
|
|
2464
|
+
...(rawDraft ? [`用户输入框当前文字: ${rawDraft}`] : ['用户输入框当前文字: (空)']),
|
|
2465
|
+
...(prevList.length > 0 ? [`已给过的建议(严禁重复或仅微调措辞,须从新角度继续猜):\n${prevList.map((p, i) => ` ${i + 1}. ${p}`).join('\n')}`] : []),
|
|
2466
|
+
`主对话最近用户原始诉求: ${latestUser || '(暂未捕捉)'}`,
|
|
2467
|
+
`小任务板 (Plan) 未完步骤: ${openPlan.slice(0, 4).map(s => clamp(s.text, 60)).join(';') || '(无)'}`,
|
|
2468
|
+
`在手任务 (doing/blocked/todo): ${activeTasks.slice(0, 5).map(t => `[${t.status}] ${clamp(t.title, 48)}`).join(';') || '(无)'}`,
|
|
2469
|
+
`必做事项 (allowed): ${(bounds.allowed || []).slice(0, 4).join(';') || '(无)'}`,
|
|
2470
|
+
`禁止红线 (forbidden): ${(bounds.forbidden || []).slice(0, 4).join(';') || '(无)'}`,
|
|
2471
|
+
`主对话现场摘要: ${leadEntry ? clamp(leadEntry.lastAssistant || '', 260) : '(无)'}`,
|
|
2472
|
+
...(numberedFacts.length ? [`近期重要结论: ${numberedFacts.slice(-4).map(f => clamp(f.text, 90)).join(';')}`] : []),
|
|
2473
|
+
]
|
|
2474
|
+
|
|
2475
|
+
let suggestion = ''
|
|
2476
|
+
let rationale = ''
|
|
2477
|
+
let llmUsed = false
|
|
2478
|
+
|
|
2479
|
+
try {
|
|
2480
|
+
const llmRes = await callChiefLlm(deps, {
|
|
2481
|
+
sessionId: rootId,
|
|
2482
|
+
system: OBJECTIVE_SUGGEST_SYSTEM,
|
|
2483
|
+
prompt: promptLines.join('\n'),
|
|
2484
|
+
maxTokens: 320,
|
|
2485
|
+
})
|
|
2486
|
+
if (llmRes && llmRes.ok && llmRes.text) {
|
|
2487
|
+
const parsed = extractJsonObject(llmRes.text)
|
|
2488
|
+
if (parsed && typeof parsed.suggestion === 'string' && parsed.suggestion.trim()) {
|
|
2489
|
+
const cleaned = cleanMultiline(stripToolCallMarkup(parsed.suggestion), 160).replace(/\s+/g, ' ').trim()
|
|
2490
|
+
const isDuplicateGuess = effectiveMode === 'guess' && prevList.some(p => p.toLowerCase() === cleaned.toLowerCase())
|
|
2491
|
+
if (cleaned && !isDuplicateGuess) {
|
|
2492
|
+
suggestion = clamp(cleaned, 120)
|
|
2493
|
+
rationale = clamp(String(parsed.rationale || '').trim(), 90)
|
|
2494
|
+
llmUsed = true
|
|
2495
|
+
}
|
|
2496
|
+
}
|
|
2497
|
+
}
|
|
2498
|
+
} catch {}
|
|
2499
|
+
|
|
2500
|
+
if (!suggestion) {
|
|
2501
|
+
const fb = buildFallbackCandidate()
|
|
2502
|
+
suggestion = fb.suggestion
|
|
2503
|
+
rationale = fb.rationale
|
|
2504
|
+
}
|
|
2505
|
+
|
|
2506
|
+
return {
|
|
2507
|
+
ok: true,
|
|
2508
|
+
suggestion,
|
|
2509
|
+
rationale: rationale || (effectiveMode === 'refine' ? '已在您原文基础上完成微调。' : '已结合当前对话态势为您揣摩建议。'),
|
|
2510
|
+
mode: effectiveMode,
|
|
2511
|
+
llmUsed,
|
|
2512
|
+
}
|
|
2513
|
+
}
|