dsh-chief 1.2.0 → 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 +51 -0
- package/README.en.md +28 -13
- package/README.md +27 -12
- 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/auto-continue.js +11 -1
- 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 +859 -153
- 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 -7492
- package/client.js +11959 -10923
- package/digest.js +8 -8
- package/index.js +154 -6095
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/model-tools.js +755 -0
- package/package.json +48 -17
- package/runtime-hooks.js +629 -0
- package/subagent-runtime.js +1399 -0
package/api-routes.js
ADDED
|
@@ -0,0 +1,1274 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* api-routes.js
|
|
3
|
+
*
|
|
4
|
+
* Same-origin HTTP route table and request guards for the DSH Chief browser panel.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import fs from 'node:fs'
|
|
8
|
+
import path from 'node:path'
|
|
9
|
+
import { renderDigest } from './digest.js'
|
|
10
|
+
import { memorySections, renderMemoryDigest } from './memory.js'
|
|
11
|
+
import {
|
|
12
|
+
loadChiefState,
|
|
13
|
+
resolveWorkspaceConfig,
|
|
14
|
+
getLinkedCluster,
|
|
15
|
+
setPeerLink,
|
|
16
|
+
listChiefModels,
|
|
17
|
+
deliverCrossMessage,
|
|
18
|
+
getChiefView,
|
|
19
|
+
recommendAndSetCompactThreshold,
|
|
20
|
+
askOrCommandChief,
|
|
21
|
+
consolidateBoundsWithChief,
|
|
22
|
+
organizeArchivesWithChief,
|
|
23
|
+
harvestTurnDetailsToArchive,
|
|
24
|
+
precipitateExperienceWithChief,
|
|
25
|
+
distillSessionArchivesToGlobal,
|
|
26
|
+
updateWorkspaceFlippedIds,
|
|
27
|
+
proposeBoundToChief,
|
|
28
|
+
handleSuggestionDecision,
|
|
29
|
+
executeBatchSuggestions,
|
|
30
|
+
updateChiefConfig,
|
|
31
|
+
suggestCoreObjectiveWithChief,
|
|
32
|
+
relayArchivesWithChief,
|
|
33
|
+
mutateChiefFact,
|
|
34
|
+
handleApprovalDecision,
|
|
35
|
+
handleElevationDecision,
|
|
36
|
+
} from './chief.js'
|
|
37
|
+
import {
|
|
38
|
+
resolveProjectKey,
|
|
39
|
+
getArchiveMeta,
|
|
40
|
+
getThreeTierArchiveCounts,
|
|
41
|
+
listArchiveHeaders,
|
|
42
|
+
getArchiveDetail,
|
|
43
|
+
mutateArchive,
|
|
44
|
+
getTakenOutArchivesForSession,
|
|
45
|
+
getTakenOutGlobalForSession,
|
|
46
|
+
getFlippedOutPrecipitatedForSession,
|
|
47
|
+
getPrecipitatedDetail,
|
|
48
|
+
mutatePrecipitated,
|
|
49
|
+
copyPrecipitatedToVault,
|
|
50
|
+
} from './archives.js'
|
|
51
|
+
import { DEFAULT_CHIEF_PERMISSION_MODE } from './chief-executor.js'
|
|
52
|
+
import {
|
|
53
|
+
API,
|
|
54
|
+
BACKEND_BUILD,
|
|
55
|
+
BODY_LIMIT,
|
|
56
|
+
emptyBoard,
|
|
57
|
+
normalizeBoundFieldName,
|
|
58
|
+
guardCount,
|
|
59
|
+
pushLog,
|
|
60
|
+
safe,
|
|
61
|
+
} from './board-schema.js'
|
|
62
|
+
|
|
63
|
+
export function createApiRoutes(deps) {
|
|
64
|
+
|
|
65
|
+
const archiveTarget = (...args) => deps.archiveTarget(...args)
|
|
66
|
+
const boardFile = (...args) => deps.boardFile(...args)
|
|
67
|
+
const boardFileFor = (...args) => deps.boardFileFor(...args)
|
|
68
|
+
const boardForSession = (...args) => deps.boardForSession(...args)
|
|
69
|
+
const boundaries = (...args) => deps.boundaries(...args)
|
|
70
|
+
const collectDigestArchiveContext = (...args) => deps.collectDigestArchiveContext(...args)
|
|
71
|
+
const executeSubagentAction = (...args) => deps.executeSubagentAction(...args)
|
|
72
|
+
const fetchTeamTasks = (...args) => deps.fetchTeamTasks(...args)
|
|
73
|
+
const getSessionContextBreakdown = (...args) => deps.getSessionContextBreakdown(...args)
|
|
74
|
+
const linkedPeersForSession = (...args) => deps.linkedPeersForSession(...args)
|
|
75
|
+
const loadBoard = (...args) => deps.loadBoard(...args)
|
|
76
|
+
const makeChiefDeps = (...args) => deps.makeChiefDeps(...args)
|
|
77
|
+
const probeSubagentSupport = (...args) => deps.probeSubagentSupport(...args)
|
|
78
|
+
const readPending = (...args) => deps.readPending(...args)
|
|
79
|
+
const refreshSubagentTree = (...args) => deps.refreshSubagentTree(...args)
|
|
80
|
+
const resolveAgentIdentity = (...args) => deps.resolveAgentIdentity(...args)
|
|
81
|
+
const resolveEffectiveHandoff = (...args) => deps.resolveEffectiveHandoff(...args)
|
|
82
|
+
const resolveRootSessionId = (...args) => deps.resolveRootSessionId(...args)
|
|
83
|
+
const runAction = (...args) => deps.runAction(...args)
|
|
84
|
+
const saveBoard = (...args) => deps.saveBoard(...args)
|
|
85
|
+
const sessionName = (...args) => deps.sessionName(...args)
|
|
86
|
+
const transcriptTimes = (...args) => deps.transcriptTimes(...args)
|
|
87
|
+
const transferChief = (...args) => deps.transferChief(...args)
|
|
88
|
+
const withBoardLock = (...args) => deps.withBoardLock(...args)
|
|
89
|
+
|
|
90
|
+
/* ---------------------------------------------------------------------- routes */
|
|
91
|
+
|
|
92
|
+
function sendJson(res, status, value) {
|
|
93
|
+
const body = JSON.stringify(value)
|
|
94
|
+
res.statusCode = status
|
|
95
|
+
res.setHeader('content-type', 'application/json; charset=utf-8')
|
|
96
|
+
res.setHeader('cache-control', 'no-store')
|
|
97
|
+
res.end(body)
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function readBody(req) {
|
|
101
|
+
return new Promise((resolve, reject) => {
|
|
102
|
+
const chunks = []
|
|
103
|
+
let size = 0
|
|
104
|
+
req.on('data', chunk => {
|
|
105
|
+
size += chunk.length
|
|
106
|
+
if (size > BODY_LIMIT) {
|
|
107
|
+
reject(new Error('body too large'))
|
|
108
|
+
req.destroy()
|
|
109
|
+
return
|
|
110
|
+
}
|
|
111
|
+
chunks.push(chunk)
|
|
112
|
+
})
|
|
113
|
+
req.on('end', () => {
|
|
114
|
+
const text = Buffer.concat(chunks).toString('utf8').trim()
|
|
115
|
+
if (!text) return resolve({})
|
|
116
|
+
try {
|
|
117
|
+
resolve(JSON.parse(text))
|
|
118
|
+
} catch (error) {
|
|
119
|
+
reject(error)
|
|
120
|
+
}
|
|
121
|
+
})
|
|
122
|
+
req.on('error', reject)
|
|
123
|
+
})
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function resolveArchiveHttpScope(raw) {
|
|
127
|
+
const s = typeof raw === 'string' ? raw.trim().toLowerCase() : ''
|
|
128
|
+
if (s === 'global') return 'global'
|
|
129
|
+
if (s === 'precipitated' || s === 'cold' || s === 'vault') return 'precipitated'
|
|
130
|
+
return 'session'
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function resolveBoundRootSid(sessionId = '') {
|
|
134
|
+
const raw = String(sessionId || '').trim()
|
|
135
|
+
if (!raw || raw === 'global') return ''
|
|
136
|
+
const root = String(resolveRootSessionId(raw) || raw).trim()
|
|
137
|
+
return (!root || root === 'global') ? '' : root
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function collectDeskItemsForUi(runtime, rootId, cabinetId = '') {
|
|
141
|
+
if (!rootId) return []
|
|
142
|
+
const targetOpt = archiveTarget(runtime, rootId, { cabinetId, vaultScope: 'session' })
|
|
143
|
+
const out = []
|
|
144
|
+
try {
|
|
145
|
+
for (const it of getTakenOutArchivesForSession(rootId, targetOpt)) {
|
|
146
|
+
out.push({ id: it.id, scope: 'session', title: it.title, summary: it.summary || '', folder: it.folder || 'inbox', paperclip: it.paperclip || 'silver' })
|
|
147
|
+
}
|
|
148
|
+
} catch {}
|
|
149
|
+
try {
|
|
150
|
+
const gOpt = archiveTarget(runtime, rootId, { cabinetId: '', vaultScope: 'global' })
|
|
151
|
+
for (const it of getTakenOutGlobalForSession(rootId, gOpt)) {
|
|
152
|
+
out.push({ id: it.id, scope: 'global', title: it.title, summary: it.summary || '', folder: it.folder || 'coords', paperclip: it.paperclip || 'silver' })
|
|
153
|
+
}
|
|
154
|
+
} catch {}
|
|
155
|
+
try {
|
|
156
|
+
const st = loadChiefState()
|
|
157
|
+
const ws = st && st.workspaces && st.workspaces[rootId]
|
|
158
|
+
const flippedIds = ws && Array.isArray(ws.flippedPrecipitatedIds) ? ws.flippedPrecipitatedIds : []
|
|
159
|
+
if (flippedIds.length) {
|
|
160
|
+
const pk = resolveProjectKey(targetOpt.cwd)
|
|
161
|
+
for (const it of getFlippedOutPrecipitatedForSession(pk, rootId, true, targetOpt)) {
|
|
162
|
+
out.push({ id: it.id, scope: 'precipitated', title: it.title, summary: it.summary || '', folder: it.category || 'contracts', paperclip: 'gold' })
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
} catch {}
|
|
166
|
+
return out
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function routeTable(runtime) {
|
|
170
|
+
const guard = (req, res) => {
|
|
171
|
+
const connection = runtime.get('connection')
|
|
172
|
+
if (connection && typeof connection.requestRejection === 'function') {
|
|
173
|
+
try {
|
|
174
|
+
const rejection = connection.requestRejection({ headers: req.headers })
|
|
175
|
+
if (rejection) {
|
|
176
|
+
sendJson(res, rejection, { ok: false, error: rejection === 401 ? 'unauthorized' : 'forbidden' })
|
|
177
|
+
return false
|
|
178
|
+
}
|
|
179
|
+
} catch (err) {
|
|
180
|
+
console.warn('[dsh-chief] request guard check failed; failing closed:', err && err.message ? err.message : err)
|
|
181
|
+
sendJson(res, 403, { ok: false, error: 'forbidden (guard check failed)' })
|
|
182
|
+
return false
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
return true
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
return [
|
|
189
|
+
{
|
|
190
|
+
path: API + '/snapshot',
|
|
191
|
+
handler: async (req, res) => {
|
|
192
|
+
if (!guard(req, res)) return
|
|
193
|
+
try {
|
|
194
|
+
let sessionId = ''
|
|
195
|
+
try {
|
|
196
|
+
sessionId = new URL(req.url || '/', 'http://127.0.0.1').searchParams.get('session') || ''
|
|
197
|
+
} catch {}
|
|
198
|
+
const board = sessionId ? boardForSession(boardFileFor(sessionId)) : emptyBoard()
|
|
199
|
+
const subagents = sessionId ? await refreshSubagentTree(runtime, sessionId, board) : []
|
|
200
|
+
const agentIdentity = sessionId ? resolveAgentIdentity(runtime, sessionId) : null
|
|
201
|
+
const secState = loadChiefState()
|
|
202
|
+
const rootSid = resolveRootSessionId(sessionId) || sessionId || 'global'
|
|
203
|
+
const cluster = getLinkedCluster(secState, rootSid)
|
|
204
|
+
let pendingSuggestions = 0
|
|
205
|
+
let factsCount = 0
|
|
206
|
+
let mailboxCount = 0
|
|
207
|
+
for (const cid of cluster) {
|
|
208
|
+
const ws = secState.workspaces && secState.workspaces[cid]
|
|
209
|
+
if (!ws) continue
|
|
210
|
+
if (Array.isArray(ws.suggestions)) pendingSuggestions += ws.suggestions.filter(s => s.status === 'pending').length
|
|
211
|
+
if (Array.isArray(ws.facts)) factsCount += ws.facts.length
|
|
212
|
+
if (Array.isArray(ws.mailbox)) mailboxCount += ws.mailbox.length
|
|
213
|
+
}
|
|
214
|
+
let followModelRef = ''
|
|
215
|
+
try {
|
|
216
|
+
const agentsSvc = runtime && runtime.get('agents')
|
|
217
|
+
const ag = agentsSvc && typeof agentsSvc.get === 'function' ? (agentsSvc.get(sessionId) || agentsSvc.get(rootSid)) : null
|
|
218
|
+
const hdr = ag && ag.session && typeof ag.session.requestHeader === 'function'
|
|
219
|
+
? ag.session.requestHeader()
|
|
220
|
+
: (ag && ag.session && ag.session.header ? ag.session.header : null)
|
|
221
|
+
const hcfg = hdr && hdr.config ? hdr.config : hdr
|
|
222
|
+
if (hcfg && hcfg.provider && hcfg.model && !String(hcfg.provider).startsWith('local-agent')) {
|
|
223
|
+
followModelRef = `${hcfg.provider}/${hcfg.model}`
|
|
224
|
+
} else {
|
|
225
|
+
const defSel = runtime && runtime.get('agentDefaultModel')?.currentSelection?.()
|
|
226
|
+
if (defSel && defSel.provider && defSel.model && !String(defSel.provider).startsWith('local-agent')) {
|
|
227
|
+
followModelRef = `${defSel.provider}/${defSel.model}`
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
} catch {}
|
|
231
|
+
const effCfg = resolveWorkspaceConfig(secState, rootSid)
|
|
232
|
+
let pinnedModelRef = effCfg.modelRef || ''
|
|
233
|
+
if (pinnedModelRef) {
|
|
234
|
+
try {
|
|
235
|
+
const llmSvc = runtime && runtime.get('llm')
|
|
236
|
+
if (llmSvc && typeof llmSvc.listProviders === 'function') {
|
|
237
|
+
const provs = new Set((llmSvc.listProviders() || []).map(p => p && p.id).filter(Boolean))
|
|
238
|
+
const pName = pinnedModelRef.split('/')[0]
|
|
239
|
+
if (provs.size > 0 && !provs.has(pName)) pinnedModelRef = ''
|
|
240
|
+
}
|
|
241
|
+
} catch {}
|
|
242
|
+
}
|
|
243
|
+
const rootWs = secState.workspaces && secState.workspaces[rootSid]
|
|
244
|
+
const tacticalModes = effCfg.tacticalModes || {}
|
|
245
|
+
const flippedIds = (rootWs && Array.isArray(rootWs.flippedPrecipitatedIds)) ? rootWs.flippedPrecipitatedIds.slice() : []
|
|
246
|
+
const boundRootSid = resolveBoundRootSid(sessionId)
|
|
247
|
+
const sessionArchOpt = archiveTarget(runtime, boundRootSid, { cabinetId: board.activeCabinetId, vaultScope: 'session' })
|
|
248
|
+
const archiveMeta = {
|
|
249
|
+
...getArchiveMeta(boundRootSid, sessionArchOpt),
|
|
250
|
+
counts: getThreeTierArchiveCounts(boundRootSid, flippedIds, sessionArchOpt),
|
|
251
|
+
}
|
|
252
|
+
const hostCompat = probeSubagentSupport(runtime)
|
|
253
|
+
sendJson(res, 200, {
|
|
254
|
+
ok: true,
|
|
255
|
+
board,
|
|
256
|
+
subagents,
|
|
257
|
+
agentIdentity,
|
|
258
|
+
teamTasks: sessionId ? fetchTeamTasks(runtime, { id: sessionId }) : undefined,
|
|
259
|
+
boundaries: boundaries(runtime, sessionId),
|
|
260
|
+
hostCompat,
|
|
261
|
+
chiefMeta: {
|
|
262
|
+
backendBuild: BACKEND_BUILD,
|
|
263
|
+
hostCompat,
|
|
264
|
+
paceMode: effCfg.paceMode || 'manual',
|
|
265
|
+
stopped: Boolean(effCfg.stopped || effCfg.paceMode === 'stopped'),
|
|
266
|
+
permissionMode: effCfg.permissionMode || DEFAULT_CHIEF_PERMISSION_MODE,
|
|
267
|
+
chiefRiskAcknowledged: Boolean(effCfg.chiefRiskVerified),
|
|
268
|
+
pendingApprovalsCount: ((rootWs && Array.isArray(rootWs.pendingApprovals)) ? rootWs.pendingApprovals : []).filter(a => a && a.status === 'pending').length,
|
|
269
|
+
hasPendingElevation: Boolean(rootWs && rootWs.pendingElevation && rootWs.pendingElevation.status === 'pending'),
|
|
270
|
+
autoPilot: Boolean(effCfg.autoPilot),
|
|
271
|
+
tacticalModes,
|
|
272
|
+
runtimeGuard: (rootWs && rootWs.runtimeGuard) || {},
|
|
273
|
+
flippedCount: flippedIds.length,
|
|
274
|
+
modelRef: pinnedModelRef,
|
|
275
|
+
followModelRef,
|
|
276
|
+
resolvedModelRef: pinnedModelRef || followModelRef || '',
|
|
277
|
+
pendingSuggestions,
|
|
278
|
+
factsCount,
|
|
279
|
+
mailboxCount,
|
|
280
|
+
linkedPeersCount: Math.max(0, cluster.length - 1),
|
|
281
|
+
contextUsage: sessionId ? getSessionContextBreakdown(runtime, sessionId) : null,
|
|
282
|
+
},
|
|
283
|
+
archiveMeta,
|
|
284
|
+
})
|
|
285
|
+
} catch (error) {
|
|
286
|
+
sendJson(res, 500, { ok: false, error: String(error && error.message ? error.message : error) })
|
|
287
|
+
}
|
|
288
|
+
},
|
|
289
|
+
},
|
|
290
|
+
{
|
|
291
|
+
path: API + '/digest',
|
|
292
|
+
handler: async (req, res) => {
|
|
293
|
+
if (!guard(req, res)) return
|
|
294
|
+
try {
|
|
295
|
+
let sessionId = ''
|
|
296
|
+
try {
|
|
297
|
+
sessionId = new URL(req.url || '/', 'http://127.0.0.1').searchParams.get('session') || ''
|
|
298
|
+
} catch {}
|
|
299
|
+
const board = sessionId ? loadBoard(boardFileFor(sessionId)) : emptyBoard()
|
|
300
|
+
const fullBoard = sessionId ? boardForSession(boardFileFor(sessionId)) : board
|
|
301
|
+
const subagents = sessionId ? await refreshSubagentTree(runtime, sessionId, fullBoard) : []
|
|
302
|
+
const agentIdentity = sessionId ? resolveAgentIdentity(runtime, sessionId) : null
|
|
303
|
+
const rootSid = resolveRootSessionId(sessionId) || sessionId
|
|
304
|
+
const linked = linkedPeersForSession(runtime, rootSid)
|
|
305
|
+
const archCtx = collectDigestArchiveContext(runtime, rootSid, fullBoard.activeCabinetId)
|
|
306
|
+
sendJson(res, 200, {
|
|
307
|
+
ok: true,
|
|
308
|
+
digest: renderDigest(fullBoard, {
|
|
309
|
+
subagents,
|
|
310
|
+
agentIdentity,
|
|
311
|
+
teamTasks: sessionId ? fetchTeamTasks(runtime, { id: sessionId }) : undefined,
|
|
312
|
+
takenOutArchives: archCtx.takenOutArchives,
|
|
313
|
+
sessionArchiveBriefs: archCtx.sessionArchiveBriefs,
|
|
314
|
+
smartCompactActive: archCtx.smartCompactActive,
|
|
315
|
+
chiefPermissionMode: archCtx.chiefPermissionMode,
|
|
316
|
+
linkedPeersCount: linked.linkedPeersCount,
|
|
317
|
+
linkedPeersProgress: linked.linkedPeersProgress,
|
|
318
|
+
}),
|
|
319
|
+
sessions: board.sessions || {},
|
|
320
|
+
updatedAt: board.updatedAt,
|
|
321
|
+
})
|
|
322
|
+
} catch (error) {
|
|
323
|
+
sendJson(res, 500, { ok: false, error: String(error && error.message ? error.message : error) })
|
|
324
|
+
}
|
|
325
|
+
},
|
|
326
|
+
},
|
|
327
|
+
{
|
|
328
|
+
path: API + '/memory',
|
|
329
|
+
handler: (req, res) => {
|
|
330
|
+
if (!guard(req, res)) return
|
|
331
|
+
let sessionId = ''
|
|
332
|
+
try {
|
|
333
|
+
sessionId = new URL(req.url || '/', 'http://127.0.0.1').searchParams.get('session') || ''
|
|
334
|
+
} catch {}
|
|
335
|
+
const board = sessionId ? loadBoard(boardFileFor(sessionId)) : emptyBoard()
|
|
336
|
+
sendJson(res, 200, {
|
|
337
|
+
ok: true,
|
|
338
|
+
sections: memorySections(board, 8),
|
|
339
|
+
count: (board.memory || []).length,
|
|
340
|
+
digest: renderMemoryDigest(board, 400),
|
|
341
|
+
settings: board.settings || {},
|
|
342
|
+
updatedAt: board.updatedAt,
|
|
343
|
+
})
|
|
344
|
+
},
|
|
345
|
+
},
|
|
346
|
+
{
|
|
347
|
+
path: API + '/transfer',
|
|
348
|
+
handler: async (req, res) => {
|
|
349
|
+
if (!guard(req, res)) return
|
|
350
|
+
try {
|
|
351
|
+
const body = await readBody(req)
|
|
352
|
+
const result = await transferChief(runtime, body, typeof body.session === 'string' ? body.session : '')
|
|
353
|
+
sendJson(res, result.ok ? 200 : 400, result)
|
|
354
|
+
} catch (error) {
|
|
355
|
+
sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
|
|
356
|
+
}
|
|
357
|
+
},
|
|
358
|
+
},
|
|
359
|
+
{
|
|
360
|
+
path: API + '/sessions',
|
|
361
|
+
handler: (req, res) => {
|
|
362
|
+
if (!guard(req, res)) return
|
|
363
|
+
let sessionId = ''
|
|
364
|
+
try {
|
|
365
|
+
sessionId = new URL(req.url || '/', 'http://127.0.0.1').searchParams.get('session') || ''
|
|
366
|
+
} catch {}
|
|
367
|
+
const agents = runtime.get('agents')
|
|
368
|
+
const own = loadBoard(boardFileFor(sessionId))
|
|
369
|
+
const shared = loadBoard()
|
|
370
|
+
const fresher = (a, b) => ((a && a.lastSeen) || 0) >= ((b && b.lastSeen) || 0) ? a : b
|
|
371
|
+
const heartbeat = id => {
|
|
372
|
+
const a = (own.sessions || {})[id]
|
|
373
|
+
const b = (shared.sessions || {})[id]
|
|
374
|
+
return fresher(a, b) || {}
|
|
375
|
+
}
|
|
376
|
+
const settings = shared.settings || {}
|
|
377
|
+
const list = agents && typeof agents.list === 'function' ? agents.list() : []
|
|
378
|
+
const archived = safe(() => runtime.get('workspaceRegistry').archivedSessionIds, [])
|
|
379
|
+
const retired = Array.isArray(archived) ? archived : []
|
|
380
|
+
const live = list.filter(agent => {
|
|
381
|
+
const id = String(agent.id)
|
|
382
|
+
return id === sessionId || !retired.includes(id)
|
|
383
|
+
})
|
|
384
|
+
const touched = transcriptTimes()
|
|
385
|
+
sendJson(res, 200, {
|
|
386
|
+
ok: true,
|
|
387
|
+
sessions: live.map(agent => {
|
|
388
|
+
const id = String(agent.id)
|
|
389
|
+
const row = heartbeat(id)
|
|
390
|
+
const seen = row.lastSeen || touched.get(id) || 0
|
|
391
|
+
return {
|
|
392
|
+
id,
|
|
393
|
+
name: sessionName(runtime, agent),
|
|
394
|
+
turns: row.turns || 0,
|
|
395
|
+
lastSeen: seen,
|
|
396
|
+
}
|
|
397
|
+
}),
|
|
398
|
+
archived: retired.length,
|
|
399
|
+
pending: readPending() ? { at: readPending().at, by: readPending().by } : null,
|
|
400
|
+
autoInject: !(settings.autoInject === false),
|
|
401
|
+
guardIdle: !(settings.guardIdle === false),
|
|
402
|
+
guardMaxPerSession: guardCount(settings.guardMaxPerSession, 3, 0, 20),
|
|
403
|
+
guardShortAnswer: guardCount(settings.guardShortAnswer, 600, 0, 10000),
|
|
404
|
+
})
|
|
405
|
+
},
|
|
406
|
+
},
|
|
407
|
+
{
|
|
408
|
+
path: API + '/handoff',
|
|
409
|
+
handler: (req, res) => {
|
|
410
|
+
if (!guard(req, res)) return
|
|
411
|
+
let sessionId = ''
|
|
412
|
+
try {
|
|
413
|
+
sessionId = new URL(req.url || '/', 'http://127.0.0.1').searchParams.get('session') || ''
|
|
414
|
+
} catch {}
|
|
415
|
+
const board = sessionId ? boardForSession(boardFileFor(sessionId)) : emptyBoard()
|
|
416
|
+
const pending = readPending()
|
|
417
|
+
const hInfo = resolveEffectiveHandoff(runtime, sessionId, board)
|
|
418
|
+
sendJson(res, 200, {
|
|
419
|
+
ok: true,
|
|
420
|
+
text: hInfo.text,
|
|
421
|
+
autoText: hInfo.autoText,
|
|
422
|
+
source: hInfo.source,
|
|
423
|
+
isCustom: hInfo.isCustom,
|
|
424
|
+
pinned: hInfo.pinned,
|
|
425
|
+
pinnedAt: hInfo.pinnedAt,
|
|
426
|
+
pinnedBy: hInfo.pinnedBy,
|
|
427
|
+
updatedAt: hInfo.updatedAt,
|
|
428
|
+
handoffAt: hInfo.handoffAt,
|
|
429
|
+
syncOnDigest: hInfo.syncOnDigest,
|
|
430
|
+
isIncomplete: hInfo.isIncomplete,
|
|
431
|
+
isStale: hInfo.isStale,
|
|
432
|
+
hasNarrativeUpdate: hInfo.hasNarrativeUpdate,
|
|
433
|
+
autoInject: !((board.settings || {}).autoInject === false),
|
|
434
|
+
guardIdle: !((board.settings || {}).guardIdle === false),
|
|
435
|
+
pending: pending ? { at: pending.at, by: pending.by, failedTarget: pending.failedTarget || '' } : null,
|
|
436
|
+
})
|
|
437
|
+
},
|
|
438
|
+
},
|
|
439
|
+
{
|
|
440
|
+
path: API + '/action',
|
|
441
|
+
handler: async (req, res) => {
|
|
442
|
+
if (!guard(req, res)) return
|
|
443
|
+
try {
|
|
444
|
+
const body = await readBody(req)
|
|
445
|
+
const sessionId = body && typeof body.session === 'string' ? body.session : ''
|
|
446
|
+
const actName = body && typeof body.action === 'string' ? body.action : ''
|
|
447
|
+
if (actName === 'bounds.propose') {
|
|
448
|
+
const propRes = proposeBoundToChief(makeChiefDeps(runtime), {
|
|
449
|
+
sessionId,
|
|
450
|
+
by: typeof body.by === 'string' ? body.by : 'operator',
|
|
451
|
+
field: normalizeBoundFieldName(body.field) || 'forbidden',
|
|
452
|
+
item: typeof body.item === 'string' ? body.item : (typeof body.text === 'string' ? body.text : ''),
|
|
453
|
+
items: Array.isArray(body.items) ? body.items : undefined,
|
|
454
|
+
reason: typeof body.reason === 'string' ? body.reason : '',
|
|
455
|
+
})
|
|
456
|
+
const board = sessionId ? boardForSession(boardFileFor(sessionId)) : emptyBoard()
|
|
457
|
+
const subagents = sessionId ? await refreshSubagentTree(runtime, sessionId, board) : []
|
|
458
|
+
sendJson(res, propRes.ok ? 200 : 400, {
|
|
459
|
+
...propRes,
|
|
460
|
+
board,
|
|
461
|
+
subagents,
|
|
462
|
+
boundaries: boundaries(runtime, sessionId),
|
|
463
|
+
})
|
|
464
|
+
return
|
|
465
|
+
}
|
|
466
|
+
if (actName === 'task.dispatch' || actName === 'team.steer' || actName === 'team.interrupt') {
|
|
467
|
+
const subResult = await executeSubagentAction(runtime, body, null)
|
|
468
|
+
sendJson(res, subResult.ok ? 200 : 400, {
|
|
469
|
+
...subResult,
|
|
470
|
+
boundaries: boundaries(runtime, sessionId),
|
|
471
|
+
})
|
|
472
|
+
return
|
|
473
|
+
}
|
|
474
|
+
const result = runAction(body)
|
|
475
|
+
const mergedBoard = result.ok && result.board && sessionId
|
|
476
|
+
? boardForSession(boardFileFor(sessionId))
|
|
477
|
+
: result.board
|
|
478
|
+
const subagents = sessionId && mergedBoard ? await refreshSubagentTree(runtime, sessionId, mergedBoard) : []
|
|
479
|
+
sendJson(res, result.ok ? 200 : 400, {
|
|
480
|
+
...result,
|
|
481
|
+
...(mergedBoard ? { board: mergedBoard } : {}),
|
|
482
|
+
subagents,
|
|
483
|
+
boundaries: boundaries(runtime, sessionId),
|
|
484
|
+
})
|
|
485
|
+
} catch (error) {
|
|
486
|
+
sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
|
|
487
|
+
}
|
|
488
|
+
},
|
|
489
|
+
},
|
|
490
|
+
{
|
|
491
|
+
path: API + '/chief/view',
|
|
492
|
+
handler: async (req, res) => {
|
|
493
|
+
if (!guard(req, res)) return
|
|
494
|
+
try {
|
|
495
|
+
const url = new URL(req.url || '/', 'http://127.0.0.1')
|
|
496
|
+
let sessionId = url.searchParams.get('session') || ''
|
|
497
|
+
let regenerate = url.searchParams.get('regenerate') === '1'
|
|
498
|
+
const qSync = url.searchParams.get('syncHandoff')
|
|
499
|
+
let syncHandoff = qSync === '1' || qSync === 'true' ? true : (qSync === '0' || qSync === 'false' ? false : undefined)
|
|
500
|
+
if (req.method === 'POST') {
|
|
501
|
+
const body = await readBody(req).catch(() => ({}))
|
|
502
|
+
if (typeof body.session === 'string' && body.session) sessionId = body.session
|
|
503
|
+
if (body.regenerate === true) regenerate = true
|
|
504
|
+
if (typeof body.syncHandoff === 'boolean') syncHandoff = body.syncHandoff
|
|
505
|
+
}
|
|
506
|
+
const view = await getChiefView(makeChiefDeps(runtime), sessionId, { regenerate, autoSummarize: !regenerate, syncHandoff })
|
|
507
|
+
if (view && view.handoffSyncResult && view.handoffSyncResult.synced && sessionId) {
|
|
508
|
+
sendJson(res, 200, { ...view, board: boardForSession(boardFileFor(sessionId)) })
|
|
509
|
+
return
|
|
510
|
+
}
|
|
511
|
+
sendJson(res, 200, view)
|
|
512
|
+
} catch (error) {
|
|
513
|
+
sendJson(res, 500, { ok: false, error: String(error && error.message ? error.message : error) })
|
|
514
|
+
}
|
|
515
|
+
},
|
|
516
|
+
},
|
|
517
|
+
{
|
|
518
|
+
path: API + '/chief/ask',
|
|
519
|
+
handler: async (req, res) => {
|
|
520
|
+
if (!guard(req, res)) return
|
|
521
|
+
try {
|
|
522
|
+
const body = await readBody(req)
|
|
523
|
+
const sessionId = typeof body.session === 'string' ? body.session : ''
|
|
524
|
+
const out = await askOrCommandChief(makeChiefDeps(runtime), {
|
|
525
|
+
sessionId,
|
|
526
|
+
text: typeof body.text === 'string' ? body.text : '',
|
|
527
|
+
forcedTarget: typeof body.target === 'string' ? body.target : '',
|
|
528
|
+
forcedMode: typeof body.mode === 'string' ? body.mode : 'steer',
|
|
529
|
+
images: Array.isArray(body.images) ? body.images : [],
|
|
530
|
+
})
|
|
531
|
+
const board = out.ok && sessionId ? boardForSession(boardFileFor(sessionId)) : undefined
|
|
532
|
+
sendJson(res, out.ok ? 200 : 400, board ? { ...out, board } : out)
|
|
533
|
+
} catch (error) {
|
|
534
|
+
sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
|
|
535
|
+
}
|
|
536
|
+
},
|
|
537
|
+
},
|
|
538
|
+
{
|
|
539
|
+
path: API + '/chief/relay-archives',
|
|
540
|
+
handler: async (req, res) => {
|
|
541
|
+
if (!guard(req, res)) return
|
|
542
|
+
try {
|
|
543
|
+
const body = await readBody(req)
|
|
544
|
+
const sessionId = typeof body?.session === 'string' ? body.session : ''
|
|
545
|
+
const rootSid = resolveRootSessionId(sessionId) || sessionId || 'global'
|
|
546
|
+
const out = await relayArchivesWithChief(makeChiefDeps(runtime), {
|
|
547
|
+
sessionId: rootSid,
|
|
548
|
+
items: Array.isArray(body?.items) ? body.items : [],
|
|
549
|
+
instruction: typeof body?.instruction === 'string' ? body.instruction : '',
|
|
550
|
+
target: typeof body?.target === 'string' ? body.target : 'lead',
|
|
551
|
+
mode: typeof body?.mode === 'string' ? body.mode : 'steer',
|
|
552
|
+
cabinetId: typeof body?.cabinetId === 'string' ? body.cabinetId : '',
|
|
553
|
+
})
|
|
554
|
+
sendJson(res, out && out.ok === false ? 400 : 200, out)
|
|
555
|
+
} catch (error) {
|
|
556
|
+
sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
|
|
557
|
+
}
|
|
558
|
+
},
|
|
559
|
+
},
|
|
560
|
+
{
|
|
561
|
+
path: API + '/chief/relay',
|
|
562
|
+
handler: async (req, res) => {
|
|
563
|
+
if (!guard(req, res)) return
|
|
564
|
+
try {
|
|
565
|
+
const body = await readBody(req)
|
|
566
|
+
const sessionId = typeof body.session === 'string' ? body.session : ''
|
|
567
|
+
const out = await deliverCrossMessage(makeChiefDeps(runtime), {
|
|
568
|
+
fromSession: sessionId,
|
|
569
|
+
fromLabel: typeof body.by === 'string' && body.by ? body.by : 'DSH 参谋长',
|
|
570
|
+
target: typeof body.target === 'string' ? body.target : 'lead',
|
|
571
|
+
subject: typeof body.subject === 'string' ? body.subject : '',
|
|
572
|
+
text: typeof body.text === 'string' ? body.text : '',
|
|
573
|
+
mode: typeof body.mode === 'string' ? body.mode : 'steer',
|
|
574
|
+
images: Array.isArray(body.images) ? body.images : [],
|
|
575
|
+
})
|
|
576
|
+
const view = await getChiefView(makeChiefDeps(runtime), sessionId, { autoSummarize: false })
|
|
577
|
+
sendJson(res, out.ok ? 200 : 400, { ...out, view })
|
|
578
|
+
} catch (error) {
|
|
579
|
+
sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
|
|
580
|
+
}
|
|
581
|
+
},
|
|
582
|
+
},
|
|
583
|
+
{
|
|
584
|
+
path: API + '/chief/models',
|
|
585
|
+
handler: async (req, res) => {
|
|
586
|
+
if (!guard(req, res)) return
|
|
587
|
+
try {
|
|
588
|
+
const url = new URL(req.url || '/', 'http://127.0.0.1')
|
|
589
|
+
const fresh = url.searchParams.get('fresh') === '1'
|
|
590
|
+
const sessionId = url.searchParams.get('session') || ''
|
|
591
|
+
const catalog = await listChiefModels(makeChiefDeps(runtime), fresh, sessionId)
|
|
592
|
+
sendJson(res, 200, { ok: true, ...catalog })
|
|
593
|
+
} catch (error) {
|
|
594
|
+
sendJson(res, 500, { ok: false, error: String(error && error.message ? error.message : error) })
|
|
595
|
+
}
|
|
596
|
+
},
|
|
597
|
+
},
|
|
598
|
+
{
|
|
599
|
+
path: API + '/chief/config',
|
|
600
|
+
handler: async (req, res) => {
|
|
601
|
+
if (!guard(req, res)) return
|
|
602
|
+
try {
|
|
603
|
+
const body = await readBody(req)
|
|
604
|
+
const sessionId = typeof body?.session === 'string' ? body.session : ''
|
|
605
|
+
const rootSid = resolveRootSessionId(sessionId) || sessionId || 'global'
|
|
606
|
+
const updated = updateChiefConfig({ ...(body || {}), sessionId: rootSid })
|
|
607
|
+
const wantsInterventionOn = Boolean(body && body.tacticalModes && body.tacticalModes.intervention === true)
|
|
608
|
+
const coreObjDraft = typeof body?.coreObjective === 'string' ? body.coreObjective.trim() : ''
|
|
609
|
+
const targetSessionForBoard = sessionId || (rootSid !== 'global' ? rootSid : '')
|
|
610
|
+
if (updated && updated.ok !== false && wantsInterventionOn && coreObjDraft && targetSessionForBoard) {
|
|
611
|
+
runAction({
|
|
612
|
+
action: 'objective.set',
|
|
613
|
+
objective: coreObjDraft,
|
|
614
|
+
session: targetSessionForBoard,
|
|
615
|
+
by: 'operator',
|
|
616
|
+
_fromInterventionSetup: true,
|
|
617
|
+
})
|
|
618
|
+
}
|
|
619
|
+
if (updated && (updated.emergencyStopped || (updated.config && (updated.config.stopped || updated.config.paceMode === 'stopped')))) {
|
|
620
|
+
if (deps.hostState.activeAutoContinue && typeof deps.hostState.activeAutoContinue.cancelSession === 'function') {
|
|
621
|
+
deps.hostState.activeAutoContinue.cancelSession(sessionId, 'chief stopped')
|
|
622
|
+
if (rootSid && rootSid !== sessionId) deps.hostState.activeAutoContinue.cancelSession(rootSid, 'chief stopped')
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
const view = await getChiefView(makeChiefDeps(runtime), sessionId, { autoSummarize: false })
|
|
626
|
+
const latestBoard = targetSessionForBoard ? boardForSession(boardFileFor(targetSessionForBoard)) : null
|
|
627
|
+
sendJson(res, updated && updated.ok === false ? 400 : 200, {
|
|
628
|
+
...updated,
|
|
629
|
+
...(latestBoard ? { board: latestBoard } : {}),
|
|
630
|
+
view,
|
|
631
|
+
})
|
|
632
|
+
} catch (error) {
|
|
633
|
+
sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
|
|
634
|
+
}
|
|
635
|
+
},
|
|
636
|
+
},
|
|
637
|
+
{
|
|
638
|
+
path: API + '/chief/approval',
|
|
639
|
+
handler: async (req, res) => {
|
|
640
|
+
if (!guard(req, res)) return
|
|
641
|
+
try {
|
|
642
|
+
const body = await readBody(req)
|
|
643
|
+
const sessionId = typeof body?.session === 'string' ? body.session : ''
|
|
644
|
+
const out = await handleApprovalDecision(makeChiefDeps(runtime), {
|
|
645
|
+
sessionId,
|
|
646
|
+
approvalId: typeof body?.id === 'string' ? body.id : '',
|
|
647
|
+
decision: body?.decision === 'approve' ? 'approve' : 'reject',
|
|
648
|
+
})
|
|
649
|
+
const board = out.ok && sessionId ? boardForSession(boardFileFor(sessionId)) : undefined
|
|
650
|
+
sendJson(res, out.ok ? 200 : 400, board ? { ...out, board } : out)
|
|
651
|
+
} catch (error) {
|
|
652
|
+
sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
|
|
653
|
+
}
|
|
654
|
+
},
|
|
655
|
+
},
|
|
656
|
+
{
|
|
657
|
+
path: API + '/chief/elevation',
|
|
658
|
+
handler: async (req, res) => {
|
|
659
|
+
if (!guard(req, res)) return
|
|
660
|
+
try {
|
|
661
|
+
const body = await readBody(req)
|
|
662
|
+
const sessionId = typeof body?.session === 'string' ? body.session : ''
|
|
663
|
+
const out = await handleElevationDecision(makeChiefDeps(runtime), {
|
|
664
|
+
sessionId,
|
|
665
|
+
elevationId: typeof body?.id === 'string' ? body.id : '',
|
|
666
|
+
decision: body?.decision === 'approve' ? 'approve' : 'reject',
|
|
667
|
+
targetMode: typeof body?.targetMode === 'string' ? body.targetMode : '',
|
|
668
|
+
confirmedChiefRisk: Boolean(body?.confirmedChiefRisk),
|
|
669
|
+
})
|
|
670
|
+
const board = sessionId ? boardForSession(boardFileFor(sessionId)) : undefined
|
|
671
|
+
sendJson(res, out.ok ? 200 : 400, board ? { ...out, board } : out)
|
|
672
|
+
} catch (error) {
|
|
673
|
+
sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
|
|
674
|
+
}
|
|
675
|
+
},
|
|
676
|
+
},
|
|
677
|
+
{
|
|
678
|
+
path: API + '/chief/suggest-objective',
|
|
679
|
+
handler: async (req, res) => {
|
|
680
|
+
if (!guard(req, res)) return
|
|
681
|
+
try {
|
|
682
|
+
const body = await readBody(req).catch(() => ({}))
|
|
683
|
+
const sessionId = typeof body?.session === 'string' ? body.session : ''
|
|
684
|
+
const out = await suggestCoreObjectiveWithChief(makeChiefDeps(runtime), {
|
|
685
|
+
sessionId,
|
|
686
|
+
draft: typeof body?.draft === 'string' ? body.draft : '',
|
|
687
|
+
mode: typeof body?.mode === 'string' ? body.mode : 'auto',
|
|
688
|
+
previousSuggestions: Array.isArray(body?.previousSuggestions) ? body.previousSuggestions : [],
|
|
689
|
+
})
|
|
690
|
+
sendJson(res, out && out.ok === false ? 400 : 200, out)
|
|
691
|
+
} catch (error) {
|
|
692
|
+
sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
|
|
693
|
+
}
|
|
694
|
+
},
|
|
695
|
+
},
|
|
696
|
+
{
|
|
697
|
+
path: API + '/chief/recommend-compact',
|
|
698
|
+
handler: async (req, res) => {
|
|
699
|
+
if (!guard(req, res)) return
|
|
700
|
+
try {
|
|
701
|
+
const body = await readBody(req).catch(() => ({}))
|
|
702
|
+
const sessionId = typeof body?.session === 'string' ? body.session : ''
|
|
703
|
+
const out = await recommendAndSetCompactThreshold(makeChiefDeps(runtime), { sessionId })
|
|
704
|
+
sendJson(res, out && out.ok === false ? 400 : 200, out)
|
|
705
|
+
} catch (error) {
|
|
706
|
+
sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
|
|
707
|
+
}
|
|
708
|
+
},
|
|
709
|
+
},
|
|
710
|
+
{
|
|
711
|
+
path: API + '/chief/link',
|
|
712
|
+
handler: async (req, res) => {
|
|
713
|
+
if (!guard(req, res)) return
|
|
714
|
+
try {
|
|
715
|
+
const body = await readBody(req)
|
|
716
|
+
const sessionId = typeof body.session === 'string' ? body.session : ''
|
|
717
|
+
const peerSession = typeof body.peerSession === 'string' ? body.peerSession : ''
|
|
718
|
+
const rootA = resolveRootSessionId(sessionId) || sessionId
|
|
719
|
+
const rootB = resolveRootSessionId(peerSession) || peerSession
|
|
720
|
+
const linked = Boolean(body.linked)
|
|
721
|
+
const out = setPeerLink(rootA, rootB, linked)
|
|
722
|
+
if (!out.ok) {
|
|
723
|
+
sendJson(res, 400, out)
|
|
724
|
+
return
|
|
725
|
+
}
|
|
726
|
+
const view = await getChiefView(makeChiefDeps(runtime), rootA, { autoSummarize: false })
|
|
727
|
+
sendJson(res, 200, { ...out, view })
|
|
728
|
+
} catch (error) {
|
|
729
|
+
sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
|
|
730
|
+
}
|
|
731
|
+
},
|
|
732
|
+
},
|
|
733
|
+
{
|
|
734
|
+
path: API + '/chief/suggestion',
|
|
735
|
+
handler: async (req, res) => {
|
|
736
|
+
if (!guard(req, res)) return
|
|
737
|
+
try {
|
|
738
|
+
const body = await readBody(req)
|
|
739
|
+
const sessionId = typeof body.session === 'string' ? body.session : ''
|
|
740
|
+
const isBatch = body.decision === 'execute_batch' || body.batch === true
|
|
741
|
+
const out = isBatch
|
|
742
|
+
? await executeBatchSuggestions(makeChiefDeps(runtime), {
|
|
743
|
+
sessionId,
|
|
744
|
+
ids: Array.isArray(body.ids) ? body.ids : [],
|
|
745
|
+
includeGoalApproval: Boolean(body.includeGoalApproval),
|
|
746
|
+
pinGlobalDefault: typeof body.pinGlobal === 'boolean'
|
|
747
|
+
? body.pinGlobal
|
|
748
|
+
: (typeof body.pinGlobalDefault === 'boolean' ? body.pinGlobalDefault : undefined),
|
|
749
|
+
})
|
|
750
|
+
: await handleSuggestionDecision(makeChiefDeps(runtime), {
|
|
751
|
+
sessionId,
|
|
752
|
+
suggestionId: typeof body.id === 'string' ? body.id : '',
|
|
753
|
+
decision: body.decision === 'approve' ? 'approve' : 'dismiss',
|
|
754
|
+
editedText: typeof body.text === 'string' ? body.text : '',
|
|
755
|
+
boundField: typeof body.boundField === 'string' ? body.boundField : '',
|
|
756
|
+
pinGlobal: typeof body.pinGlobal === 'boolean' ? body.pinGlobal : undefined,
|
|
757
|
+
})
|
|
758
|
+
const board = out.ok && sessionId ? boardForSession(boardFileFor(sessionId)) : undefined
|
|
759
|
+
sendJson(res, out.ok ? 200 : 400, board ? { ...out, board } : out)
|
|
760
|
+
} catch (error) {
|
|
761
|
+
sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
|
|
762
|
+
}
|
|
763
|
+
},
|
|
764
|
+
},
|
|
765
|
+
{
|
|
766
|
+
path: API + '/chief/consolidate-bounds',
|
|
767
|
+
handler: async (req, res) => {
|
|
768
|
+
if (!guard(req, res)) return
|
|
769
|
+
try {
|
|
770
|
+
const body = await readBody(req)
|
|
771
|
+
const sessionId = typeof body.session === 'string' ? body.session : ''
|
|
772
|
+
const out = await consolidateBoundsWithChief(makeChiefDeps(runtime), {
|
|
773
|
+
sessionId,
|
|
774
|
+
field: typeof body.field === 'string' ? body.field : '',
|
|
775
|
+
items: Array.isArray(body.items) ? body.items : [],
|
|
776
|
+
instruction: typeof body.instruction === 'string' ? body.instruction : '',
|
|
777
|
+
})
|
|
778
|
+
const board = sessionId ? boardForSession(boardFileFor(sessionId)) : undefined
|
|
779
|
+
sendJson(res, out.ok ? 200 : 400, board ? { ...out, board } : out)
|
|
780
|
+
} catch (error) {
|
|
781
|
+
sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
|
|
782
|
+
}
|
|
783
|
+
},
|
|
784
|
+
},
|
|
785
|
+
{
|
|
786
|
+
path: API + '/chief/fact',
|
|
787
|
+
handler: async (req, res) => {
|
|
788
|
+
if (!guard(req, res)) return
|
|
789
|
+
try {
|
|
790
|
+
const body = await readBody(req)
|
|
791
|
+
const sessionId = typeof body.session === 'string' ? body.session : ''
|
|
792
|
+
const out = mutateChiefFact(makeChiefDeps(runtime), {
|
|
793
|
+
sessionId,
|
|
794
|
+
op: typeof body.op === 'string' ? body.op : 'add',
|
|
795
|
+
id: typeof body.id === 'string' ? body.id : '',
|
|
796
|
+
text: typeof body.text === 'string' ? body.text : '',
|
|
797
|
+
category: typeof body.category === 'string' ? body.category : 'discipline',
|
|
798
|
+
pinned: Boolean(body.pinned),
|
|
799
|
+
})
|
|
800
|
+
if (!out.ok) {
|
|
801
|
+
sendJson(res, 400, out)
|
|
802
|
+
return
|
|
803
|
+
}
|
|
804
|
+
const view = await getChiefView(makeChiefDeps(runtime), sessionId, { autoSummarize: false })
|
|
805
|
+
sendJson(res, 200, { ...out, view })
|
|
806
|
+
} catch (error) {
|
|
807
|
+
sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
|
|
808
|
+
}
|
|
809
|
+
},
|
|
810
|
+
},
|
|
811
|
+
{
|
|
812
|
+
path: API + '/archives',
|
|
813
|
+
handler: async (req, res) => {
|
|
814
|
+
if (!guard(req, res)) return
|
|
815
|
+
try {
|
|
816
|
+
const url = new URL(req.url || '/', 'http://127.0.0.1')
|
|
817
|
+
if (req.method === 'GET' || !req.method) {
|
|
818
|
+
const sessionId = url.searchParams.get('session') || ''
|
|
819
|
+
const rootSid = resolveBoundRootSid(sessionId)
|
|
820
|
+
const query = url.searchParams.get('q') || ''
|
|
821
|
+
const folder = url.searchParams.get('folder') || ''
|
|
822
|
+
const paperclip = url.searchParams.get('paperclip') || ''
|
|
823
|
+
const reqScope = resolveArchiveHttpScope(url.searchParams.get('scope') || url.searchParams.get('vaultScope') || '')
|
|
824
|
+
const workingScope = reqScope === 'global' ? 'global' : 'session'
|
|
825
|
+
const cabinetId = workingScope === 'global' ? '' : (url.searchParams.get('cabinetId') || '')
|
|
826
|
+
const targetOpt = archiveTarget(runtime, rootSid, { cabinetId, vaultScope: workingScope })
|
|
827
|
+
const st = loadChiefState()
|
|
828
|
+
const ws = rootSid && st.workspaces ? st.workspaces[rootSid] : null
|
|
829
|
+
const flippedIds = (ws && Array.isArray(ws.flippedPrecipitatedIds)) ? ws.flippedPrecipitatedIds.slice() : []
|
|
830
|
+
const out = listArchiveHeaders(rootSid, {
|
|
831
|
+
query,
|
|
832
|
+
folder,
|
|
833
|
+
paperclip,
|
|
834
|
+
vaultScope: workingScope,
|
|
835
|
+
includePrecipitated: true,
|
|
836
|
+
flippedIds,
|
|
837
|
+
}, targetOpt)
|
|
838
|
+
sendJson(res, 200, {
|
|
839
|
+
...out,
|
|
840
|
+
requestedScope: reqScope,
|
|
841
|
+
flippedPrecipitatedIds: flippedIds,
|
|
842
|
+
deskItems: collectDeskItemsForUi(runtime, rootSid, cabinetId),
|
|
843
|
+
counts: out.counts || getThreeTierArchiveCounts(rootSid, flippedIds, targetOpt),
|
|
844
|
+
archiveMeta: getArchiveMeta(rootSid, targetOpt),
|
|
845
|
+
})
|
|
846
|
+
return
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
const body = await readBody(req)
|
|
850
|
+
const sessionId = typeof body.session === 'string' ? body.session : ''
|
|
851
|
+
const rootSid = resolveBoundRootSid(sessionId)
|
|
852
|
+
const op = typeof body.op === 'string' ? body.op : 'save'
|
|
853
|
+
const reqScope = resolveArchiveHttpScope(body.vaultScope || body.scope || '')
|
|
854
|
+
const workingScope = reqScope === 'global' ? 'global' : 'session'
|
|
855
|
+
const cabinetId = workingScope === 'global' ? '' : (typeof body.cabinetId === 'string' ? body.cabinetId : '')
|
|
856
|
+
const targetOpt = archiveTarget(runtime, rootSid, { cabinetId, vaultScope: workingScope })
|
|
857
|
+
const projectKey = resolveProjectKey(targetOpt.cwd)
|
|
858
|
+
|
|
859
|
+
if (['flipOut', 'sealBack', 'deletePrecipitated', 'updatePrecipitated'].includes(op)) {
|
|
860
|
+
const pid = typeof body.id === 'string' ? body.id : (typeof body.precipitatedId === 'string' ? body.precipitatedId : '')
|
|
861
|
+
const pRes = mutatePrecipitated(projectKey, {
|
|
862
|
+
...body,
|
|
863
|
+
id: pid,
|
|
864
|
+
precipitatedId: pid,
|
|
865
|
+
op,
|
|
866
|
+
rootSessionId: rootSid,
|
|
867
|
+
}, targetOpt)
|
|
868
|
+
if (!pRes.ok) {
|
|
869
|
+
sendJson(res, 400, pRes)
|
|
870
|
+
return
|
|
871
|
+
}
|
|
872
|
+
if (rootSid) {
|
|
873
|
+
if (op === 'flipOut' && pid) updateWorkspaceFlippedIds(rootSid, { flippedId: pid })
|
|
874
|
+
else if ((op === 'sealBack' || op === 'deletePrecipitated') && pid) updateWorkspaceFlippedIds(rootSid, { sealId: pid })
|
|
875
|
+
}
|
|
876
|
+
const stAfter = loadChiefState()
|
|
877
|
+
const wsAfter = rootSid && stAfter.workspaces ? stAfter.workspaces[rootSid] : null
|
|
878
|
+
const flippedAfter = (wsAfter && Array.isArray(wsAfter.flippedPrecipitatedIds)) ? wsAfter.flippedPrecipitatedIds.slice() : []
|
|
879
|
+
const archives = listArchiveHeaders(rootSid, { vaultScope: workingScope, includePrecipitated: true, flippedIds: flippedAfter }, targetOpt)
|
|
880
|
+
sendJson(res, 200, {
|
|
881
|
+
...pRes,
|
|
882
|
+
archives,
|
|
883
|
+
deskItems: collectDeskItemsForUi(runtime, rootSid, cabinetId),
|
|
884
|
+
counts: archives.counts || getThreeTierArchiveCounts(rootSid, flippedAfter, targetOpt),
|
|
885
|
+
flippedPrecipitatedIds: flippedAfter,
|
|
886
|
+
archiveMeta: getArchiveMeta(rootSid, targetOpt),
|
|
887
|
+
})
|
|
888
|
+
return
|
|
889
|
+
}
|
|
890
|
+
|
|
891
|
+
if (op === 'pullPrecipitated') {
|
|
892
|
+
const pid = typeof body.id === 'string' ? body.id : (typeof body.precipitatedId === 'string' ? body.precipitatedId : '')
|
|
893
|
+
const targetScope = resolveArchiveHttpScope(body.targetScope || body.toScope || 'session') === 'global' ? 'global' : 'session'
|
|
894
|
+
const copyRes = copyPrecipitatedToVault(projectKey, {
|
|
895
|
+
...body,
|
|
896
|
+
id: pid,
|
|
897
|
+
precipitatedId: pid,
|
|
898
|
+
targetScope,
|
|
899
|
+
rootSessionId: rootSid,
|
|
900
|
+
}, targetOpt)
|
|
901
|
+
if (!copyRes.ok) {
|
|
902
|
+
sendJson(res, 400, copyRes)
|
|
903
|
+
return
|
|
904
|
+
}
|
|
905
|
+
const stAfter = loadChiefState()
|
|
906
|
+
const wsAfter = rootSid && stAfter.workspaces ? stAfter.workspaces[rootSid] : null
|
|
907
|
+
const flippedAfter = (wsAfter && Array.isArray(wsAfter.flippedPrecipitatedIds)) ? wsAfter.flippedPrecipitatedIds.slice() : []
|
|
908
|
+
const archives = listArchiveHeaders(rootSid, { vaultScope: workingScope, includePrecipitated: true, flippedIds: flippedAfter }, targetOpt)
|
|
909
|
+
sendJson(res, 200, {
|
|
910
|
+
...copyRes,
|
|
911
|
+
archives,
|
|
912
|
+
deskItems: collectDeskItemsForUi(runtime, rootSid, cabinetId),
|
|
913
|
+
counts: archives.counts || getThreeTierArchiveCounts(rootSid, flippedAfter, targetOpt),
|
|
914
|
+
flippedPrecipitatedIds: flippedAfter,
|
|
915
|
+
archiveMeta: getArchiveMeta(rootSid, targetOpt),
|
|
916
|
+
})
|
|
917
|
+
return
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
if (op === 'precipitateNotes') {
|
|
921
|
+
// Sweep active board.notes (session / rootSession / matched shared notes) into active working cabinet
|
|
922
|
+
const NOTE_SWEEP_SECRET_RE = /(?:sk-[a-zA-Z0-9_-]{16,}|ghp_[a-zA-Z0-9]{20,}|AKIA[0-9A-Z]{16}|AIza[0-9A-Za-z_-]{30,}|Bearer\s+[A-Za-z0-9._~+/=-]{20,}|-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----|-----BEGIN [A-Z ]*PRIVATE KEY-----)/g
|
|
923
|
+
const noteIds = Array.isArray(body.noteIds) && body.noteIds.length > 0
|
|
924
|
+
? new Set(body.noteIds.map(String))
|
|
925
|
+
: null
|
|
926
|
+
let sweptCount = 0
|
|
927
|
+
const sweptIds = new Set()
|
|
928
|
+
const savedFolders = new Set()
|
|
929
|
+
let lastCabId = ''
|
|
930
|
+
|
|
931
|
+
const saveNoteIntoArchive = (note) => {
|
|
932
|
+
const paperclip = (note.pinned || (note.tags || []).includes('anchor')) ? 'gold' : undefined
|
|
933
|
+
const basePayload = {
|
|
934
|
+
op: 'save',
|
|
935
|
+
vaultScope: workingScope,
|
|
936
|
+
sourceNoteId: note.id,
|
|
937
|
+
title: note.title,
|
|
938
|
+
body: note.body,
|
|
939
|
+
tags: note.tags,
|
|
940
|
+
paperclip,
|
|
941
|
+
by: note.by || 'user',
|
|
942
|
+
rootSessionId: rootSid,
|
|
943
|
+
}
|
|
944
|
+
let saved = mutateArchive(basePayload, targetOpt)
|
|
945
|
+
if (!saved.ok && typeof saved.error === 'string' && /秘钥|凭据|密钥|SECRET|Token/i.test(saved.error)) {
|
|
946
|
+
const redactedTitle = String(note.title || '').replace(NOTE_SWEEP_SECRET_RE, '[REDACTED]')
|
|
947
|
+
const redactedBody = String(note.body || '').replace(NOTE_SWEEP_SECRET_RE, '[REDACTED]')
|
|
948
|
+
saved = mutateArchive({
|
|
949
|
+
...basePayload,
|
|
950
|
+
title: redactedTitle,
|
|
951
|
+
body: redactedBody,
|
|
952
|
+
}, targetOpt)
|
|
953
|
+
}
|
|
954
|
+
return saved
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
const sweepFromFile = (targetFile, { allowUnfiltered = true } = {}) => {
|
|
958
|
+
if (!targetFile || !fs.existsSync(targetFile)) return
|
|
959
|
+
withBoardLock(targetFile, () => {
|
|
960
|
+
const b = loadBoard(targetFile)
|
|
961
|
+
if (!Array.isArray(b.notes) || !b.notes.length) return
|
|
962
|
+
const keep = []
|
|
963
|
+
let fileSwept = 0
|
|
964
|
+
let changed = false
|
|
965
|
+
for (const note of b.notes) {
|
|
966
|
+
if (!note || !note.id) {
|
|
967
|
+
keep.push(note)
|
|
968
|
+
continue
|
|
969
|
+
}
|
|
970
|
+
if (sweptIds.has(note.id)) {
|
|
971
|
+
changed = true
|
|
972
|
+
continue
|
|
973
|
+
}
|
|
974
|
+
if (noteIds) {
|
|
975
|
+
if (!noteIds.has(note.id)) {
|
|
976
|
+
keep.push(note)
|
|
977
|
+
continue
|
|
978
|
+
}
|
|
979
|
+
} else if (!allowUnfiltered && (note.pinned || (Array.isArray(note.tags) && note.tags.includes('anchor')))) {
|
|
980
|
+
keep.push(note)
|
|
981
|
+
continue
|
|
982
|
+
}
|
|
983
|
+
const saved = saveNoteIntoArchive(note)
|
|
984
|
+
if (saved.ok) {
|
|
985
|
+
sweptCount += 1
|
|
986
|
+
fileSwept += 1
|
|
987
|
+
changed = true
|
|
988
|
+
sweptIds.add(note.id)
|
|
989
|
+
if (saved.item && saved.item.folder) savedFolders.add(saved.item.folder)
|
|
990
|
+
const cab = (saved.meta && saved.meta.activeCabinetId) || saved.activeCabinetId || saved.cabinetId || ''
|
|
991
|
+
if (cab) lastCabId = cab
|
|
992
|
+
} else {
|
|
993
|
+
keep.push(note)
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
if (changed) {
|
|
997
|
+
b.notes = keep
|
|
998
|
+
if (fileSwept > 0) {
|
|
999
|
+
pushLog(b, `🗄️ 已将 ${fileSwept} 篇便签收纳进「${workingScope === 'global' ? '全局' : '本会话'}档案柜」`, 'operator', sessionId)
|
|
1000
|
+
}
|
|
1001
|
+
saveBoard(b, targetFile)
|
|
1002
|
+
}
|
|
1003
|
+
})
|
|
1004
|
+
}
|
|
1005
|
+
|
|
1006
|
+
if (sessionId) {
|
|
1007
|
+
const candidateFiles = []
|
|
1008
|
+
const addFile = (f, allowUnfiltered) => {
|
|
1009
|
+
if (!f) return
|
|
1010
|
+
const norm = path.resolve(f)
|
|
1011
|
+
if (!candidateFiles.some(x => x.norm === norm)) {
|
|
1012
|
+
candidateFiles.push({ file: f, norm, allowUnfiltered })
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
addFile(boardFileFor(sessionId), true)
|
|
1016
|
+
if (rootSid && rootSid !== sessionId) addFile(boardFileFor(rootSid), true)
|
|
1017
|
+
for (const cand of candidateFiles) {
|
|
1018
|
+
sweepFromFile(cand.file, { allowUnfiltered: cand.allowUnfiltered })
|
|
1019
|
+
}
|
|
1020
|
+
if ((noteIds && sweptIds.size < noteIds.size) || sweptCount === 0) {
|
|
1021
|
+
sweepFromFile(boardFile(), { allowUnfiltered: false })
|
|
1022
|
+
}
|
|
1023
|
+
} else {
|
|
1024
|
+
sweepFromFile(boardFile(), { allowUnfiltered: true })
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
if (rootSid && workingScope !== 'global' && lastCabId) {
|
|
1028
|
+
const bFile = boardFileFor(rootSid)
|
|
1029
|
+
withBoardLock(bFile, () => {
|
|
1030
|
+
const b = loadBoard(bFile)
|
|
1031
|
+
if (!b.activeCabinetId) {
|
|
1032
|
+
b.activeCabinetId = lastCabId
|
|
1033
|
+
saveBoard(b, bFile)
|
|
1034
|
+
}
|
|
1035
|
+
})
|
|
1036
|
+
}
|
|
1037
|
+
|
|
1038
|
+
const finalOpt = archiveTarget(runtime, rootSid || sessionId, {
|
|
1039
|
+
cabinetId: lastCabId || cabinetId,
|
|
1040
|
+
vaultScope: workingScope,
|
|
1041
|
+
})
|
|
1042
|
+
const stNow = loadChiefState()
|
|
1043
|
+
const wsNow = rootSid && stNow.workspaces ? stNow.workspaces[rootSid] : null
|
|
1044
|
+
const flippedNow = (wsNow && Array.isArray(wsNow.flippedPrecipitatedIds)) ? wsNow.flippedPrecipitatedIds.slice() : []
|
|
1045
|
+
const board = sessionId ? boardForSession(boardFileFor(sessionId)) : boardForSession(boardFile())
|
|
1046
|
+
const archives = listArchiveHeaders(rootSid, { vaultScope: workingScope, includePrecipitated: true, flippedIds: flippedNow }, finalOpt)
|
|
1047
|
+
sendJson(res, 200, {
|
|
1048
|
+
ok: true,
|
|
1049
|
+
sweptCount,
|
|
1050
|
+
savedFolders: [...savedFolders],
|
|
1051
|
+
board,
|
|
1052
|
+
archives,
|
|
1053
|
+
deskItems: collectDeskItemsForUi(runtime, rootSid, lastCabId || cabinetId || ''),
|
|
1054
|
+
counts: archives.counts || getThreeTierArchiveCounts(rootSid, flippedNow, finalOpt),
|
|
1055
|
+
archiveMeta: getArchiveMeta(rootSid, finalOpt),
|
|
1056
|
+
})
|
|
1057
|
+
return
|
|
1058
|
+
}
|
|
1059
|
+
|
|
1060
|
+
const out = mutateArchive({
|
|
1061
|
+
...body,
|
|
1062
|
+
vaultScope: workingScope,
|
|
1063
|
+
op,
|
|
1064
|
+
rootSessionId: rootSid,
|
|
1065
|
+
}, targetOpt)
|
|
1066
|
+
if (!out.ok) {
|
|
1067
|
+
sendJson(res, 400, out)
|
|
1068
|
+
return
|
|
1069
|
+
}
|
|
1070
|
+
const isCrossCopy = op === 'copyToGlobal' || op === 'copyToSession'
|
|
1071
|
+
const usedCabId = out.activeCabinetId || out.cabinetId || ''
|
|
1072
|
+
if (rootSid && workingScope !== 'global' && !isCrossCopy && usedCabId && op !== 'listCabinets') {
|
|
1073
|
+
const bFile = boardFileFor(rootSid)
|
|
1074
|
+
withBoardLock(bFile, () => {
|
|
1075
|
+
const b = loadBoard(bFile)
|
|
1076
|
+
if (op === 'switchCabinet' || op === 'createCabinet' || !b.activeCabinetId) {
|
|
1077
|
+
b.activeCabinetId = usedCabId
|
|
1078
|
+
saveBoard(b, bFile)
|
|
1079
|
+
}
|
|
1080
|
+
})
|
|
1081
|
+
}
|
|
1082
|
+
const stNow = loadChiefState()
|
|
1083
|
+
const wsNow = rootSid && stNow.workspaces ? stNow.workspaces[rootSid] : null
|
|
1084
|
+
const flippedNow = (wsNow && Array.isArray(wsNow.flippedPrecipitatedIds)) ? wsNow.flippedPrecipitatedIds.slice() : []
|
|
1085
|
+
const finalOpt = isCrossCopy
|
|
1086
|
+
? targetOpt
|
|
1087
|
+
: archiveTarget(runtime, rootSid || sessionId, { cabinetId: out.activeCabinetId || cabinetId || out.cabinetId, vaultScope: workingScope })
|
|
1088
|
+
const archives = listArchiveHeaders(rootSid, { vaultScope: workingScope, includePrecipitated: true, flippedIds: flippedNow }, finalOpt)
|
|
1089
|
+
const board = sessionId ? boardForSession(boardFileFor(sessionId)) : undefined
|
|
1090
|
+
sendJson(res, 200, {
|
|
1091
|
+
...out,
|
|
1092
|
+
archives,
|
|
1093
|
+
deskItems: collectDeskItemsForUi(runtime, rootSid, out.activeCabinetId || cabinetId || out.cabinetId || ''),
|
|
1094
|
+
diffSummary: out.diffSummary || archives.diffSummary,
|
|
1095
|
+
counts: out.counts || archives.counts || getThreeTierArchiveCounts(rootSid, flippedNow, finalOpt),
|
|
1096
|
+
...(board ? { board } : {}),
|
|
1097
|
+
archiveMeta: getArchiveMeta(rootSid, finalOpt),
|
|
1098
|
+
})
|
|
1099
|
+
} catch (error) {
|
|
1100
|
+
sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
|
|
1101
|
+
}
|
|
1102
|
+
},
|
|
1103
|
+
},
|
|
1104
|
+
{
|
|
1105
|
+
path: API + '/archives/detail',
|
|
1106
|
+
handler: (req, res) => {
|
|
1107
|
+
if (!guard(req, res)) return
|
|
1108
|
+
try {
|
|
1109
|
+
const url = new URL(req.url || '/', 'http://127.0.0.1')
|
|
1110
|
+
const id = url.searchParams.get('id') || ''
|
|
1111
|
+
const sessionId = url.searchParams.get('session') || ''
|
|
1112
|
+
const reqScope = resolveArchiveHttpScope(url.searchParams.get('scope') || url.searchParams.get('vaultScope') || '')
|
|
1113
|
+
const cabinetId = reqScope === 'global' ? '' : (url.searchParams.get('cabinetId') || '')
|
|
1114
|
+
const isPrecip = url.searchParams.get('precipitated') === '1' || url.searchParams.get('precipitated') === 'true' || reqScope === 'precipitated'
|
|
1115
|
+
const rootSid = resolveBoundRootSid(sessionId)
|
|
1116
|
+
const targetOpt = archiveTarget(runtime, rootSid, { cabinetId, vaultScope: reqScope === 'global' ? 'global' : 'session' })
|
|
1117
|
+
const out = isPrecip
|
|
1118
|
+
? getPrecipitatedDetail(resolveProjectKey(targetOpt.cwd), id, rootSid, targetOpt)
|
|
1119
|
+
: getArchiveDetail(id, rootSid, targetOpt)
|
|
1120
|
+
sendJson(res, out.ok ? 200 : 404, out)
|
|
1121
|
+
} catch (error) {
|
|
1122
|
+
sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
|
|
1123
|
+
}
|
|
1124
|
+
},
|
|
1125
|
+
},
|
|
1126
|
+
{
|
|
1127
|
+
path: API + '/archives/organize',
|
|
1128
|
+
handler: async (req, res) => {
|
|
1129
|
+
if (!guard(req, res)) return
|
|
1130
|
+
try {
|
|
1131
|
+
const body = await readBody(req)
|
|
1132
|
+
const sessionId = typeof body.session === 'string' ? body.session : ''
|
|
1133
|
+
const rootSid = resolveBoundRootSid(sessionId)
|
|
1134
|
+
const vaultScope = resolveArchiveHttpScope(body.vaultScope || body.scope) === 'global' ? 'global' : 'session'
|
|
1135
|
+
const cabinetId = vaultScope === 'global' ? '' : (typeof body.cabinetId === 'string' ? body.cabinetId : '')
|
|
1136
|
+
const targetOpt = archiveTarget(runtime, rootSid, { cabinetId, vaultScope })
|
|
1137
|
+
const out = await organizeArchivesWithChief(makeChiefDeps(runtime), {
|
|
1138
|
+
sessionId: rootSid || 'global',
|
|
1139
|
+
vaultScope,
|
|
1140
|
+
cabinetId,
|
|
1141
|
+
ids: Array.isArray(body.ids) ? body.ids : [],
|
|
1142
|
+
folder: typeof body.folder === 'string' ? body.folder : '',
|
|
1143
|
+
scope: typeof body.scope === 'string' ? body.scope : 'unorganized',
|
|
1144
|
+
instruction: typeof body.instruction === 'string' ? body.instruction : '',
|
|
1145
|
+
})
|
|
1146
|
+
const stNow = loadChiefState()
|
|
1147
|
+
const wsNow = rootSid && stNow.workspaces ? stNow.workspaces[rootSid] : null
|
|
1148
|
+
const flippedNow = (wsNow && Array.isArray(wsNow.flippedPrecipitatedIds)) ? wsNow.flippedPrecipitatedIds.slice() : []
|
|
1149
|
+
sendJson(res, out.ok ? 200 : 400, {
|
|
1150
|
+
...out,
|
|
1151
|
+
counts: getThreeTierArchiveCounts(rootSid, flippedNow, targetOpt),
|
|
1152
|
+
archiveMeta: getArchiveMeta(rootSid, targetOpt),
|
|
1153
|
+
})
|
|
1154
|
+
} catch (error) {
|
|
1155
|
+
sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
|
|
1156
|
+
}
|
|
1157
|
+
},
|
|
1158
|
+
},
|
|
1159
|
+
{
|
|
1160
|
+
path: API + '/archives/distill-to-global',
|
|
1161
|
+
handler: async (req, res) => {
|
|
1162
|
+
if (!guard(req, res)) return
|
|
1163
|
+
try {
|
|
1164
|
+
const body = await readBody(req)
|
|
1165
|
+
const sessionId = typeof body.session === 'string' ? body.session : ''
|
|
1166
|
+
const rootSid = resolveBoundRootSid(sessionId)
|
|
1167
|
+
if (!rootSid) {
|
|
1168
|
+
sendJson(res, 400, { ok: false, error: '当前未绑定具体会话,无法从本会话档案柜提炼' })
|
|
1169
|
+
return
|
|
1170
|
+
}
|
|
1171
|
+
const cabinetId = typeof body.cabinetId === 'string' ? body.cabinetId : ''
|
|
1172
|
+
const targetOpt = archiveTarget(runtime, rootSid, { cabinetId, vaultScope: 'session' })
|
|
1173
|
+
const out = await distillSessionArchivesToGlobal(makeChiefDeps(runtime), {
|
|
1174
|
+
sessionId: rootSid,
|
|
1175
|
+
cabinetId,
|
|
1176
|
+
ids: Array.isArray(body.ids) ? body.ids : null,
|
|
1177
|
+
folder: typeof body.folder === 'string' ? body.folder : '',
|
|
1178
|
+
clearSource: Boolean(body.clearSource),
|
|
1179
|
+
instruction: typeof body.instruction === 'string' ? body.instruction : '',
|
|
1180
|
+
})
|
|
1181
|
+
const stNow = loadChiefState()
|
|
1182
|
+
const wsNow = stNow.workspaces ? stNow.workspaces[rootSid] : null
|
|
1183
|
+
const flippedNow = (wsNow && Array.isArray(wsNow.flippedPrecipitatedIds)) ? wsNow.flippedPrecipitatedIds.slice() : []
|
|
1184
|
+
sendJson(res, out.ok ? 200 : 400, {
|
|
1185
|
+
...out,
|
|
1186
|
+
deskItems: collectDeskItemsForUi(runtime, rootSid, cabinetId),
|
|
1187
|
+
counts: getThreeTierArchiveCounts(rootSid, flippedNow, targetOpt),
|
|
1188
|
+
archiveMeta: getArchiveMeta(rootSid, targetOpt),
|
|
1189
|
+
})
|
|
1190
|
+
} catch (error) {
|
|
1191
|
+
sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
|
|
1192
|
+
}
|
|
1193
|
+
},
|
|
1194
|
+
},
|
|
1195
|
+
{
|
|
1196
|
+
path: API + '/archives/harvest',
|
|
1197
|
+
handler: async (req, res) => {
|
|
1198
|
+
if (!guard(req, res)) return
|
|
1199
|
+
try {
|
|
1200
|
+
const body = await readBody(req)
|
|
1201
|
+
const sessionId = typeof body.session === 'string' ? body.session : ''
|
|
1202
|
+
const rootSid = resolveBoundRootSid(sessionId)
|
|
1203
|
+
const cabinetId = typeof body.cabinetId === 'string' ? body.cabinetId : ''
|
|
1204
|
+
const vaultScope = 'session'
|
|
1205
|
+
const targetOpt = archiveTarget(runtime, rootSid, { cabinetId, vaultScope })
|
|
1206
|
+
const out = await harvestTurnDetailsToArchive(makeChiefDeps(runtime), {
|
|
1207
|
+
sessionId: rootSid,
|
|
1208
|
+
vaultScope,
|
|
1209
|
+
cabinetId,
|
|
1210
|
+
trigger: 'manual',
|
|
1211
|
+
focusHint: typeof body.focusHint === 'string' ? body.focusHint : '',
|
|
1212
|
+
})
|
|
1213
|
+
const stNow = loadChiefState()
|
|
1214
|
+
const wsNow = rootSid && stNow.workspaces ? stNow.workspaces[rootSid] : null
|
|
1215
|
+
const flippedNow = (wsNow && Array.isArray(wsNow.flippedPrecipitatedIds)) ? wsNow.flippedPrecipitatedIds.slice() : []
|
|
1216
|
+
sendJson(res, out.ok ? 200 : 400, {
|
|
1217
|
+
...out,
|
|
1218
|
+
counts: getThreeTierArchiveCounts(rootSid, flippedNow, targetOpt),
|
|
1219
|
+
archiveMeta: getArchiveMeta(rootSid, targetOpt),
|
|
1220
|
+
})
|
|
1221
|
+
} catch (error) {
|
|
1222
|
+
sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
|
|
1223
|
+
}
|
|
1224
|
+
},
|
|
1225
|
+
},
|
|
1226
|
+
{
|
|
1227
|
+
path: API + '/archives/precipitate',
|
|
1228
|
+
handler: async (req, res) => {
|
|
1229
|
+
if (!guard(req, res)) return
|
|
1230
|
+
try {
|
|
1231
|
+
const body = await readBody(req)
|
|
1232
|
+
const sessionId = typeof body.session === 'string' ? body.session : ''
|
|
1233
|
+
const rootSid = resolveRootSessionId(sessionId) || sessionId
|
|
1234
|
+
const cabinetId = typeof body.cabinetId === 'string' ? body.cabinetId : ''
|
|
1235
|
+
const vaultScope = resolveArchiveHttpScope(body.vaultScope || body.scope) === 'global' ? 'global' : 'session'
|
|
1236
|
+
if (vaultScope !== 'global') {
|
|
1237
|
+
sendJson(res, 400, { ok: false, error: '实行三级梯度制度:本会话档案请先升级入「🌐 全局档案柜」,再从全局档案柜沉淀为冷档案' })
|
|
1238
|
+
return
|
|
1239
|
+
}
|
|
1240
|
+
const targetOpt = archiveTarget(runtime, rootSid || sessionId, { cabinetId, vaultScope })
|
|
1241
|
+
const out = await precipitateExperienceWithChief(makeChiefDeps(runtime), {
|
|
1242
|
+
sessionId: rootSid,
|
|
1243
|
+
vaultScope,
|
|
1244
|
+
op: typeof body.op === 'string' ? body.op : 'cabinet',
|
|
1245
|
+
cabinetId,
|
|
1246
|
+
folder: typeof body.folder === 'string' ? body.folder : '',
|
|
1247
|
+
ids: Array.isArray(body.ids) ? body.ids : [],
|
|
1248
|
+
clearSource: Boolean(body.clearSource),
|
|
1249
|
+
})
|
|
1250
|
+
const stNow = loadChiefState()
|
|
1251
|
+
const wsNow = rootSid && stNow.workspaces ? stNow.workspaces[rootSid] : null
|
|
1252
|
+
const flippedNow = (wsNow && Array.isArray(wsNow.flippedPrecipitatedIds)) ? wsNow.flippedPrecipitatedIds.slice() : []
|
|
1253
|
+
sendJson(res, out.ok ? 200 : 400, {
|
|
1254
|
+
...out,
|
|
1255
|
+
counts: getThreeTierArchiveCounts(rootSid, flippedNow, targetOpt),
|
|
1256
|
+
archiveMeta: getArchiveMeta(rootSid, targetOpt),
|
|
1257
|
+
})
|
|
1258
|
+
} catch (error) {
|
|
1259
|
+
sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
|
|
1260
|
+
}
|
|
1261
|
+
},
|
|
1262
|
+
},
|
|
1263
|
+
]
|
|
1264
|
+
}
|
|
1265
|
+
|
|
1266
|
+
return {
|
|
1267
|
+
sendJson,
|
|
1268
|
+
readBody,
|
|
1269
|
+
resolveArchiveHttpScope,
|
|
1270
|
+
resolveBoundRootSid,
|
|
1271
|
+
collectDeskItemsForUi,
|
|
1272
|
+
routeTable,
|
|
1273
|
+
}
|
|
1274
|
+
}
|