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
|
@@ -0,0 +1,1399 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* subagent-runtime.js
|
|
3
|
+
*
|
|
4
|
+
* Subagent tree resolution, workspace lookup, context accounting, compaction, and Chief runtime bridges.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import fs from 'node:fs'
|
|
8
|
+
import path from 'node:path'
|
|
9
|
+
import os from 'node:os'
|
|
10
|
+
import { answerMemory } from './memory.js'
|
|
11
|
+
import {
|
|
12
|
+
loadChiefState,
|
|
13
|
+
getLinkedCluster,
|
|
14
|
+
collectClusterPeerProgress,
|
|
15
|
+
deliverCrossMessage,
|
|
16
|
+
} from './chief.js'
|
|
17
|
+
import {
|
|
18
|
+
API,
|
|
19
|
+
newId,
|
|
20
|
+
nowMs,
|
|
21
|
+
str,
|
|
22
|
+
CAP_TASK_TITLE,
|
|
23
|
+
CAP_TASK_INTENT,
|
|
24
|
+
asBool,
|
|
25
|
+
normalizeTask,
|
|
26
|
+
pushLog,
|
|
27
|
+
safe,
|
|
28
|
+
} from './board-schema.js'
|
|
29
|
+
|
|
30
|
+
export function createSubagentRuntime(deps) {
|
|
31
|
+
|
|
32
|
+
const boardFile = (...args) => deps.boardFile(...args)
|
|
33
|
+
const boardFileFor = (...args) => deps.boardFileFor(...args)
|
|
34
|
+
const boardForSession = (...args) => deps.boardForSession(...args)
|
|
35
|
+
const composeHandoffFromNarrative = (...args) => deps.composeHandoffFromNarrative(...args)
|
|
36
|
+
const injectInto = (...args) => deps.injectInto(...args)
|
|
37
|
+
const loadBoard = (...args) => deps.loadBoard(...args)
|
|
38
|
+
const runAction = (...args) => deps.runAction(...args)
|
|
39
|
+
const saveBoard = (...args) => deps.saveBoard(...args)
|
|
40
|
+
const withBoardLock = (...args) => deps.withBoardLock(...args)
|
|
41
|
+
const writePending = (...args) => deps.writePending(...args)
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Resolve the root Session id for a member of a subagent collaboration tree.
|
|
45
|
+
* Child subagents share their root ("lead") session's chief board so tasks,
|
|
46
|
+
* dependencies, and evidence written by either side appear on one unified graph.
|
|
47
|
+
*/
|
|
48
|
+
function resolveRootSessionId(sessionId, agentHint) {
|
|
49
|
+
const sid = String(sessionId || '').trim()
|
|
50
|
+
if (!sid) return ''
|
|
51
|
+
if (deps.hostState.subagentRootMap.has(sid)) return deps.hostState.subagentRootMap.get(sid)
|
|
52
|
+
try {
|
|
53
|
+
if (deps.hostState.activeRuntime) {
|
|
54
|
+
const subagents = deps.hostState.activeRuntime.get('subagents')
|
|
55
|
+
const agents = deps.hostState.activeRuntime.get('agents')
|
|
56
|
+
const agent = agentHint || (agents && typeof agents.get === 'function' ? agents.get(sid) : null)
|
|
57
|
+
if (subagents && typeof subagents.rootOf === 'function' && agent) {
|
|
58
|
+
const root = subagents.rootOf(agent)
|
|
59
|
+
if (root && root.id) {
|
|
60
|
+
const rootId = String(root.id)
|
|
61
|
+
deps.hostState.subagentRootMap.set(sid, rootId)
|
|
62
|
+
return rootId
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
if (agent && agent.parentId) {
|
|
66
|
+
let cur = agent
|
|
67
|
+
let guard = 0
|
|
68
|
+
while (cur && cur.parentId && guard++ < 12) {
|
|
69
|
+
if (deps.hostState.subagentRootMap.has(cur.parentId)) {
|
|
70
|
+
const rId = deps.hostState.subagentRootMap.get(cur.parentId)
|
|
71
|
+
deps.hostState.subagentRootMap.set(sid, rId)
|
|
72
|
+
return rId
|
|
73
|
+
}
|
|
74
|
+
const nextParent = agents && typeof agents.get === 'function' ? agents.get(cur.parentId) : null
|
|
75
|
+
if (!nextParent) {
|
|
76
|
+
deps.hostState.subagentRootMap.set(sid, String(cur.parentId))
|
|
77
|
+
return String(cur.parentId)
|
|
78
|
+
}
|
|
79
|
+
cur = nextParent
|
|
80
|
+
}
|
|
81
|
+
if (cur && cur.id) {
|
|
82
|
+
deps.hostState.subagentRootMap.set(sid, String(cur.id))
|
|
83
|
+
return String(cur.id)
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
} catch {}
|
|
88
|
+
return sid
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Inspect caller's subagent identity ({ self, parent, rootId, isChild, sessionId }). */
|
|
92
|
+
function resolveAgentIdentity(runtime, sessionId, agentHint) {
|
|
93
|
+
const rt = runtime || deps.hostState.activeRuntime
|
|
94
|
+
const sid = String(sessionId || (agentHint && agentHint.id) || '').trim()
|
|
95
|
+
if (!rt || !sid) return null
|
|
96
|
+
try {
|
|
97
|
+
const subagents = rt.get('subagents')
|
|
98
|
+
const agents = rt.get('agents')
|
|
99
|
+
const agent = agentHint || (agents && typeof agents.get === 'function' ? agents.get(sid) : null)
|
|
100
|
+
if (!subagents || !agent) return null
|
|
101
|
+
const names = typeof subagents.namesOf === 'function' ? subagents.namesOf(agent) : null
|
|
102
|
+
const root = typeof subagents.rootOf === 'function' ? subagents.rootOf(agent) : null
|
|
103
|
+
const rootId = root && root.id ? String(root.id) : sid
|
|
104
|
+
if (rootId) deps.hostState.subagentRootMap.set(sid, rootId)
|
|
105
|
+
if (!names) return { self: 'lead', parent: '', rootId, isChild: sid !== rootId, sessionId: sid }
|
|
106
|
+
return {
|
|
107
|
+
self: String(names.self || 'lead'),
|
|
108
|
+
parent: names.parent ? String(names.parent) : '',
|
|
109
|
+
rootId,
|
|
110
|
+
isChild: Boolean(names.parent) || (names.self && names.self !== 'lead'),
|
|
111
|
+
sessionId: sid,
|
|
112
|
+
}
|
|
113
|
+
} catch {
|
|
114
|
+
const rootId = deps.hostState.subagentRootMap.get(sid) || sid
|
|
115
|
+
return { self: sid === rootId ? 'lead' : sid, parent: '', rootId, isChild: sid !== rootId, sessionId: sid }
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Refresh and cache the subagent tree for a root session. */
|
|
120
|
+
async function refreshSubagentTree(runtime, sessionId, board) {
|
|
121
|
+
const rt = runtime || deps.hostState.activeRuntime
|
|
122
|
+
const rootId = resolveRootSessionId(sessionId)
|
|
123
|
+
if (!rt || !rootId) return getSubagentRoster(rt, rootId, board)
|
|
124
|
+
try {
|
|
125
|
+
const subagents = rt.get('subagents')
|
|
126
|
+
const agents = rt.get('agents')
|
|
127
|
+
if (subagents && typeof subagents.listDescendants === 'function') {
|
|
128
|
+
const entries = await subagents.listDescendants(rootId)
|
|
129
|
+
if (Array.isArray(entries)) {
|
|
130
|
+
for (const entry of entries) {
|
|
131
|
+
if (entry && entry.id) deps.hostState.subagentRootMap.set(String(entry.id), rootId)
|
|
132
|
+
}
|
|
133
|
+
const rows = [
|
|
134
|
+
{
|
|
135
|
+
id: rootId,
|
|
136
|
+
name: 'lead',
|
|
137
|
+
status: agents && agents.get(rootId)?.status === 'running' ? 'running' : 'inactive',
|
|
138
|
+
description: '主代理 (Root Coordinator)',
|
|
139
|
+
mode: 'continuable',
|
|
140
|
+
},
|
|
141
|
+
...entries.map(entry => ({
|
|
142
|
+
id: String(entry.id || ''),
|
|
143
|
+
parentId: String(entry.parentId || rootId),
|
|
144
|
+
name: String(entry.path || entry.name || entry.id || ''),
|
|
145
|
+
status: entry.kind === 'diagnostic'
|
|
146
|
+
? String(entry.reason || 'unavailable')
|
|
147
|
+
: (agents && agents.get(entry.id)?.status === 'running' ? 'running' : 'inactive'),
|
|
148
|
+
description: String(entry.label || entry.description || ''),
|
|
149
|
+
mode: String(entry.mode || 'continuable'),
|
|
150
|
+
})),
|
|
151
|
+
]
|
|
152
|
+
deps.hostState.subagentTreeCache.set(rootId, rows)
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
} catch {}
|
|
156
|
+
return getSubagentRoster(rt, rootId, board)
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Synchronous roster combining cached subagent tree + live agent status + board task assignments. */
|
|
160
|
+
function getSubagentRoster(runtime, sessionId, board) {
|
|
161
|
+
const rt = runtime || deps.hostState.activeRuntime
|
|
162
|
+
const rootId = resolveRootSessionId(sessionId)
|
|
163
|
+
const agents = rt ? rt.get('agents') : null
|
|
164
|
+
const cached = deps.hostState.subagentTreeCache.get(rootId) || []
|
|
165
|
+
const byName = new Map()
|
|
166
|
+
|
|
167
|
+
const liveStatus = (id, fallback) => {
|
|
168
|
+
try {
|
|
169
|
+
if (agents && typeof agents.get === 'function' && id) {
|
|
170
|
+
const a = agents.get(id)
|
|
171
|
+
if (a) return a.status === 'running' ? 'running' : 'inactive'
|
|
172
|
+
}
|
|
173
|
+
} catch {}
|
|
174
|
+
return fallback || 'inactive'
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
for (const row of cached) {
|
|
178
|
+
byName.set(row.name, {
|
|
179
|
+
...row,
|
|
180
|
+
status: liveStatus(row.id, row.status),
|
|
181
|
+
tasks: [],
|
|
182
|
+
})
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
if (!byName.has('lead') && rootId) {
|
|
186
|
+
byName.set('lead', {
|
|
187
|
+
id: rootId,
|
|
188
|
+
name: 'lead',
|
|
189
|
+
status: liveStatus(rootId, 'inactive'),
|
|
190
|
+
description: '主代理 (Root Coordinator)',
|
|
191
|
+
mode: 'continuable',
|
|
192
|
+
tasks: [],
|
|
193
|
+
})
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
const tasks = Array.isArray(board && board.tasks) ? board.tasks : []
|
|
197
|
+
for (const t of tasks) {
|
|
198
|
+
const ownerRaw = String(t.subagent || t.owner || '').trim()
|
|
199
|
+
if (!ownerRaw || ownerRaw === 'agent' || ownerRaw === 'operator' || ownerRaw === 'user') continue
|
|
200
|
+
if (!byName.has(ownerRaw)) {
|
|
201
|
+
byName.set(ownerRaw, {
|
|
202
|
+
id: String(t.session || ''),
|
|
203
|
+
name: ownerRaw,
|
|
204
|
+
status: t.status === 'doing' ? liveStatus(t.session, 'running') : 'inactive',
|
|
205
|
+
description: t.title || '',
|
|
206
|
+
mode: 'continuable',
|
|
207
|
+
tasks: [],
|
|
208
|
+
})
|
|
209
|
+
}
|
|
210
|
+
const entry = byName.get(ownerRaw)
|
|
211
|
+
if (entry) {
|
|
212
|
+
entry.tasks.push({ id: t.id, title: t.title, status: t.status })
|
|
213
|
+
if (!entry.taskId && t.status !== 'done') {
|
|
214
|
+
entry.taskId = t.id
|
|
215
|
+
entry.taskTitle = t.title
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
return [...byName.values()]
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** Probe whether the DSH host provides the post-rc.2 named subagent tree APIs. */
|
|
223
|
+
function probeSubagentSupport(rt) {
|
|
224
|
+
const subagents = rt ? safe(() => rt.get('subagents'), null) : null
|
|
225
|
+
if (!subagents) {
|
|
226
|
+
return {
|
|
227
|
+
present: false,
|
|
228
|
+
namedSubagentsSupported: false,
|
|
229
|
+
missingMethods: [],
|
|
230
|
+
minDshVersion: '0.2.2-rc.2',
|
|
231
|
+
warning: '',
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
const missingMethods = []
|
|
235
|
+
if (typeof subagents.resolveName !== 'function') missingMethods.push('resolveName')
|
|
236
|
+
if (typeof subagents.rootOf !== 'function') missingMethods.push('rootOf')
|
|
237
|
+
if (typeof subagents.namesOf !== 'function') missingMethods.push('namesOf')
|
|
238
|
+
const ok = missingMethods.length === 0
|
|
239
|
+
return {
|
|
240
|
+
present: true,
|
|
241
|
+
namedSubagentsSupported: ok,
|
|
242
|
+
missingMethods,
|
|
243
|
+
minDshVersion: '0.2.2-rc.2',
|
|
244
|
+
warning: ok
|
|
245
|
+
? ''
|
|
246
|
+
: '当前 DSH 宿主版本不支持命名子代理树接口(缺少 subagents.resolveName / rootOf / namesOf,常见于 0.2.2-rc.1 及更早版本)。面板其余功能可正常使用;如需使用子代理派发 (task.dispatch) 与插话 (team.steer),请将 DSH 升级至 >= 0.2.2-rc.2。',
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** The agent a lookup resolves to: the one named, or the one whose turn this is.
|
|
251
|
+
* Kept separate from sessionOf because the boundary report has to NAME the
|
|
252
|
+
* Session it read facts for — the facts were derived from currentInitiator()
|
|
253
|
+
* while the report said sessionId: null, which is unusable on a machine with
|
|
254
|
+
* twenty live agents. */
|
|
255
|
+
function agentOf(runtime, sessionId) {
|
|
256
|
+
const agents = runtime.get('agents')
|
|
257
|
+
try {
|
|
258
|
+
if (sessionId && agents && typeof agents.get === 'function') {
|
|
259
|
+
return agents.get(sessionId) || undefined
|
|
260
|
+
}
|
|
261
|
+
if (agents && typeof agents.currentInitiator === 'function') {
|
|
262
|
+
return agents.currentInitiator() || undefined
|
|
263
|
+
}
|
|
264
|
+
} catch {}
|
|
265
|
+
return undefined
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
function sessionOf(runtime, sessionId) {
|
|
269
|
+
const agent = agentOf(runtime, sessionId)
|
|
270
|
+
return agent && agent.session ? agent.session : undefined
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** One registration per route, as the Host web server expects. */
|
|
274
|
+
/** Names that carry no information in a picker: an empty turn marker, a bare
|
|
275
|
+
* acknowledgement, an injected template, or markup with no words left after
|
|
276
|
+
* it. A board row is allowed to hold any of these — it is a log line, not a
|
|
277
|
+
* title — so the gate lives at read time, not at write time. */
|
|
278
|
+
const NAME_NOISE = [
|
|
279
|
+
/^\[pass\]/i,
|
|
280
|
+
/^\[(?:ok|done|fail|warn)\]/i,
|
|
281
|
+
/^\[dsh-mnemon:/i,
|
|
282
|
+
/^\[handoff\b/i,
|
|
283
|
+
/^\[bot team setup\]/i,
|
|
284
|
+
/^\[参谋看板/,
|
|
285
|
+
/^(?:继续|好的|收到|明白|ok|done|yes|no)$/i,
|
|
286
|
+
/^please\s+continue$/i,
|
|
287
|
+
/^\.{2,}$/,
|
|
288
|
+
/^[\s\p{P}\p{S}]+$/u,
|
|
289
|
+
]
|
|
290
|
+
|
|
291
|
+
/** Room a name gets in the picker. A 60-character board objective rendered in
|
|
292
|
+
* a select box is as unreadable as eight hex characters — it truncates to a
|
|
293
|
+
* fragment that identifies nothing. 32 keeps a whole clause. */
|
|
294
|
+
const NAME_CAP = 32
|
|
295
|
+
|
|
296
|
+
/** True when the text can stand on its own as a label in a picker. */
|
|
297
|
+
function nameWorthShowing(text) {
|
|
298
|
+
const value = str(text, '').replace(/\s+/g, ' ').trim()
|
|
299
|
+
if (value === '') return false
|
|
300
|
+
if (value.replace(/[^\p{L}\p{N}]/gu, '').length < 2) return false
|
|
301
|
+
for (const pattern of NAME_NOISE) {
|
|
302
|
+
if (pattern.test(value)) return false
|
|
303
|
+
}
|
|
304
|
+
return true
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
function shortenName(text) {
|
|
308
|
+
const value = str(text, '').replace(/\s+/g, ' ').trim()
|
|
309
|
+
if (value.length <= NAME_CAP) return value
|
|
310
|
+
return value.slice(0, NAME_CAP - 1) + '…'
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
function nameCandidate(text) {
|
|
314
|
+
return nameWorthShowing(text) ? shortenName(text) : ''
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** A human-readable name for one Session.
|
|
318
|
+
*
|
|
319
|
+
* The picker is how the operator chooses which conversation takes over, so a
|
|
320
|
+
* row reading `会话 f4ccf574` asks them to recognise a conversation by eight
|
|
321
|
+
* random hex characters. Three sources, strongest first:
|
|
322
|
+
*
|
|
323
|
+
* 1. The Session's own title. The operator can rename a conversation, and the
|
|
324
|
+
* title service also derives one from the first prompt — that name is what
|
|
325
|
+
* the conversation is called everywhere else in the UI, and it survives a
|
|
326
|
+
* conversation that never wrote a single board row.
|
|
327
|
+
* 2. The board this Session left: a stated objective, the newest memory
|
|
328
|
+
* headline, the newest open task, the newest note. Only reached when no
|
|
329
|
+
* title exists (a Session created before the operator named it).
|
|
330
|
+
* 3. The Session header: the leaf of its working directory, then the date it
|
|
331
|
+
* started. Enough to tell two unnamed conversations apart.
|
|
332
|
+
*
|
|
333
|
+
* Every source passes the same quality gate, so a `[PASS]` log line or an
|
|
334
|
+
* injected `[Handoff · part 2]` template is skipped instead of becoming a
|
|
335
|
+
* label. Returns '' when nothing usable is found; callers then fall back to
|
|
336
|
+
* the short id, which is at least honest about being an id. */
|
|
337
|
+
function sessionName(runtime, agentOrId) {
|
|
338
|
+
const agent = agentOrId && typeof agentOrId === 'object' ? agentOrId : undefined
|
|
339
|
+
const id = str(agent && agent.id, '') || str(agentOrId, '')
|
|
340
|
+
if (!id) return ''
|
|
341
|
+
const session = agent && agent.session
|
|
342
|
+
? agent.session
|
|
343
|
+
: safe(() => sessionOf(runtime, id), undefined)
|
|
344
|
+
|
|
345
|
+
// Operator-chosen (or derived) title: the only name that exists for a
|
|
346
|
+
// conversation which never touched its board.
|
|
347
|
+
const snap = session
|
|
348
|
+
? safe(() => {
|
|
349
|
+
const titles = runtime.get('sessionTitle')
|
|
350
|
+
return titles && typeof titles.get === 'function' ? titles.get(session) : undefined
|
|
351
|
+
}, undefined)
|
|
352
|
+
: undefined
|
|
353
|
+
const titled = nameCandidate(snap && snap.title)
|
|
354
|
+
if (titled !== '') return titled
|
|
355
|
+
|
|
356
|
+
let board
|
|
357
|
+
try {
|
|
358
|
+
board = loadBoard(boardFileFor(id))
|
|
359
|
+
} catch {
|
|
360
|
+
board = undefined
|
|
361
|
+
}
|
|
362
|
+
if (board) {
|
|
363
|
+
const stated = nameCandidate(board.objective)
|
|
364
|
+
if (stated !== '') return stated
|
|
365
|
+
const memory = Array.isArray(board.memory) ? board.memory : []
|
|
366
|
+
for (let i = memory.length - 1; i >= 0; i -= 1) {
|
|
367
|
+
const fromMemory = nameCandidate(memory[i] && memory[i].title)
|
|
368
|
+
if (fromMemory !== '') return fromMemory
|
|
369
|
+
}
|
|
370
|
+
const tasks = Array.isArray(board.tasks) ? board.tasks : []
|
|
371
|
+
for (const task of tasks) {
|
|
372
|
+
if (!task || task.status === 'done') continue
|
|
373
|
+
const fromTask = nameCandidate(task.title)
|
|
374
|
+
if (fromTask !== '') return fromTask
|
|
375
|
+
}
|
|
376
|
+
const notes = Array.isArray(board.notes) ? board.notes : []
|
|
377
|
+
for (const note of notes) {
|
|
378
|
+
const fromNote = nameCandidate(note && note.title)
|
|
379
|
+
if (fromNote !== '') return fromNote
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
// Header: a working directory names the work; a start date at least orders it.
|
|
384
|
+
const header = session && session.header ? session.header : undefined
|
|
385
|
+
const cwd = str(header && header.cwd, '').trim()
|
|
386
|
+
if (cwd !== '') {
|
|
387
|
+
const leaf = safe(() => path.basename(cwd), '')
|
|
388
|
+
const fromCwd = nameCandidate(leaf)
|
|
389
|
+
if (fromCwd !== '') return fromCwd
|
|
390
|
+
}
|
|
391
|
+
const createdAt = Number(header && header.createdAt)
|
|
392
|
+
if (Number.isFinite(createdAt) && createdAt > 0) return dateStamp(createdAt)
|
|
393
|
+
return ''
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/** `M/D` for a Session that has nothing else to go on. */
|
|
397
|
+
function dateStamp(at) {
|
|
398
|
+
const date = new Date(at)
|
|
399
|
+
if (Number.isNaN(date.getTime())) return ''
|
|
400
|
+
return (date.getMonth() + 1) + '/' + date.getDate()
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/** When each Session was last written to disk, read from its own transcript.
|
|
404
|
+
*
|
|
405
|
+
* The board's heartbeat table only knows Sessions that wrote a board row, so
|
|
406
|
+
* an untouched conversation shows 0 turns and no time — exactly the row that
|
|
407
|
+
* most needs a timestamp. The transcript file is touched on every event, so
|
|
408
|
+
* its mtime answers "when was this conversation last alive" without parsing
|
|
409
|
+
* a single compressed frame. One directory pass per request; a Session with
|
|
410
|
+
* no transcript is simply absent from the map. */
|
|
411
|
+
function transcriptTimes() {
|
|
412
|
+
const home = process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
|
|
413
|
+
const root = path.join(home, 'sessions')
|
|
414
|
+
const found = new Map()
|
|
415
|
+
const buckets = safe(() => fs.readdirSync(root), [])
|
|
416
|
+
for (const bucket of buckets) {
|
|
417
|
+
const dir = path.join(root, bucket)
|
|
418
|
+
const names = safe(() => fs.readdirSync(dir), [])
|
|
419
|
+
for (const name of names) {
|
|
420
|
+
const file = path.join(dir, name, 'session.v4.jsonl.zstd')
|
|
421
|
+
let at = 0
|
|
422
|
+
try {
|
|
423
|
+
at = fs.statSync(file).mtimeMs
|
|
424
|
+
} catch {
|
|
425
|
+
continue
|
|
426
|
+
}
|
|
427
|
+
const key = name.indexOf('session-') === 0 ? name : 'session-' + name
|
|
428
|
+
const previous = found.get(key) || 0
|
|
429
|
+
// mtimeMs is a float; every other timestamp on this wire is an integer
|
|
430
|
+
// millisecond stamp, so round rather than leak a fraction into readers
|
|
431
|
+
// that compare with === or format with String().
|
|
432
|
+
const stamp = Math.round(at)
|
|
433
|
+
if (stamp > previous) found.set(key, stamp)
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
return found
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
/** Normalize a candidate subagent name to DSH's rules: [a-z][a-z0-9-]{0,31}, never 'lead'. */
|
|
440
|
+
function sanitizeSubagentName(raw, fallbackSuffix) {
|
|
441
|
+
let clean = String(raw || '')
|
|
442
|
+
.trim()
|
|
443
|
+
.split('/')
|
|
444
|
+
.pop()
|
|
445
|
+
.toLowerCase()
|
|
446
|
+
.replace(/[^a-z0-9-]+/g, '-')
|
|
447
|
+
.replace(/^-+|-+$/g, '')
|
|
448
|
+
if (!clean || clean === 'lead' || clean === 'agent' || clean === 'operator' || clean === 'user' || clean === 'human') {
|
|
449
|
+
clean = 'worker-' + String(fallbackSuffix || newId('w')).toLowerCase().replace(/[^a-z0-9]/g, '').slice(0, 10)
|
|
450
|
+
}
|
|
451
|
+
if (!/^[a-z]/.test(clean)) clean = 'w-' + clean
|
|
452
|
+
return clean.slice(0, 32).replace(/-+$/g, '') || 'worker-1'
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/** Build a self-contained task brief with objective, upstream evidence, and write-back instructions. */
|
|
456
|
+
function buildTaskDispatchBrief(board, task, extraPrompt) {
|
|
457
|
+
const byId = new Map((board.tasks || []).map(t => [t.id, t]))
|
|
458
|
+
const lines = [
|
|
459
|
+
'# 任务委派简报 (dsh-chief Task Dispatch)',
|
|
460
|
+
'',
|
|
461
|
+
'你正在参与主代理(`lead`)统筹的协作任务图。请独立完成以下节点并将结果与证据回写到共享看板:',
|
|
462
|
+
'',
|
|
463
|
+
'- **任务 ID**: `' + task.id + '`',
|
|
464
|
+
'- **任务标题**: ' + task.title,
|
|
465
|
+
]
|
|
466
|
+
if (board.objective) lines.push('- **全局目标**: ' + board.objective.slice(0, 400))
|
|
467
|
+
if (task.intent) lines.push('- **任务意图 (Intent)**: ' + task.intent)
|
|
468
|
+
if (task.evidence) lines.push('- **验收标准 (Expected Evidence)**: ' + task.evidence)
|
|
469
|
+
if (task.note) lines.push('- **补充说明 (Note)**: ' + task.note)
|
|
470
|
+
|
|
471
|
+
if (task.parentId && byId.has(task.parentId)) {
|
|
472
|
+
const parent = byId.get(task.parentId)
|
|
473
|
+
lines.push('- **所属父任务**: #' + parent.id + ' ' + parent.title)
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
const deps = (Array.isArray(task.blockedBy) ? task.blockedBy : []).map(id => byId.get(id)).filter(Boolean)
|
|
477
|
+
if (deps.length) {
|
|
478
|
+
lines.push('', '## 上游前置任务产出')
|
|
479
|
+
for (const dep of deps) {
|
|
480
|
+
lines.push('- **#' + dep.id + ' ' + dep.title + '** [' + dep.status + ']' + (dep.evidence ? ' — 证据/结论: ' + dep.evidence : ''))
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
const forbidden = board.bounds && Array.isArray(board.bounds.forbidden) ? board.bounds.forbidden : []
|
|
485
|
+
if (forbidden.length) {
|
|
486
|
+
lines.push('', '## 严禁触碰红线 (Forbidden Bounds)')
|
|
487
|
+
for (const item of forbidden.slice(0, 8)) lines.push('- ⛔ ' + item)
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
if (extraPrompt && String(extraPrompt).trim()) {
|
|
491
|
+
lines.push('', '## 额外执行指令', String(extraPrompt).trim())
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
lines.push(
|
|
495
|
+
'',
|
|
496
|
+
'## 完工回写与跨对话协同要求',
|
|
497
|
+
'1. 完成工作并验证后,**必须**调用 `chief_board` 工具回写参谋看板任务状态与证据:',
|
|
498
|
+
' `chief_board({ action: "task.update", id: "' + task.id + '", status: "done", evidence: "写明实测结果、修改的文件或关键结论" })`',
|
|
499
|
+
'2. 若遇到无法绕过的阻塞,调用 `chief_board({ action: "task.update", id: "' + task.id + '", status: "blocked", note: "写明阻塞原因" })`。',
|
|
500
|
+
'3. 如需与主对话 (`lead`)、其他兄弟子代理或跨窗口协同会话直接递话/同步结论,调用:',
|
|
501
|
+
' `chief_board({ action: "mail.send", target: "lead 或子代理名", text: "要同步的关键信息" })`。',
|
|
502
|
+
)
|
|
503
|
+
return lines.join('\n')
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
function isInternalProfileCwd(dirPath) {
|
|
507
|
+
return /[\\/]\.dsh[\\/]+profiles(?:$|[\\/])/i.test(String(dirPath || '').trim())
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
function listWorkspaceRows(runtime) {
|
|
511
|
+
const rt = runtime || deps.hostState.activeRuntime
|
|
512
|
+
if (!rt) return []
|
|
513
|
+
try {
|
|
514
|
+
const reg = rt.get('workspaceRegistry')
|
|
515
|
+
const rawList = reg && typeof reg.list === 'function' ? reg.list() : []
|
|
516
|
+
return Array.isArray(rawList)
|
|
517
|
+
? rawList
|
|
518
|
+
: (Array.isArray(rawList && rawList.workspaces) ? rawList.workspaces : (Array.isArray(rawList && rawList.items) ? rawList.items : []))
|
|
519
|
+
} catch {
|
|
520
|
+
return []
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
function resolveWorkspaceIdForSession(runtime, sessionId) {
|
|
525
|
+
const sid = String(sessionId || '').trim()
|
|
526
|
+
const rootId = sid ? (resolveRootSessionId(sid) || sid) : ''
|
|
527
|
+
const rows = listWorkspaceRows(runtime)
|
|
528
|
+
if (!rows.length) return ''
|
|
529
|
+
const bySid = rows.find((w) => {
|
|
530
|
+
if (!w) return false
|
|
531
|
+
const sids = Array.isArray(w.sessionIds) ? w.sessionIds : []
|
|
532
|
+
return (sid && sids.includes(sid)) || (rootId && sids.includes(rootId))
|
|
533
|
+
})
|
|
534
|
+
if (bySid && (bySid.workspaceId || bySid.id)) {
|
|
535
|
+
return String(bySid.workspaceId || bySid.id).trim()
|
|
536
|
+
}
|
|
537
|
+
const cwd = getSessionCwd(runtime, sid || rootId)
|
|
538
|
+
if (cwd && !isInternalProfileCwd(cwd)) {
|
|
539
|
+
const normCwd = process.platform === 'win32' ? path.resolve(cwd).toLowerCase() : path.resolve(cwd)
|
|
540
|
+
const byPath = rows.find((w) => {
|
|
541
|
+
if (!w || typeof w.path !== 'string' || !w.path.trim()) return false
|
|
542
|
+
const wNorm = process.platform === 'win32' ? path.resolve(w.path).toLowerCase() : path.resolve(w.path)
|
|
543
|
+
return wNorm === normCwd
|
|
544
|
+
})
|
|
545
|
+
if (byPath && (byPath.workspaceId || byPath.id)) {
|
|
546
|
+
return String(byPath.workspaceId || byPath.id).trim()
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
return ''
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
function getSessionCwd(runtime, sessionId) {
|
|
553
|
+
const sid = String(sessionId || '').trim()
|
|
554
|
+
const rootId = sid ? (resolveRootSessionId(sid) || sid) : ''
|
|
555
|
+
const rt = runtime || deps.hostState.activeRuntime
|
|
556
|
+
if (rt) {
|
|
557
|
+
try {
|
|
558
|
+
const agents = rt.get('agents')
|
|
559
|
+
const agent = (agents && typeof agents.get === 'function') ? (agents.get(sid) || agents.get(rootId)) : null
|
|
560
|
+
const headerCwd = agent && agent.session && agent.session.header && agent.session.header.cwd
|
|
561
|
+
if (typeof headerCwd === 'string' && headerCwd.trim()) return headerCwd.trim()
|
|
562
|
+
const sessionObj = agent && agent.session ? agent.session : safe(() => sessionOf(rt, sid || rootId), null)
|
|
563
|
+
const wd = rt.get('workingDirectory')
|
|
564
|
+
if (wd && typeof wd.get === 'function' && sessionObj) {
|
|
565
|
+
const wDir = wd.get(sessionObj)
|
|
566
|
+
if (typeof wDir === 'string' && wDir.trim()) return wDir.trim()
|
|
567
|
+
}
|
|
568
|
+
} catch {}
|
|
569
|
+
}
|
|
570
|
+
for (const probeId of [sid, rootId].filter(Boolean)) {
|
|
571
|
+
try {
|
|
572
|
+
const b = loadBoard(boardFileFor(probeId))
|
|
573
|
+
const row = b && b.sessions && (b.sessions[probeId] || b.sessions[sid])
|
|
574
|
+
if (row && typeof row.cwd === 'string' && row.cwd.trim() && !isInternalProfileCwd(row.cwd)) {
|
|
575
|
+
return row.cwd.trim()
|
|
576
|
+
}
|
|
577
|
+
} catch {}
|
|
578
|
+
}
|
|
579
|
+
{
|
|
580
|
+
const rows = listWorkspaceRows(rt)
|
|
581
|
+
if (rows.length) {
|
|
582
|
+
const matched = rows.find((w) => {
|
|
583
|
+
if (!w || typeof w.path !== 'string' || !w.path.trim()) return false
|
|
584
|
+
const sids = Array.isArray(w.sessionIds) ? w.sessionIds : []
|
|
585
|
+
return (sid && sids.includes(sid)) || (rootId && sids.includes(rootId))
|
|
586
|
+
})
|
|
587
|
+
if (matched) return matched.path.trim()
|
|
588
|
+
const sorted = rows
|
|
589
|
+
.filter(w => w && typeof w.path === 'string' && w.path.trim() && !isInternalProfileCwd(w.path))
|
|
590
|
+
.slice()
|
|
591
|
+
.sort((a, b) => Number(b.updatedAt || b.createdAt || 0) - Number(a.updatedAt || a.createdAt || 0))
|
|
592
|
+
if (sorted[0]) return sorted[0].path.trim()
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
try {
|
|
596
|
+
const boardsDir = path.join(path.dirname(boardFile()), 'boards')
|
|
597
|
+
if (fs.existsSync(boardsDir)) {
|
|
598
|
+
const recentFiles = fs.readdirSync(boardsDir)
|
|
599
|
+
.filter(name => name.endsWith('.json'))
|
|
600
|
+
.map((name) => {
|
|
601
|
+
const full = path.join(boardsDir, name)
|
|
602
|
+
return { full, mtimeMs: safe(() => fs.statSync(full).mtimeMs, 0) }
|
|
603
|
+
})
|
|
604
|
+
.sort((a, b) => b.mtimeMs - a.mtimeMs)
|
|
605
|
+
.slice(0, 15)
|
|
606
|
+
for (const f of recentFiles) {
|
|
607
|
+
const b = safe(() => loadBoard(f.full), null)
|
|
608
|
+
const sessMap = b && b.sessions && typeof b.sessions === 'object' ? Object.values(b.sessions) : []
|
|
609
|
+
for (const row of sessMap) {
|
|
610
|
+
if (row && typeof row.cwd === 'string' && row.cwd.trim() && !isInternalProfileCwd(row.cwd)) {
|
|
611
|
+
return row.cwd.trim()
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
} catch {}
|
|
617
|
+
return process.cwd()
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
function getSessionContextBreakdown(runtime, sessionId, agentArg = null) {
|
|
621
|
+
const rt = runtime || deps.hostState.activeRuntime
|
|
622
|
+
const sid = String(sessionId || (agentArg && agentArg.id) || '').trim()
|
|
623
|
+
const rootSid = sid ? (resolveRootSessionId(sid, agentArg) || sid) : ''
|
|
624
|
+
const agents = rt ? rt.get('agents') : null
|
|
625
|
+
const ag = agentArg
|
|
626
|
+
|| (sid && agents && typeof agents.get === 'function' ? agents.get(sid) : null)
|
|
627
|
+
|| (rootSid && agents && typeof agents.get === 'function' ? agents.get(rootSid) : null)
|
|
628
|
+
|
|
629
|
+
let contextWindow = 128_000
|
|
630
|
+
let totalTokens = 0
|
|
631
|
+
let seq = 0
|
|
632
|
+
let systemTokens = 0
|
|
633
|
+
let toolsTokens = 0
|
|
634
|
+
let messageTokens = 0
|
|
635
|
+
let modelRef = ''
|
|
636
|
+
let source = 'estimate'
|
|
637
|
+
|
|
638
|
+
try {
|
|
639
|
+
const projectionsSvc = rt ? rt.get('sessionProjections') : null
|
|
640
|
+
if (ag && ag.session && projectionsSvc && typeof projectionsSvc.snapshot === 'function') {
|
|
641
|
+
const snap = projectionsSvc.snapshot(ag.session, ['contextPressure', 'contextBreakdown', 'contextTimeline'])
|
|
642
|
+
const values = (snap && snap.values) || {}
|
|
643
|
+
const bd = values.contextBreakdown
|
|
644
|
+
const pressure = values.contextPressure
|
|
645
|
+
const timeline = values.contextTimeline
|
|
646
|
+
if (bd && typeof bd === 'object') {
|
|
647
|
+
if (Number(bd.systemTokens) >= 0) systemTokens = Math.round(Number(bd.systemTokens))
|
|
648
|
+
if (Number(bd.toolsTokens) >= 0) toolsTokens = Math.round(Number(bd.toolsTokens))
|
|
649
|
+
if (Number(bd.messageTokens) >= 0) messageTokens = Math.round(Number(bd.messageTokens))
|
|
650
|
+
if (Number(bd.contextWindow) > 0) contextWindow = Math.round(Number(bd.contextWindow))
|
|
651
|
+
const bdTotal = Number(bd.totalTokens) || (systemTokens + toolsTokens + messageTokens)
|
|
652
|
+
if (bdTotal > 0) {
|
|
653
|
+
totalTokens = Math.round(bdTotal)
|
|
654
|
+
source = 'projection'
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
if (pressure && typeof pressure === 'object') {
|
|
658
|
+
if (Number(pressure.contextWindow) > 0) contextWindow = Math.round(Number(pressure.contextWindow))
|
|
659
|
+
const pTok = Number(pressure.projectedTokens) || Number(pressure.pressureTokens) || 0
|
|
660
|
+
if (pTok > totalTokens) {
|
|
661
|
+
totalTokens = Math.round(pTok)
|
|
662
|
+
source = 'projection'
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
if (timeline && timeline.current && typeof timeline.current === 'object') {
|
|
666
|
+
const cur = timeline.current
|
|
667
|
+
if (!systemTokens && Number(cur.system) > 0) systemTokens = Math.round(Number(cur.system))
|
|
668
|
+
if (!toolsTokens && Number(cur.tools) > 0) toolsTokens = Math.round(Number(cur.tools))
|
|
669
|
+
if (!totalTokens && Number(cur.total) > 0) totalTokens = Math.round(Number(cur.total))
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
} catch {}
|
|
673
|
+
|
|
674
|
+
let provider = ''
|
|
675
|
+
let model = ''
|
|
676
|
+
try {
|
|
677
|
+
if (ag && ag.session && typeof ag.session.ownEvents === 'function') {
|
|
678
|
+
const events = ag.session.ownEvents() || []
|
|
679
|
+
seq = events.length
|
|
680
|
+
for (let i = events.length - 1; i >= 0; i -= 1) {
|
|
681
|
+
const ev = events[i]
|
|
682
|
+
if (!ev) continue
|
|
683
|
+
if (!provider && ev.type === 'request/header' && ev.data && ev.data.header && ev.data.header.config) {
|
|
684
|
+
provider = String(ev.data.header.config.provider || '')
|
|
685
|
+
model = String(ev.data.header.config.model || '')
|
|
686
|
+
}
|
|
687
|
+
const usage = ev.usage || (ev.message && ev.message.usage) || (ev.data && ev.data.usage)
|
|
688
|
+
if (!totalTokens && usage && typeof usage === 'object') {
|
|
689
|
+
const calc = (Number(usage.inputTokens) || 0)
|
|
690
|
+
+ (Number(usage.cacheReadTokens) || 0)
|
|
691
|
+
+ (Number(usage.outputTokens) || 0)
|
|
692
|
+
const uTotal = Number(usage.totalTokens) || calc
|
|
693
|
+
if (uTotal > 0) {
|
|
694
|
+
totalTokens = Math.round(uTotal)
|
|
695
|
+
if (source === 'estimate') source = 'usage'
|
|
696
|
+
}
|
|
697
|
+
if (Number(usage.contextWindow) > 0) contextWindow = Math.round(Number(usage.contextWindow))
|
|
698
|
+
if (!systemTokens && Number(usage.systemTokens) > 0) systemTokens = Math.round(Number(usage.systemTokens))
|
|
699
|
+
if (!toolsTokens && Number(usage.toolsTokens) > 0) toolsTokens = Math.round(Number(usage.toolsTokens))
|
|
700
|
+
}
|
|
701
|
+
if (provider && model && totalTokens > 0) break
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
} catch {}
|
|
705
|
+
|
|
706
|
+
try {
|
|
707
|
+
const llm = deps.hostState.activeLlm || (rt ? rt.get('llm') : null)
|
|
708
|
+
if (!provider && ag && ag.session && typeof ag.session.requestHeader === 'function') {
|
|
709
|
+
const h = ag.session.requestHeader()
|
|
710
|
+
if (h && h.config) {
|
|
711
|
+
provider = String(h.config.provider || '')
|
|
712
|
+
model = String(h.config.model || '')
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
if (provider && model) {
|
|
716
|
+
modelRef = `${provider}/${model}`
|
|
717
|
+
const winCache = (deps.hostState.modelWindowCache = deps.hostState.modelWindowCache || new Map())
|
|
718
|
+
const cachedWin = winCache.get(modelRef)
|
|
719
|
+
if (cachedWin > 0 && contextWindow <= 128_000) {
|
|
720
|
+
contextWindow = cachedWin
|
|
721
|
+
}
|
|
722
|
+
// Historical sessions may reference providers that no longer have an adapter.
|
|
723
|
+
// Never let context-window lookup take down the host process.
|
|
724
|
+
if (llm && typeof llm.resolveModelInfo === 'function' && provider !== 'opendesign') {
|
|
725
|
+
try {
|
|
726
|
+
const infoOrPromise = llm.resolveModelInfo(provider, model)
|
|
727
|
+
if (infoOrPromise && typeof infoOrPromise.then === 'function') {
|
|
728
|
+
infoOrPromise.then((resolved) => {
|
|
729
|
+
if (resolved && Number(resolved.contextWindow) > 0) {
|
|
730
|
+
winCache.set(modelRef, Math.round(Number(resolved.contextWindow)))
|
|
731
|
+
}
|
|
732
|
+
}).catch(() => {})
|
|
733
|
+
} else if (infoOrPromise && Number(infoOrPromise.contextWindow) > 0) {
|
|
734
|
+
const cw = Math.round(Number(infoOrPromise.contextWindow))
|
|
735
|
+
winCache.set(modelRef, cw)
|
|
736
|
+
contextWindow = cw
|
|
737
|
+
}
|
|
738
|
+
} catch {}
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
} catch {}
|
|
742
|
+
|
|
743
|
+
// Fallback rough split only when official projection breakdown isn't populated yet
|
|
744
|
+
if (totalTokens > 0 && systemTokens === 0 && toolsTokens === 0 && messageTokens === 0) {
|
|
745
|
+
systemTokens = Math.min(totalTokens, Math.round(Math.min(52_000, Math.max(12_000, contextWindow * 0.04))))
|
|
746
|
+
toolsTokens = Math.min(Math.max(0, totalTokens - systemTokens), 1500)
|
|
747
|
+
messageTokens = Math.max(0, totalTokens - systemTokens - toolsTokens)
|
|
748
|
+
} else if (totalTokens > 0 && messageTokens === 0) {
|
|
749
|
+
messageTokens = Math.max(0, totalTokens - systemTokens - toolsTokens)
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
const overheadTokens = systemTokens + toolsTokens
|
|
753
|
+
const usedTokens = Math.max(totalTokens, overheadTokens + messageTokens)
|
|
754
|
+
const otherTokens = Math.max(0, usedTokens - overheadTokens - messageTokens)
|
|
755
|
+
const pct = contextWindow > 0 ? Math.min(100, Math.round((usedTokens / contextWindow) * 100)) : 0
|
|
756
|
+
|
|
757
|
+
return {
|
|
758
|
+
totalTokens: usedTokens,
|
|
759
|
+
usedTokens,
|
|
760
|
+
contextWindow,
|
|
761
|
+
pct,
|
|
762
|
+
systemTokens,
|
|
763
|
+
toolsTokens,
|
|
764
|
+
messageTokens,
|
|
765
|
+
otherTokens,
|
|
766
|
+
overheadTokens,
|
|
767
|
+
modelRef,
|
|
768
|
+
seq,
|
|
769
|
+
source,
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
function linkedPeersForSession(runtime, rootId) {
|
|
774
|
+
if (!rootId) return { linkedPeersCount: 0, linkedPeersProgress: [] }
|
|
775
|
+
const state = loadChiefState()
|
|
776
|
+
const cluster = getLinkedCluster(state, rootId)
|
|
777
|
+
if (!Array.isArray(cluster) || cluster.length <= 1) {
|
|
778
|
+
return { linkedPeersCount: 0, linkedPeersProgress: [] }
|
|
779
|
+
}
|
|
780
|
+
const linkedPeersProgress = collectClusterPeerProgress(makeChiefDeps(runtime), cluster, rootId)
|
|
781
|
+
return {
|
|
782
|
+
linkedPeersCount: Math.max(0, cluster.length - 1),
|
|
783
|
+
linkedPeersProgress,
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
/**
|
|
788
|
+
* Execute host session compaction across Cordis service isolation:
|
|
789
|
+
* 1. Resolve live or archived session agent (`agents.get` -> `sessionController.resolveAgent`).
|
|
790
|
+
* 2. Refuse compaction while the agent is actively running.
|
|
791
|
+
* 3. Prefer unisolated/direct `compaction.compactNow` if present; otherwise invoke
|
|
792
|
+
* `commands.execute(ag, '/compact', [], signal)` which crosses into `@deepseek-ai/dsh-command-compact`.
|
|
793
|
+
*/
|
|
794
|
+
async function executeHostSessionCompaction(rt, sid, cmdId) {
|
|
795
|
+
const targetSid = String(sid || '').trim()
|
|
796
|
+
if (!targetSid) throw new Error('missing target session id for compaction')
|
|
797
|
+
const agents = rt && typeof rt.get === 'function' ? rt.get('agents') : null
|
|
798
|
+
let ag = agents && typeof agents.get === 'function' ? agents.get(targetSid) : null
|
|
799
|
+
if (!ag) {
|
|
800
|
+
const ctrl = rt && typeof rt.get === 'function' ? rt.get('sessionController') : null
|
|
801
|
+
if (ctrl && typeof ctrl.resolveAgent === 'function') {
|
|
802
|
+
try {
|
|
803
|
+
const resolved = await ctrl.resolveAgent(targetSid)
|
|
804
|
+
if (resolved && resolved.agent) ag = resolved.agent
|
|
805
|
+
} catch {}
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
if (!ag) throw new Error('target session agent not found for compaction')
|
|
809
|
+
if (ag.status === 'running') throw new Error('agent is busy running; refusing compaction')
|
|
810
|
+
|
|
811
|
+
const signal = AbortSignal.timeout(60_000)
|
|
812
|
+
const effectiveCmdId = cmdId || ('chief-compact-' + Date.now().toString(36))
|
|
813
|
+
|
|
814
|
+
const compSvc = rt && typeof rt.get === 'function' ? rt.get('compaction') : null
|
|
815
|
+
if (compSvc && typeof compSvc.compactNow === 'function') {
|
|
816
|
+
const directRes = await compSvc.compactNow(ag, signal, effectiveCmdId)
|
|
817
|
+
if (directRes === null) {
|
|
818
|
+
return { ok: true, noop: true, via: 'compaction.compactNow', commandId: effectiveCmdId, text: 'No compactable history yet.' }
|
|
819
|
+
}
|
|
820
|
+
return directRes && typeof directRes === 'object'
|
|
821
|
+
? { ok: true, noop: false, via: 'compaction.compactNow', ...directRes }
|
|
822
|
+
: { ok: true, noop: false, via: 'compaction.compactNow', result: directRes }
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
const cmdSvc = rt && typeof rt.get === 'function' ? rt.get('commands') : null
|
|
826
|
+
if (cmdSvc && typeof cmdSvc.execute === 'function') {
|
|
827
|
+
const execOut = await cmdSvc.execute(ag, '/compact', [], signal)
|
|
828
|
+
const cmdRes = execOut && execOut.result ? execOut.result : execOut
|
|
829
|
+
if (!cmdRes) {
|
|
830
|
+
throw new Error('dsh-command /compact unavailable in runtime')
|
|
831
|
+
}
|
|
832
|
+
if (cmdRes.kind === 'error') {
|
|
833
|
+
throw new Error(String(cmdRes.text || 'host /compact command failed'))
|
|
834
|
+
}
|
|
835
|
+
const text = String(cmdRes.text || '')
|
|
836
|
+
const noop = /no compactable history/i.test(text)
|
|
837
|
+
return {
|
|
838
|
+
ok: true,
|
|
839
|
+
noop,
|
|
840
|
+
via: 'commands:/compact',
|
|
841
|
+
commandId: (execOut && execOut.commandId) || effectiveCmdId,
|
|
842
|
+
text,
|
|
843
|
+
sourceEventSeq: cmdRes.sourceEventSeq,
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
throw new Error('dsh-compaction and /compact command services unavailable')
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
function makeChiefDeps(runtime) {
|
|
851
|
+
const rt = runtime || deps.hostState.activeRuntime
|
|
852
|
+
return {
|
|
853
|
+
runtime: rt,
|
|
854
|
+
getLlm: () => deps.hostState.activeLlm || (rt ? rt.get('llm') : null),
|
|
855
|
+
getAttachments: () => safe(() => (rt ? rt.get('attachments') : null), null),
|
|
856
|
+
getSessionCwd: (sid) => getSessionCwd(rt, sid),
|
|
857
|
+
getAgentStatus(sid) {
|
|
858
|
+
const agents = rt ? rt.get('agents') : null
|
|
859
|
+
const ag = agents && typeof agents.get === 'function' ? agents.get(sid) : null
|
|
860
|
+
return (ag && ag.status) || 'idle'
|
|
861
|
+
},
|
|
862
|
+
async measureSessionTokens(sid, agentArg) {
|
|
863
|
+
return getSessionContextBreakdown(rt, sid, agentArg)
|
|
864
|
+
},
|
|
865
|
+
composeHandoffFromNarrative(opts) {
|
|
866
|
+
return composeHandoffFromNarrative(opts)
|
|
867
|
+
},
|
|
868
|
+
async compactSessionNow(sid, cmdId) {
|
|
869
|
+
return executeHostSessionCompaction(rt, sid, cmdId)
|
|
870
|
+
},
|
|
871
|
+
stagePendingTransfer(text, fromSid, extra = {}) {
|
|
872
|
+
const cleanText = String(text || '').trim()
|
|
873
|
+
if (!cleanText) return false
|
|
874
|
+
return writePending({
|
|
875
|
+
at: nowMs(),
|
|
876
|
+
by: (extra && extra.by) || 'chief',
|
|
877
|
+
session: fromSid || 'global',
|
|
878
|
+
text: cleanText,
|
|
879
|
+
...(extra && typeof extra === 'object' ? extra : {}),
|
|
880
|
+
})
|
|
881
|
+
},
|
|
882
|
+
resolveRootSessionId,
|
|
883
|
+
resolveAgentIdentity,
|
|
884
|
+
refreshSubagentTree,
|
|
885
|
+
boardForSession,
|
|
886
|
+
boardFileFor,
|
|
887
|
+
sharedBoardFile: boardFile,
|
|
888
|
+
loadBoard,
|
|
889
|
+
sessionName,
|
|
890
|
+
findLiveCallerAgent,
|
|
891
|
+
runAction,
|
|
892
|
+
answerMemory,
|
|
893
|
+
appendBoardLog(rootSessionId, text, by) {
|
|
894
|
+
if (!rootSessionId) return
|
|
895
|
+
const file = boardFileFor(rootSessionId)
|
|
896
|
+
withBoardLock(file, () => {
|
|
897
|
+
const board = loadBoard(file)
|
|
898
|
+
pushLog(board, text, by || 'chief', rootSessionId)
|
|
899
|
+
saveBoard(board, file)
|
|
900
|
+
})
|
|
901
|
+
},
|
|
902
|
+
executeSubagentAction: (input, callerAgent, signal) => executeSubagentAction(rt, input, callerAgent, signal),
|
|
903
|
+
async controlMainAgent({ rootId = '', sessionId = '', op = 'steer', modelRef = '', reasoningEffort = '', message = '', reason = '' } = {}) {
|
|
904
|
+
const targetSid = String(sessionId || rootId || '').trim()
|
|
905
|
+
if (!targetSid || targetSid === 'global') {
|
|
906
|
+
return { ok: false, error: '当前为空白未绑定会话,无法直接控制主对话代理' }
|
|
907
|
+
}
|
|
908
|
+
const ctrl = rt ? rt.get('sessionController') : null
|
|
909
|
+
if (op === 'switch_model') {
|
|
910
|
+
const rawRef = String(modelRef || '').trim()
|
|
911
|
+
if (!rawRef) return { ok: false, error: 'switch_model 需要 modelRef 参数(如 provider/model)' }
|
|
912
|
+
if (!ctrl || typeof ctrl.selectModel !== 'function') {
|
|
913
|
+
return { ok: false, error: '当前宿主未挂载 sessionController.selectModel 接口' }
|
|
914
|
+
}
|
|
915
|
+
const slash = rawRef.indexOf('/')
|
|
916
|
+
let provider = slash > 0 ? rawRef.slice(0, slash).trim() : ''
|
|
917
|
+
const model = slash > 0 ? rawRef.slice(slash + 1).trim() : rawRef
|
|
918
|
+
if (!provider) {
|
|
919
|
+
const curInfo = getSessionContextBreakdown(rt, targetSid)
|
|
920
|
+
const curRef = String((curInfo && curInfo.modelRef) || '')
|
|
921
|
+
if (curRef.includes('/')) provider = curRef.split('/')[0]
|
|
922
|
+
}
|
|
923
|
+
try {
|
|
924
|
+
const selRes = await ctrl.selectModel({
|
|
925
|
+
sessionId: targetSid,
|
|
926
|
+
...(provider ? { provider } : {}),
|
|
927
|
+
model,
|
|
928
|
+
...(reasoningEffort ? { reasoningEffort } : {}),
|
|
929
|
+
})
|
|
930
|
+
return {
|
|
931
|
+
ok: true,
|
|
932
|
+
selected: selRes && selRes.selected ? selRes.selected : { provider, model },
|
|
933
|
+
badge: `🔄 主模型 → ${model}`,
|
|
934
|
+
}
|
|
935
|
+
} catch (err) {
|
|
936
|
+
return { ok: false, error: (err && err.message) || String(err || '切换主模型失败') }
|
|
937
|
+
}
|
|
938
|
+
}
|
|
939
|
+
if (op === 'interrupt') {
|
|
940
|
+
try {
|
|
941
|
+
if (ctrl && typeof ctrl.cancel === 'function') {
|
|
942
|
+
await ctrl.cancel({ sessionId: targetSid })
|
|
943
|
+
return { ok: true, interrupted: true, badge: '⏹ 已中断主对话' }
|
|
944
|
+
}
|
|
945
|
+
const agents = rt ? rt.get('agents') : null
|
|
946
|
+
const ag = agents && typeof agents.get === 'function' ? agents.get(targetSid) : null
|
|
947
|
+
if (ag && typeof ag.interrupt === 'function') {
|
|
948
|
+
await ag.interrupt()
|
|
949
|
+
return { ok: true, interrupted: true, badge: '⏹ 已中断主对话' }
|
|
950
|
+
}
|
|
951
|
+
return { ok: false, error: '当前宿主未提供主对话中断接口' }
|
|
952
|
+
} catch (err) {
|
|
953
|
+
return { ok: false, error: (err && err.message) || String(err || '中断主对话失败') }
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
const textBody = String(message || reason || '').trim()
|
|
957
|
+
if (!textBody) return { ok: false, error: '引导主对话需要 message 指令内容' }
|
|
958
|
+
const deliv = await deliverCrossMessage(makeChiefDeps(rt), {
|
|
959
|
+
fromSession: rootId || targetSid,
|
|
960
|
+
fromLabel: 'DSH 参谋长 (控制主代理)',
|
|
961
|
+
target: 'lead',
|
|
962
|
+
subject: reason || '参谋长主对话工作流调控',
|
|
963
|
+
text: textBody,
|
|
964
|
+
mode: op === 'followup' ? 'followup' : 'steer',
|
|
965
|
+
})
|
|
966
|
+
return {
|
|
967
|
+
...deliv,
|
|
968
|
+
badge: deliv.ok ? `🎯 已${op === 'followup' ? '递话' : '插话'}主代理` : '⚠️ 调控主代理失败',
|
|
969
|
+
}
|
|
970
|
+
},
|
|
971
|
+
async triggerAutoContinueNow(sid, trigger, opts = {}) {
|
|
972
|
+
if (!deps.hostState.activeAutoContinue || typeof deps.hostState.activeAutoContinue.fireNow !== 'function') {
|
|
973
|
+
return { ok: false, error: '断线续跑引擎未挂载' }
|
|
974
|
+
}
|
|
975
|
+
return deps.hostState.activeAutoContinue.fireNow(sid, trigger, { ...(opts || {}), bypassGate: true })
|
|
976
|
+
},
|
|
977
|
+
cancelAutoContinue(sid, reason) {
|
|
978
|
+
return Boolean(
|
|
979
|
+
deps.hostState.activeAutoContinue
|
|
980
|
+
&& typeof deps.hostState.activeAutoContinue.cancelSession === 'function'
|
|
981
|
+
&& sid
|
|
982
|
+
&& deps.hostState.activeAutoContinue.cancelSession(sid, reason || 'chief-halt'),
|
|
983
|
+
)
|
|
984
|
+
},
|
|
985
|
+
}
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
/** Find a live calling or root agent handle for subagent operations. */
|
|
989
|
+
function findLiveCallerAgent(runtime, sessionId, callerAgent) {
|
|
990
|
+
if (callerAgent && callerAgent.id) return callerAgent
|
|
991
|
+
const rt = runtime || deps.hostState.activeRuntime
|
|
992
|
+
if (!rt) return null
|
|
993
|
+
const agents = rt.get('agents')
|
|
994
|
+
if (!agents) return null
|
|
995
|
+
const rootId = resolveRootSessionId(sessionId)
|
|
996
|
+
if (sessionId && typeof agents.get === 'function') {
|
|
997
|
+
const exact = agents.get(sessionId)
|
|
998
|
+
if (exact) return exact
|
|
999
|
+
}
|
|
1000
|
+
if (rootId && typeof agents.get === 'function') {
|
|
1001
|
+
const rootAgent = agents.get(rootId)
|
|
1002
|
+
if (rootAgent) return rootAgent
|
|
1003
|
+
}
|
|
1004
|
+
if (typeof agents.list === 'function') {
|
|
1005
|
+
const all = agents.list()
|
|
1006
|
+
if (Array.isArray(all) && all.length) return all[0]
|
|
1007
|
+
}
|
|
1008
|
+
return null
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
/**
|
|
1012
|
+
* Execute asynchronous subagent team actions (`task.dispatch`, `team.steer`, `team.interrupt`).
|
|
1013
|
+
* Works identically whether invoked from the model's `chief_board` tool or from the Web GUI.
|
|
1014
|
+
*/
|
|
1015
|
+
async function executeSubagentAction(runtime, input, callerAgent, signal) {
|
|
1016
|
+
const rt = runtime || deps.hostState.activeRuntime
|
|
1017
|
+
const args = input && typeof input === 'object' ? input : {}
|
|
1018
|
+
const action = str(args.action, '')
|
|
1019
|
+
const by = str(args.by, callerAgent ? 'agent' : 'operator')
|
|
1020
|
+
const session = str(args.session, callerAgent && callerAgent.id ? String(callerAgent.id) : '')
|
|
1021
|
+
const rootId = resolveRootSessionId(session, callerAgent)
|
|
1022
|
+
const file = boardFileFor(rootId || session)
|
|
1023
|
+
const subagents = rt ? rt.get('subagents') : null
|
|
1024
|
+
const agents = rt ? rt.get('agents') : null
|
|
1025
|
+
const sig = signal || new AbortController().signal
|
|
1026
|
+
|
|
1027
|
+
if (!rootId && !session) {
|
|
1028
|
+
return { ok: false, error: 'no active session bound for subagent operation' }
|
|
1029
|
+
}
|
|
1030
|
+
|
|
1031
|
+
const liveCaller = findLiveCallerAgent(rt, rootId || session, callerAgent)
|
|
1032
|
+
|
|
1033
|
+
if (action === 'task.dispatch') {
|
|
1034
|
+
const taskId = str(args.taskId !== undefined ? args.taskId : args.id, '').trim()
|
|
1035
|
+
if (!taskId) return { ok: false, error: 'task.dispatch requires id (taskId)' }
|
|
1036
|
+
|
|
1037
|
+
const boardSnapshot = loadBoard(file)
|
|
1038
|
+
const targetTask = boardSnapshot.tasks.find(t => t.id === taskId)
|
|
1039
|
+
if (!targetTask) return { ok: false, error: 'no such task: ' + taskId }
|
|
1040
|
+
|
|
1041
|
+
const unresolved = (targetTask.blockedBy || []).filter(depId => {
|
|
1042
|
+
const dep = boardSnapshot.tasks.find(t => t.id === depId)
|
|
1043
|
+
return dep && dep.status !== 'done'
|
|
1044
|
+
})
|
|
1045
|
+
if (unresolved.length && asBool(args.force) !== true) {
|
|
1046
|
+
return { ok: false, error: '任务 #' + taskId + ' 仍有未完成的前置依赖: ' + unresolved.join(', ') + '(完成后将自动解锁,或传 force: true 强制派发)' }
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
const requestedTarget = str(args.agent || args.subagent || args.target || targetTask.subagent || targetTask.owner, '').trim()
|
|
1050
|
+
const brief = buildTaskDispatchBrief(boardSnapshot, targetTask, args.prompt || args.message || args.text)
|
|
1051
|
+
let dispatchedName = requestedTarget
|
|
1052
|
+
let childSessionId = ''
|
|
1053
|
+
let dispatchMode = 'assigned'
|
|
1054
|
+
|
|
1055
|
+
// Case 1: Dispatch to an existing standalone session (session-...)
|
|
1056
|
+
if (requestedTarget.startsWith('session-') && agents && typeof agents.get === 'function') {
|
|
1057
|
+
const targetSessionAgent = agents.get(requestedTarget)
|
|
1058
|
+
if (targetSessionAgent) {
|
|
1059
|
+
const delivered = await injectInto(targetSessionAgent, brief)
|
|
1060
|
+
if (!delivered.ok) return { ok: false, error: '向会话投递失败: ' + delivered.error }
|
|
1061
|
+
childSessionId = requestedTarget
|
|
1062
|
+
dispatchMode = 'session-inject'
|
|
1063
|
+
}
|
|
1064
|
+
} else if (subagents && liveCaller) {
|
|
1065
|
+
// Case 2: Use DSH native subagent service (continue existing subagent or spawn/fork a new one)
|
|
1066
|
+
if (typeof subagents.resolveName !== 'function' || typeof subagents.startActivation !== 'function') {
|
|
1067
|
+
return {
|
|
1068
|
+
ok: false,
|
|
1069
|
+
error: '当前 DSH 宿主不支持命名子代理 API(缺少 subagents.resolveName / startActivation,例如 0.2.2-rc.1 为重构前旧接口),请将 DSH 升级至 >= 0.2.2-rc.2 后再使用子代理派发与插话。',
|
|
1070
|
+
}
|
|
1071
|
+
}
|
|
1072
|
+
const providerName = str(args.provider, targetTask.preset === 'fork' ? 'fork' : 'spawn') || 'spawn'
|
|
1073
|
+
const preset = str(args.preset, targetTask.preset && targetTask.preset !== 'fork' && targetTask.preset !== 'spawn' ? targetTask.preset : '')
|
|
1074
|
+
const candidateName = sanitizeSubagentName(requestedTarget, targetTask.id)
|
|
1075
|
+
|
|
1076
|
+
let existingTargetId = ''
|
|
1077
|
+
if (requestedTarget && requestedTarget !== 'agent' && requestedTarget !== 'operator' && requestedTarget !== 'lead') {
|
|
1078
|
+
try {
|
|
1079
|
+
existingTargetId = await subagents.resolveName(liveCaller, requestedTarget, sig)
|
|
1080
|
+
} catch {
|
|
1081
|
+
try {
|
|
1082
|
+
existingTargetId = await subagents.resolveName(liveCaller, candidateName, sig)
|
|
1083
|
+
} catch {}
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
if (existingTargetId && existingTargetId !== String(liveCaller.id)) {
|
|
1088
|
+
await subagents.sendMessage(liveCaller, existingTargetId, [{ type: 'text', text: brief }], { signal: sig })
|
|
1089
|
+
dispatchedName = requestedTarget || candidateName
|
|
1090
|
+
childSessionId = String(existingTargetId)
|
|
1091
|
+
deps.hostState.subagentRootMap.set(childSessionId, rootId)
|
|
1092
|
+
dispatchMode = 'send_message'
|
|
1093
|
+
} else {
|
|
1094
|
+
let activation
|
|
1095
|
+
try {
|
|
1096
|
+
activation = await subagents.startActivation({
|
|
1097
|
+
provider: providerName,
|
|
1098
|
+
label: targetTask.title.slice(0, 48),
|
|
1099
|
+
name: candidateName,
|
|
1100
|
+
prompt: [{ type: 'text', text: brief }],
|
|
1101
|
+
parent: liveCaller,
|
|
1102
|
+
...(preset ? { agentPreset: preset } : {}),
|
|
1103
|
+
signal: sig,
|
|
1104
|
+
delivery: 'parent',
|
|
1105
|
+
})
|
|
1106
|
+
} catch (spawnErr) {
|
|
1107
|
+
// If name collision occurred, retry with a unique suffix
|
|
1108
|
+
const msg = String(spawnErr && spawnErr.message ? spawnErr.message : spawnErr)
|
|
1109
|
+
if (/already exists|unique|taken|duplicate/i.test(msg)) {
|
|
1110
|
+
const fallbackName = sanitizeSubagentName(candidateName + '-' + Math.random().toString(36).slice(2, 5), targetTask.id)
|
|
1111
|
+
activation = await subagents.startActivation({
|
|
1112
|
+
provider: providerName,
|
|
1113
|
+
label: targetTask.title.slice(0, 48),
|
|
1114
|
+
name: fallbackName,
|
|
1115
|
+
prompt: [{ type: 'text', text: brief }],
|
|
1116
|
+
parent: liveCaller,
|
|
1117
|
+
...(preset ? { agentPreset: preset } : {}),
|
|
1118
|
+
signal: sig,
|
|
1119
|
+
delivery: 'parent',
|
|
1120
|
+
})
|
|
1121
|
+
} else {
|
|
1122
|
+
return { ok: false, error: '启动子代理失败: ' + msg }
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
dispatchedName = String((activation && activation.name) || candidateName)
|
|
1126
|
+
childSessionId = String((activation && activation.childId) || '')
|
|
1127
|
+
if (childSessionId) deps.hostState.subagentRootMap.set(childSessionId, rootId)
|
|
1128
|
+
dispatchMode = 'spawn:' + providerName
|
|
1129
|
+
}
|
|
1130
|
+
} else {
|
|
1131
|
+
dispatchedName = sanitizeSubagentName(requestedTarget, targetTask.id)
|
|
1132
|
+
dispatchMode = 'board-only (no live parent agent active)'
|
|
1133
|
+
}
|
|
1134
|
+
|
|
1135
|
+
const updated = withBoardLock(file, () => {
|
|
1136
|
+
const board = loadBoard(file)
|
|
1137
|
+
const task = board.tasks.find(t => t.id === taskId)
|
|
1138
|
+
if (!task) return { ok: false, error: 'no such task: ' + taskId }
|
|
1139
|
+
task.status = 'doing'
|
|
1140
|
+
task.owner = dispatchedName
|
|
1141
|
+
task.subagent = dispatchedName
|
|
1142
|
+
if (childSessionId) task.session = childSessionId
|
|
1143
|
+
if (args.preset) task.preset = str(args.preset, '').slice(0, 80)
|
|
1144
|
+
task.dispatchedAt = nowMs()
|
|
1145
|
+
task.updatedAt = nowMs()
|
|
1146
|
+
board.cursor = {
|
|
1147
|
+
...(board.cursor || {}),
|
|
1148
|
+
at: nowMs(),
|
|
1149
|
+
step: '已派发 #' + task.id + ' ' + task.title.slice(0, 60) + ' → ' + dispatchedName,
|
|
1150
|
+
expectedTaskId: task.id,
|
|
1151
|
+
by,
|
|
1152
|
+
session: rootId || session,
|
|
1153
|
+
}
|
|
1154
|
+
pushLog(board, '🚀 派发任务 #' + task.id + '「' + task.title.slice(0, 36) + '」→ 子代理 ' + dispatchedName + ' (' + dispatchMode + ')', by, rootId || session)
|
|
1155
|
+
return { ok: true, task, board: saveBoard(board, file) }
|
|
1156
|
+
})
|
|
1157
|
+
if (!updated.ok) return updated
|
|
1158
|
+
const roster = await refreshSubagentTree(rt, rootId || session, updated.board)
|
|
1159
|
+
return {
|
|
1160
|
+
ok: true,
|
|
1161
|
+
dispatched: { taskId, agent: dispatchedName, childSessionId, mode: dispatchMode },
|
|
1162
|
+
task: updated.task,
|
|
1163
|
+
board: updated.board,
|
|
1164
|
+
subagents: roster,
|
|
1165
|
+
}
|
|
1166
|
+
}
|
|
1167
|
+
|
|
1168
|
+
if (action === 'team.steer') {
|
|
1169
|
+
const taskId = str(args.taskId !== undefined ? args.taskId : args.id, '').trim()
|
|
1170
|
+
const boardSnapshot = loadBoard(file)
|
|
1171
|
+
const linkedTask = taskId ? boardSnapshot.tasks.find(t => t.id === taskId) : null
|
|
1172
|
+
const targetName = str(args.agent || args.subagent || args.target || (linkedTask && (linkedTask.subagent || linkedTask.owner)), '').trim()
|
|
1173
|
+
const text = str(args.message || args.prompt || args.text || args.note, '').trim()
|
|
1174
|
+
if (!targetName) return { ok: false, error: 'team.steer requires agent name or task id with assigned subagent' }
|
|
1175
|
+
if (!text) return { ok: false, error: 'team.steer requires message / prompt text' }
|
|
1176
|
+
if (!subagents || !liveCaller) return { ok: false, error: 'subagents service or live caller agent unavailable' }
|
|
1177
|
+
if (typeof subagents.resolveName !== 'function') {
|
|
1178
|
+
return {
|
|
1179
|
+
ok: false,
|
|
1180
|
+
error: '当前 DSH 宿主不支持命名子代理 API(缺少 subagents.resolveName,例如 0.2.2-rc.1 为重构前旧接口),请将 DSH 升级至 >= 0.2.2-rc.2 后再使用子代理派发与插话。',
|
|
1181
|
+
}
|
|
1182
|
+
}
|
|
1183
|
+
|
|
1184
|
+
let targetId = ''
|
|
1185
|
+
try {
|
|
1186
|
+
targetId = await subagents.resolveName(liveCaller, targetName, sig)
|
|
1187
|
+
} catch (err) {
|
|
1188
|
+
return { ok: false, error: '找不到子代理 "' + targetName + '": ' + String(err && err.message ? err.message : err) }
|
|
1189
|
+
}
|
|
1190
|
+
const messageId = await subagents.sendMessage(liveCaller, targetId, [{ type: 'text', text }], { signal: sig })
|
|
1191
|
+
const updated = withBoardLock(file, () => {
|
|
1192
|
+
const board = loadBoard(file)
|
|
1193
|
+
const task = taskId
|
|
1194
|
+
? board.tasks.find(t => t.id === taskId)
|
|
1195
|
+
: board.tasks.find(t => (t.subagent === targetName || t.owner === targetName) && t.status !== 'done')
|
|
1196
|
+
if (task) {
|
|
1197
|
+
task.status = 'doing'
|
|
1198
|
+
task.updatedAt = nowMs()
|
|
1199
|
+
}
|
|
1200
|
+
pushLog(board, '💬 向子代理 ' + targetName + ' 发送引导指令:' + text.slice(0, 60), by, rootId || session)
|
|
1201
|
+
return { ok: true, task, board: saveBoard(board, file) }
|
|
1202
|
+
})
|
|
1203
|
+
const roster = await refreshSubagentTree(rt, rootId || session, updated.board)
|
|
1204
|
+
return { ok: true, messageId, agent: targetName, board: updated.board, subagents: roster }
|
|
1205
|
+
}
|
|
1206
|
+
|
|
1207
|
+
if (action === 'team.interrupt') {
|
|
1208
|
+
const taskId = str(args.taskId !== undefined ? args.taskId : args.id, '').trim()
|
|
1209
|
+
const boardSnapshot = loadBoard(file)
|
|
1210
|
+
const linkedTask = taskId ? boardSnapshot.tasks.find(t => t.id === taskId) : null
|
|
1211
|
+
const targetName = str(args.agent || args.subagent || args.target || (linkedTask && (linkedTask.subagent || linkedTask.owner)), '').trim()
|
|
1212
|
+
if (!targetName) return { ok: false, error: 'team.interrupt requires agent name or task id' }
|
|
1213
|
+
if (!subagents || !liveCaller) return { ok: false, error: 'subagents service or live caller agent unavailable' }
|
|
1214
|
+
if (typeof subagents.resolveName !== 'function') {
|
|
1215
|
+
return {
|
|
1216
|
+
ok: false,
|
|
1217
|
+
error: '当前 DSH 宿主不支持命名子代理 API(缺少 subagents.resolveName,例如 0.2.2-rc.1 为重构前旧接口),请将 DSH 升级至 >= 0.2.2-rc.2 后再使用子代理派发与插话。',
|
|
1218
|
+
}
|
|
1219
|
+
}
|
|
1220
|
+
if (typeof subagents.interrupt !== 'function') {
|
|
1221
|
+
return { ok: false, error: '当前 DSH 宿主不支持 subagents.interrupt,请升级至 >= 0.2.2-rc.2' }
|
|
1222
|
+
}
|
|
1223
|
+
|
|
1224
|
+
let targetId = ''
|
|
1225
|
+
try {
|
|
1226
|
+
targetId = await subagents.resolveName(liveCaller, targetName, sig)
|
|
1227
|
+
} catch (err) {
|
|
1228
|
+
return { ok: false, error: '找不到子代理 "' + targetName + '": ' + String(err && err.message ? err.message : err) }
|
|
1229
|
+
}
|
|
1230
|
+
subagents.interrupt(targetId, { kind: 'ancestor', agent: liveCaller })
|
|
1231
|
+
const updated = withBoardLock(file, () => {
|
|
1232
|
+
const board = loadBoard(file)
|
|
1233
|
+
const task = taskId
|
|
1234
|
+
? board.tasks.find(t => t.id === taskId)
|
|
1235
|
+
: board.tasks.find(t => (t.subagent === targetName || t.owner === targetName) && t.status === 'doing')
|
|
1236
|
+
if (task && asBool(args.keepDoing) !== true) {
|
|
1237
|
+
task.status = 'blocked'
|
|
1238
|
+
task.note = (task.note ? task.note + '\n' : '') + '[已中断子代理 ' + targetName + ']'
|
|
1239
|
+
task.updatedAt = nowMs()
|
|
1240
|
+
}
|
|
1241
|
+
pushLog(board, '⏹ 已请求中断子代理:' + targetName, by, rootId || session)
|
|
1242
|
+
return { ok: true, task, board: saveBoard(board, file) }
|
|
1243
|
+
})
|
|
1244
|
+
const roster = await refreshSubagentTree(rt, rootId || session, updated.board)
|
|
1245
|
+
return { ok: true, interrupted: targetName, board: updated.board, subagents: roster }
|
|
1246
|
+
}
|
|
1247
|
+
|
|
1248
|
+
return { ok: false, error: 'unknown subagent action: ' + action }
|
|
1249
|
+
}
|
|
1250
|
+
|
|
1251
|
+
/**
|
|
1252
|
+
* Mirror native `subagent` / `subagent_fork` / `send_message` / `interrupt_agent`
|
|
1253
|
+
* tool calls into the shared root chief board so the visual DAG always reflects
|
|
1254
|
+
* live subagent delegations even when the model calls native tools directly.
|
|
1255
|
+
*/
|
|
1256
|
+
function syncSubagentToolCall(runtime, exec, result) {
|
|
1257
|
+
try {
|
|
1258
|
+
const caller = exec && exec.agent ? exec.agent : null
|
|
1259
|
+
const sessionId = caller && caller.id ? String(caller.id) : ''
|
|
1260
|
+
if (!sessionId) return
|
|
1261
|
+
const rootId = resolveRootSessionId(sessionId, caller)
|
|
1262
|
+
const file = boardFileFor(rootId || sessionId)
|
|
1263
|
+
const toolName = String((exec && exec.name) || '')
|
|
1264
|
+
const args = exec && typeof exec.arguments === 'object' && exec.arguments
|
|
1265
|
+
? exec.arguments
|
|
1266
|
+
: (typeof exec?.arguments === 'string' ? safe(() => JSON.parse(exec.arguments), {}) : {})
|
|
1267
|
+
|
|
1268
|
+
if (toolName === 'subagent' || toolName === 'subagent_fork') {
|
|
1269
|
+
// Extract started subagent name from presentationMeta, structured value, or rendered text
|
|
1270
|
+
let childName = ''
|
|
1271
|
+
if (result && result.value && typeof result.value.name === 'string') {
|
|
1272
|
+
childName = result.value.name
|
|
1273
|
+
} else if (result && Array.isArray(result.content)) {
|
|
1274
|
+
const txt = result.content.map(c => c && c.text ? c.text : '').join(' ')
|
|
1275
|
+
const m = /started subagent\s+([^\s]+)/i.exec(txt)
|
|
1276
|
+
if (m) childName = m[1]
|
|
1277
|
+
}
|
|
1278
|
+
if (!childName) childName = str(args.name, 'subagent')
|
|
1279
|
+
const shortChild = childName.split('/').pop()
|
|
1280
|
+
const desc = str(args.description, '').trim() || ('子代理任务: ' + childName)
|
|
1281
|
+
const promptText = str(args.prompt, '').trim()
|
|
1282
|
+
const presetVal = str(args.agent_preset, toolName === 'subagent_fork' ? 'fork' : 'spawn')
|
|
1283
|
+
|
|
1284
|
+
withBoardLock(file, () => {
|
|
1285
|
+
const board = loadBoard(file)
|
|
1286
|
+
// Find an existing open task matching this subagent owner or title
|
|
1287
|
+
let task = board.tasks.find(t =>
|
|
1288
|
+
t.status !== 'done' && (
|
|
1289
|
+
t.subagent === childName ||
|
|
1290
|
+
t.owner === childName ||
|
|
1291
|
+
t.subagent === shortChild ||
|
|
1292
|
+
t.owner === shortChild ||
|
|
1293
|
+
(desc && t.title.toLowerCase() === desc.toLowerCase())
|
|
1294
|
+
),
|
|
1295
|
+
)
|
|
1296
|
+
if (task) {
|
|
1297
|
+
task.status = 'doing'
|
|
1298
|
+
task.owner = childName
|
|
1299
|
+
task.subagent = childName
|
|
1300
|
+
task.preset = task.preset || presetVal
|
|
1301
|
+
if (!task.intent && promptText) task.intent = promptText.slice(0, CAP_TASK_INTENT)
|
|
1302
|
+
task.dispatchedAt = nowMs()
|
|
1303
|
+
task.updatedAt = nowMs()
|
|
1304
|
+
} else {
|
|
1305
|
+
const parentId = (board.cursor && board.cursor.expectedTaskId && board.tasks.some(t => t.id === board.cursor.expectedTaskId))
|
|
1306
|
+
? board.cursor.expectedTaskId
|
|
1307
|
+
: ''
|
|
1308
|
+
task = normalizeTask({
|
|
1309
|
+
id: newId('t'),
|
|
1310
|
+
title: desc.slice(0, CAP_TASK_TITLE),
|
|
1311
|
+
note: '',
|
|
1312
|
+
status: 'doing',
|
|
1313
|
+
priority: 'normal',
|
|
1314
|
+
owner: childName,
|
|
1315
|
+
subagent: childName,
|
|
1316
|
+
preset: presetVal,
|
|
1317
|
+
dispatchedAt: nowMs(),
|
|
1318
|
+
session: rootId || sessionId,
|
|
1319
|
+
intent: promptText.slice(0, CAP_TASK_INTENT),
|
|
1320
|
+
evidence: '',
|
|
1321
|
+
blockedBy: [],
|
|
1322
|
+
parentId,
|
|
1323
|
+
createdAt: nowMs(),
|
|
1324
|
+
updatedAt: nowMs(),
|
|
1325
|
+
})
|
|
1326
|
+
board.tasks.push(task)
|
|
1327
|
+
}
|
|
1328
|
+
pushLog(board, '🤖 自动同步子代理委派:' + childName + ' → #' + task.id + '「' + task.title.slice(0, 40) + '」', 'agent', rootId || sessionId)
|
|
1329
|
+
saveBoard(board, file)
|
|
1330
|
+
})
|
|
1331
|
+
refreshSubagentTree(runtime, rootId || sessionId).catch(() => {})
|
|
1332
|
+
} else if (toolName === 'send_message') {
|
|
1333
|
+
const target = str(args.agent, '').trim()
|
|
1334
|
+
const msg = str(args.message, '').trim()
|
|
1335
|
+
if (!target) return
|
|
1336
|
+
withBoardLock(file, () => {
|
|
1337
|
+
const board = loadBoard(file)
|
|
1338
|
+
const task = board.tasks.find(t => (t.subagent === target || t.owner === target) && t.status !== 'done')
|
|
1339
|
+
if (task && task.status !== 'doing') {
|
|
1340
|
+
task.status = 'doing'
|
|
1341
|
+
task.updatedAt = nowMs()
|
|
1342
|
+
}
|
|
1343
|
+
pushLog(board, '💬 消息投递 → ' + target + ':' + msg.slice(0, 50), 'agent', rootId || sessionId)
|
|
1344
|
+
saveBoard(board, file)
|
|
1345
|
+
})
|
|
1346
|
+
} else if (toolName === 'interrupt_agent') {
|
|
1347
|
+
const target = str(args.agent, '').trim()
|
|
1348
|
+
if (!target) return
|
|
1349
|
+
withBoardLock(file, () => {
|
|
1350
|
+
const board = loadBoard(file)
|
|
1351
|
+
pushLog(board, '⏹ 中断子代理:' + target, 'agent', rootId || sessionId)
|
|
1352
|
+
saveBoard(board, file)
|
|
1353
|
+
})
|
|
1354
|
+
}
|
|
1355
|
+
} catch {}
|
|
1356
|
+
}
|
|
1357
|
+
|
|
1358
|
+
/**
|
|
1359
|
+
* Shared fetch for the official Agent Team board. All three renderHandoff call
|
|
1360
|
+
* sites need it, and each one used to inline its own try/catch — drift waiting
|
|
1361
|
+
* to happen. The caller passes whatever agent handle the context exposes
|
|
1362
|
+
* (exec.agent for tools, spCtx.agent for the system prompt, a sessionId string
|
|
1363
|
+
* for the panel API — listTasks only needs a stable id).
|
|
1364
|
+
*/
|
|
1365
|
+
function fetchTeamTasks(runtime, agent) {
|
|
1366
|
+
try {
|
|
1367
|
+
const svc = runtime.get('agentTeams')
|
|
1368
|
+
if (!svc || typeof svc.listTasks !== 'function' || !agent) return undefined
|
|
1369
|
+
return svc.listTasks(agent) || undefined
|
|
1370
|
+
} catch { return undefined }
|
|
1371
|
+
}
|
|
1372
|
+
|
|
1373
|
+
return {
|
|
1374
|
+
resolveRootSessionId,
|
|
1375
|
+
resolveAgentIdentity,
|
|
1376
|
+
refreshSubagentTree,
|
|
1377
|
+
getSubagentRoster,
|
|
1378
|
+
probeSubagentSupport,
|
|
1379
|
+
agentOf,
|
|
1380
|
+
sessionOf,
|
|
1381
|
+
sessionName,
|
|
1382
|
+
dateStamp,
|
|
1383
|
+
transcriptTimes,
|
|
1384
|
+
sanitizeSubagentName,
|
|
1385
|
+
buildTaskDispatchBrief,
|
|
1386
|
+
isInternalProfileCwd,
|
|
1387
|
+
listWorkspaceRows,
|
|
1388
|
+
resolveWorkspaceIdForSession,
|
|
1389
|
+
getSessionCwd,
|
|
1390
|
+
getSessionContextBreakdown,
|
|
1391
|
+
linkedPeersForSession,
|
|
1392
|
+
executeHostSessionCompaction,
|
|
1393
|
+
makeChiefDeps,
|
|
1394
|
+
findLiveCallerAgent,
|
|
1395
|
+
executeSubagentAction,
|
|
1396
|
+
syncSubagentToolCall,
|
|
1397
|
+
fetchTeamTasks,
|
|
1398
|
+
}
|
|
1399
|
+
}
|