dsh-collab-pair 0.0.0-stage → 1.0.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/LICENSE +21 -0
- package/README.md +123 -2
- package/client.js +481 -0
- package/cordis.patch.yml +11 -0
- package/icon.svg +24 -0
- package/index.js +1612 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +46 -4
package/index.js
ADDED
|
@@ -0,0 +1,1612 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Collaboration pair: link one project-manager conversation with one or more
|
|
3
|
+
* worker conversations.
|
|
4
|
+
*
|
|
5
|
+
* The manager dispatches a round to one worker with `collab_dispatch` (the
|
|
6
|
+
* worker id is required when several workers are linked). The worker executes
|
|
7
|
+
* it, reports with `collab_report`, and when that worker turn ends the plugin
|
|
8
|
+
* delivers the report plus the worker's final message to the manager. The
|
|
9
|
+
* manager reviews it and dispatches again, so every worker runs its own loop
|
|
10
|
+
* until `collab_done` closes that worker.
|
|
11
|
+
*
|
|
12
|
+
* Link state lives in the `collab_pair` storage domain (table `links`), keyed by
|
|
13
|
+
* link id: one record per worker, all sharing the same manager. The domain is
|
|
14
|
+
* opened through the optional `storageDomain` service, with an in-memory
|
|
15
|
+
* fallback when it is unavailable.
|
|
16
|
+
*
|
|
17
|
+
* @module dsh-collab-pair
|
|
18
|
+
*/
|
|
19
|
+
import { randomUUID } from 'node:crypto'
|
|
20
|
+
|
|
21
|
+
export const inject = ['tools', 'systemPrompt', 'agents', 'sessions', 'commands']
|
|
22
|
+
|
|
23
|
+
const SECTION_NAME = 'collab-pair'
|
|
24
|
+
const SECTION_ORDER = 650
|
|
25
|
+
const STORAGE_DOMAIN = {
|
|
26
|
+
name: 'collab_pair',
|
|
27
|
+
version: 1,
|
|
28
|
+
tables: { links: { valueSchema: { parse: (value) => value } } },
|
|
29
|
+
}
|
|
30
|
+
const ACTIVE = 'active'
|
|
31
|
+
const DONE = 'done'
|
|
32
|
+
const STOPPED = 'stopped'
|
|
33
|
+
const REPORTS = new Set(['done', 'partial', 'blocked'])
|
|
34
|
+
const PROMPT_TIMEOUT_MS = 180000
|
|
35
|
+
const ENGINE = 'collab-pair/1.0.8'
|
|
36
|
+
|
|
37
|
+
/** A recoverable failure whose message is meant for the model. */
|
|
38
|
+
class CollabError extends Error {}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Resolve tunable values without a Config schema, so the bundle stays
|
|
42
|
+
* dependency-free and still accepts a `config` block in the profile patch.
|
|
43
|
+
* @param {unknown} raw - the row config object.
|
|
44
|
+
* @returns normalized settings.
|
|
45
|
+
*/
|
|
46
|
+
function resolveConfig(raw) {
|
|
47
|
+
const value = raw !== null && typeof raw === 'object' ? raw : {}
|
|
48
|
+
return {
|
|
49
|
+
maxRounds: clampInt(value.maxRounds, 1, 200, 20),
|
|
50
|
+
maxRelayChars: clampInt(value.maxRelayChars, 500, 100000, 12000),
|
|
51
|
+
maxHistory: clampInt(value.maxHistory, 1, 100, 20),
|
|
52
|
+
notifyWorkerOnDone: value.notifyWorkerOnDone !== false,
|
|
53
|
+
autoRelay: value.autoRelay !== false,
|
|
54
|
+
addPrefix: value.addPrefix !== false,
|
|
55
|
+
prefixManager: prefixText(value.prefixManager, '【项目经理】'),
|
|
56
|
+
prefixWorker: prefixText(value.prefixWorker, '【员工】'),
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** One non-empty prefix string, clamped to a title-safe length. */
|
|
61
|
+
function prefixText(candidate, fallback) {
|
|
62
|
+
if (typeof candidate !== 'string') return fallback
|
|
63
|
+
const value = candidate.trim()
|
|
64
|
+
if (value === '') return fallback
|
|
65
|
+
return value.length > 24 ? value.slice(0, 24) : value
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Clamp one integer setting. */
|
|
69
|
+
function clampInt(candidate, min, max, fallback) {
|
|
70
|
+
const number = typeof candidate === 'number' ? candidate : Number(candidate)
|
|
71
|
+
if (!Number.isFinite(number)) return fallback
|
|
72
|
+
const integer = Math.trunc(number)
|
|
73
|
+
if (integer < min) return min
|
|
74
|
+
if (integer > max) return max
|
|
75
|
+
return integer
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Truncate text at a stable boundary. */
|
|
79
|
+
function clip(text, limit) {
|
|
80
|
+
const value = typeof text === 'string' ? text : ''
|
|
81
|
+
if (value.length <= limit) return value
|
|
82
|
+
const head = Math.max(0, limit - 40)
|
|
83
|
+
return `${value.slice(0, head)}\n…(已截断,共 ${value.length} 字符)`
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Join assistant/user content blocks into plain text. */
|
|
87
|
+
function messageText(message) {
|
|
88
|
+
const content = message?.content
|
|
89
|
+
if (!Array.isArray(content)) return ''
|
|
90
|
+
const parts = []
|
|
91
|
+
for (const block of content) if (block?.type === 'text' && typeof block.text === 'string') parts.push(block.text)
|
|
92
|
+
return parts.join('\n').trim()
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Human description of a turn end reason. */
|
|
96
|
+
function reasonText(reason) {
|
|
97
|
+
const kind = reason?.kind
|
|
98
|
+
if (kind === 'completed') return '正常结束'
|
|
99
|
+
if (kind === 'blocked') return '等待输入(blocked)'
|
|
100
|
+
if (kind === 'max-tokens') return '达到输出上限'
|
|
101
|
+
if (kind === 'interrupted') return '被中断'
|
|
102
|
+
if (kind === 'forked') return '会话已分叉'
|
|
103
|
+
if (kind === 'aborted') {
|
|
104
|
+
const cause = reason?.reason?.kind
|
|
105
|
+
if (cause === 'user') return '被用户中止'
|
|
106
|
+
if (cause === 'parent') return '被父级中止'
|
|
107
|
+
if (cause === 'disposed') return '会话被关闭'
|
|
108
|
+
if (cause === 'hook') return '被钩子中止'
|
|
109
|
+
return '被中止'
|
|
110
|
+
}
|
|
111
|
+
if (kind === 'error') return `出错:${reason?.error?.message ?? '未知错误'}`
|
|
112
|
+
return typeof kind === 'string' ? kind : '未知'
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Best-effort readable delivery failure. */
|
|
116
|
+
function deliveryFailure(error) {
|
|
117
|
+
const code = error?.code ?? error?.details?.code
|
|
118
|
+
const detail = error?.message ?? String(error)
|
|
119
|
+
if (code === 'session/not-found') return '目标对话不存在或已被删除(session/not-found)。'
|
|
120
|
+
if (code === 'session/writer-held') return '目标对话正被另一个进程占用(session/writer-held),请关闭其他窗口后重试。'
|
|
121
|
+
if (code === 'session/agent-busy') return `目标对话暂时无法接收消息(session/agent-busy):${detail}`
|
|
122
|
+
if (code === 'session/migration-required') return '目标对话需要先打开完成迁移(session/migration-required)。'
|
|
123
|
+
return `投递失败${typeof code === 'string' ? `(${code})` : ''}:${detail}`
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** ISO time for tool output, tolerant of bad stored values. */
|
|
127
|
+
function isoTime(value) {
|
|
128
|
+
return typeof value === 'number' && Number.isFinite(value) ? new Date(value).toISOString() : null
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Split one `/collab` invocation into an action and its arguments.
|
|
133
|
+
* The body may be a JSON object (what the settings page sends) or `--key value`
|
|
134
|
+
* flags (what a person types).
|
|
135
|
+
* @param rawInput - text after the command name.
|
|
136
|
+
* @returns the action name and its arguments.
|
|
137
|
+
*/
|
|
138
|
+
function parseCommandBody(rawInput) {
|
|
139
|
+
const text = typeof rawInput === 'string' ? rawInput.trim() : ''
|
|
140
|
+
if (text === '') return { action: 'status', args: {} }
|
|
141
|
+
const space = text.search(/\s/)
|
|
142
|
+
const action = (space === -1 ? text : text.slice(0, space)).toLowerCase()
|
|
143
|
+
const rest = space === -1 ? '' : text.slice(space + 1).trim()
|
|
144
|
+
if (rest === '') return { action, args: {} }
|
|
145
|
+
if (rest.startsWith('{')) {
|
|
146
|
+
let parsed
|
|
147
|
+
try {
|
|
148
|
+
parsed = JSON.parse(rest)
|
|
149
|
+
} catch (error) {
|
|
150
|
+
throw new CollabError(`参数不是合法 JSON:${String(error instanceof Error ? error.message : error)}`)
|
|
151
|
+
}
|
|
152
|
+
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) throw new CollabError('参数必须是 JSON 对象。')
|
|
153
|
+
return { action, args: parsed }
|
|
154
|
+
}
|
|
155
|
+
return { action, args: parseFlags(rest) }
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Parse `--key value`, `--key=value`, quoted values, and boolean flags. */
|
|
159
|
+
function parseFlags(text) {
|
|
160
|
+
const args = {}
|
|
161
|
+
let index = 0
|
|
162
|
+
while (index < text.length) {
|
|
163
|
+
while (text[index] === ' ') index++
|
|
164
|
+
if (index >= text.length) break
|
|
165
|
+
if (text[index] !== '-' || text[index + 1] !== '-') throw new CollabError(`无法解析参数:"${text.slice(index)}"。用法:--key 值`)
|
|
166
|
+
index += 2
|
|
167
|
+
let key = ''
|
|
168
|
+
while (index < text.length && text[index] !== '=' && text[index] !== ' ') key += text[index++]
|
|
169
|
+
if (text[index] === '=') index++
|
|
170
|
+
else while (text[index] === ' ') index++
|
|
171
|
+
let value = ''
|
|
172
|
+
const quote = text[index]
|
|
173
|
+
if (quote === '"' || quote === "'") {
|
|
174
|
+
index++
|
|
175
|
+
while (index < text.length && text[index] !== quote) {
|
|
176
|
+
if (text[index] === '\\' && index + 1 < text.length) {
|
|
177
|
+
value += text[index + 1]
|
|
178
|
+
index += 2
|
|
179
|
+
} else {
|
|
180
|
+
value += text[index++]
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
index++
|
|
184
|
+
} else {
|
|
185
|
+
while (index < text.length && text[index] !== ' ') value += text[index++]
|
|
186
|
+
}
|
|
187
|
+
if (key === '') throw new CollabError('参数名不能为空。')
|
|
188
|
+
args[key] = value === 'true' ? true : value === 'false' ? false : value
|
|
189
|
+
}
|
|
190
|
+
return args
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
export function apply(ctx, rawConfig) {
|
|
194
|
+
const cfg = resolveConfig(rawConfig)
|
|
195
|
+
const links = new Map()
|
|
196
|
+
/** managerId -> Set<linkId>, every link the session manages (any status). */
|
|
197
|
+
const byManager = new Map()
|
|
198
|
+
/** workerId -> linkId, only while that worker link is active. */
|
|
199
|
+
const byWorker = new Map()
|
|
200
|
+
const relays = new Map()
|
|
201
|
+
const toolExecutors = {}
|
|
202
|
+
let storageState = 'pending'
|
|
203
|
+
let storageError = null
|
|
204
|
+
|
|
205
|
+
const domainReady = openStorage()
|
|
206
|
+
|
|
207
|
+
ctx.effect(() => async () => {
|
|
208
|
+
const domain = await domainReady.catch(() => undefined)
|
|
209
|
+
if (domain === undefined) return
|
|
210
|
+
try {
|
|
211
|
+
await domain.close()
|
|
212
|
+
} catch (error) {
|
|
213
|
+
ctx.logger.warn(`collab-pair: closing the storage domain failed: ${String(error)}`)
|
|
214
|
+
}
|
|
215
|
+
})
|
|
216
|
+
|
|
217
|
+
ctx.systemPrompt.section({
|
|
218
|
+
name: SECTION_NAME,
|
|
219
|
+
order: SECTION_ORDER,
|
|
220
|
+
text: sectionText,
|
|
221
|
+
})
|
|
222
|
+
|
|
223
|
+
ctx.on('session/event', onSessionEvent)
|
|
224
|
+
|
|
225
|
+
registerTools()
|
|
226
|
+
registerCommand()
|
|
227
|
+
|
|
228
|
+
// ---------------------------------------------------------------- storage
|
|
229
|
+
|
|
230
|
+
/** Open the durable link table and hydrate the in-memory index. */
|
|
231
|
+
async function openStorage() {
|
|
232
|
+
const facility = ctx.get('storageDomain')
|
|
233
|
+
if (facility === undefined) {
|
|
234
|
+
storageState = 'memory'
|
|
235
|
+
ctx.logger.info('collab-pair: no storage domain; collaboration links are kept in memory for this run')
|
|
236
|
+
return undefined
|
|
237
|
+
}
|
|
238
|
+
try {
|
|
239
|
+
const domain = await facility.open(STORAGE_DOMAIN)
|
|
240
|
+
const stored = [...domain.table('links').entries()].sort((left, right) => (left[1]?.updatedAt ?? 0) - (right[1]?.updatedAt ?? 0))
|
|
241
|
+
for (const [key, value] of stored) adoptStoredLink(key, value)
|
|
242
|
+
storageState = 'ready'
|
|
243
|
+
return domain
|
|
244
|
+
} catch (error) {
|
|
245
|
+
storageState = 'memory'
|
|
246
|
+
storageError = String(error instanceof Error ? error.message : error)
|
|
247
|
+
ctx.logger.warn(`collab-pair: durable storage is unavailable; links are kept in memory: ${String(error)}`)
|
|
248
|
+
return undefined
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** Wait for the storage attempt once; tools always work afterwards. */
|
|
253
|
+
async function ensureStorage() {
|
|
254
|
+
return domainReady.catch(() => undefined)
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** Validate and index one stored record, ignoring anything malformed. */
|
|
258
|
+
function adoptStoredLink(key, value) {
|
|
259
|
+
if (value === null || typeof value !== 'object') return
|
|
260
|
+
if (typeof value.id !== 'string' || value.id !== key) return
|
|
261
|
+
if (typeof value.manager !== 'string' || typeof value.worker !== 'string') return
|
|
262
|
+
if (value.manager === value.worker) return
|
|
263
|
+
const link = normalizeLink(value)
|
|
264
|
+
const existingId = byWorker.get(link.worker)
|
|
265
|
+
if (existingId !== undefined && existingId !== link.id) {
|
|
266
|
+
const existing = links.get(existingId)
|
|
267
|
+
if (existing !== undefined) unindex(existing)
|
|
268
|
+
}
|
|
269
|
+
index(link)
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** Fill missing fields on a stored record. */
|
|
273
|
+
function normalizeLink(value) {
|
|
274
|
+
const status = value.status === DONE || value.status === STOPPED ? value.status : ACTIVE
|
|
275
|
+
return {
|
|
276
|
+
v: 1,
|
|
277
|
+
id: value.id,
|
|
278
|
+
manager: value.manager,
|
|
279
|
+
worker: value.worker,
|
|
280
|
+
label: typeof value.label === 'string' ? value.label : '',
|
|
281
|
+
goal: typeof value.goal === 'string' ? value.goal : '',
|
|
282
|
+
status,
|
|
283
|
+
round: Number.isSafeInteger(value.round) && value.round >= 0 ? value.round : 0,
|
|
284
|
+
pending: normalizePending(value.pending),
|
|
285
|
+
lastReport: value.lastReport !== null && typeof value.lastReport === 'object' ? value.lastReport : null,
|
|
286
|
+
history: Array.isArray(value.history) ? value.history.slice(-cfg.maxHistory) : [],
|
|
287
|
+
createdAt: Number.isFinite(value.createdAt) ? value.createdAt : Date.now(),
|
|
288
|
+
updatedAt: Number.isFinite(value.updatedAt) ? value.updatedAt : Date.now(),
|
|
289
|
+
...(typeof value.closedAt === 'number' ? { closedAt: value.closedAt } : {}),
|
|
290
|
+
...(typeof value.finalSummary === 'string' ? { finalSummary: value.finalSummary } : {}),
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** Fill missing fields on a stored pending round. */
|
|
295
|
+
function normalizePending(value) {
|
|
296
|
+
if (value === null || typeof value !== 'object') return null
|
|
297
|
+
if (!Number.isSafeInteger(value.round) || value.round < 1) return null
|
|
298
|
+
if (typeof value.task !== 'string' || typeof value.requestId !== 'string') return null
|
|
299
|
+
return {
|
|
300
|
+
round: value.round,
|
|
301
|
+
task: value.task,
|
|
302
|
+
acceptance: typeof value.acceptance === 'string' ? value.acceptance : '',
|
|
303
|
+
requestId: value.requestId,
|
|
304
|
+
dispatchedAt: Number.isFinite(value.dispatchedAt) ? value.dispatchedAt : Date.now(),
|
|
305
|
+
report: normalizeReport(value.report),
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/** Fill missing fields on a stored worker report. */
|
|
310
|
+
function normalizeReport(value) {
|
|
311
|
+
if (value === null || typeof value !== 'object') return null
|
|
312
|
+
if (typeof value.summary !== 'string') return null
|
|
313
|
+
return {
|
|
314
|
+
summary: value.summary,
|
|
315
|
+
status: REPORTS.has(value.status) ? value.status : 'partial',
|
|
316
|
+
details: typeof value.details === 'string' ? value.details : '',
|
|
317
|
+
next: typeof value.next === 'string' ? value.next : '',
|
|
318
|
+
reportedAt: Number.isFinite(value.reportedAt) ? value.reportedAt : Date.now(),
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/** Persist one link record; a storage failure never breaks the live loop. */
|
|
323
|
+
async function persist(link) {
|
|
324
|
+
const domain = await ensureStorage()
|
|
325
|
+
if (domain === undefined) return
|
|
326
|
+
try {
|
|
327
|
+
await domain.table('links').put(link.id, JSON.parse(JSON.stringify(link)))
|
|
328
|
+
} catch (error) {
|
|
329
|
+
ctx.logger.warn(`collab-pair: persisting link ${link.id} failed: ${String(error)}`)
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
// ------------------------------------------------------------- prompt text
|
|
334
|
+
|
|
335
|
+
/**
|
|
336
|
+
* Dynamic system-prompt section. It returns nothing for sessions outside an
|
|
337
|
+
* active link, so it costs no tokens until a pair exists.
|
|
338
|
+
*/
|
|
339
|
+
function sectionText(context) {
|
|
340
|
+
const agentId = context?.agent?.id ?? context?.scope?.id
|
|
341
|
+
if (typeof agentId !== 'string') return ''
|
|
342
|
+
const managed = managerLinks(agentId, true)
|
|
343
|
+
if (managed.length > 0) {
|
|
344
|
+
const rows = managed.slice(0, 8).map((link) => {
|
|
345
|
+
const state = link.pending === null ? '空闲' : '等待回报'
|
|
346
|
+
const last = link.lastReport === null ? '' : ` · 最近:${statusLabel(link.lastReport.status)}`
|
|
347
|
+
return `- ${link.label || '(未命名员工)'}(${link.worker}):第 ${link.round} 轮 · ${state}${last}`
|
|
348
|
+
})
|
|
349
|
+
if (managed.length > 8) rows.push(`- …另有 ${managed.length - 8} 个员工,用 collab_status 查看`)
|
|
350
|
+
return [
|
|
351
|
+
'## 双对话协作 · 你是项目经理',
|
|
352
|
+
`你正在协调 ${managed.length} 个员工对话;项目目标、任务拆解与验收标准由你在对话中掌握。`,
|
|
353
|
+
'员工:',
|
|
354
|
+
...rows,
|
|
355
|
+
'',
|
|
356
|
+
'规则:',
|
|
357
|
+
'- 用 `collab_dispatch` 派发任务;有多个员工时用 `worker` 指定员工(sessionId 或标题),只有一个时可省略。',
|
|
358
|
+
'- 需要调整某个员工的 agent 预设或模型时,用 `collab_configure`(worker 指定员工)。',
|
|
359
|
+
'- 收到以【协作回报】开头的消息后,继续派发,或对该员工调用 `collab_done`;`collab_status` 查看全部进度。',
|
|
360
|
+
'- 除非用户明确要求,不要自己执行员工的交付任务;你负责拆解、验收和决定下一步。',
|
|
361
|
+
`- 每个员工最多 ${cfg.maxRounds} 轮。`,
|
|
362
|
+
].join('\n')
|
|
363
|
+
}
|
|
364
|
+
const link = workerLink(agentId)
|
|
365
|
+
if (link === undefined) return ''
|
|
366
|
+
return [
|
|
367
|
+
'## 双对话协作 · 你是员工',
|
|
368
|
+
`项目经理对话:${link.manager}`,
|
|
369
|
+
`进度:第 ${link.round} 轮${link.pending === null ? '' : ',待你完成本轮任务'}`,
|
|
370
|
+
'你负责执行项目经理派发的任务,并如实回报结果;项目目标与验收标准以派发消息为准,不要改变大方向或扩大范围。',
|
|
371
|
+
'',
|
|
372
|
+
'规则:',
|
|
373
|
+
'- 严格按本对话里最近一条【协作任务】执行。',
|
|
374
|
+
'- 完成后调用 `collab_report` 汇报:summary(交付物/结论)、status(done/partial/blocked)、details、next,然后结束本轮回复。',
|
|
375
|
+
'- 你的最终回复会连同汇报一起自动回传给项目经理;遇到阻塞用 blocked 写清需要什么决策。',
|
|
376
|
+
'- 项目经理可能连续派发多轮任务,每轮都按上述流程执行。',
|
|
377
|
+
].join('\n')
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/** Render one dispatch message for a worker. */
|
|
381
|
+
function dispatchText(link, round, task, acceptance) {
|
|
382
|
+
const lines = [`【协作任务 · 第 ${round} 轮】`, '']
|
|
383
|
+
if (link.goal) lines.push(`项目目标:${link.goal}`, '')
|
|
384
|
+
lines.push(
|
|
385
|
+
'—— 本轮任务 ——',
|
|
386
|
+
task,
|
|
387
|
+
'',
|
|
388
|
+
'—— 验收标准 ——',
|
|
389
|
+
acceptance || '(未指定;按任务目标自行检查交付完整性)',
|
|
390
|
+
'',
|
|
391
|
+
'—— 交付要求 ——',
|
|
392
|
+
'1. 直接执行本轮任务,不要改变项目大方向,也不要扩大到任务之外。',
|
|
393
|
+
'2. 完成后调用 collab_report 汇报:summary / status(done 完成、partial 部分完成、blocked 受阻需决策)/ details / next。',
|
|
394
|
+
'3. 汇报后结束本轮回复;你的最终回复会作为「产出与反馈」自动回传给项目经理。',
|
|
395
|
+
`[[collab:${link.id}:r${round}]]`,
|
|
396
|
+
)
|
|
397
|
+
return lines.join('\n')
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/** Render the report the manager receives. */
|
|
401
|
+
function reportText({ link, pending, report, finalText, reason, workerTitle }) {
|
|
402
|
+
const status = report === undefined ? '未显式汇报' : statusLabel(report.status)
|
|
403
|
+
const lines = [
|
|
404
|
+
`【协作回报 · 第 ${pending.round} 轮】`,
|
|
405
|
+
`来自员工对话:${workerTitle || link.label || '(未命名对话)'}(${link.worker})`,
|
|
406
|
+
`本轮状态:${status}`,
|
|
407
|
+
`结束原因:${reasonText(reason)}`,
|
|
408
|
+
'',
|
|
409
|
+
]
|
|
410
|
+
if (report !== undefined) {
|
|
411
|
+
lines.push('—— 员工汇报 ——', report.summary)
|
|
412
|
+
if (report.details) lines.push('', '细节:', report.details)
|
|
413
|
+
if (report.next) lines.push('', `员工建议:${report.next}`)
|
|
414
|
+
lines.push('')
|
|
415
|
+
}
|
|
416
|
+
lines.push(
|
|
417
|
+
'—— 员工最终产出 ——',
|
|
418
|
+
finalText || (report === undefined
|
|
419
|
+
? '(本轮没有可读取的文本产出,可打开员工对话查看完整过程)'
|
|
420
|
+
: '(员工本轮没有额外文字总结,以上汇报即为其产出。)'),
|
|
421
|
+
'',
|
|
422
|
+
)
|
|
423
|
+
if (link.round >= cfg.maxRounds) {
|
|
424
|
+
lines.push(`⚠ 该员工已达到配置的最大轮次 ${cfg.maxRounds},无法再派发新一轮;请验收成果后调用 collab_done 收尾。`, '')
|
|
425
|
+
}
|
|
426
|
+
lines.push(
|
|
427
|
+
'—— 下一步 ——',
|
|
428
|
+
'请以项目经理身份审阅本轮结果:',
|
|
429
|
+
`- 需要继续:调用 collab_dispatch 下发第 ${link.round + 1} 轮任务,worker="${link.worker}"(可附验收标准)。`,
|
|
430
|
+
`- 该员工已完成:调用 collab_done,worker="${link.worker}",形成总结并收尾。`,
|
|
431
|
+
`- 需要了解过程细节:可打开员工对话 ${link.worker} 查看。`,
|
|
432
|
+
`[[collab:${link.id}:r${pending.round}:report]]`,
|
|
433
|
+
)
|
|
434
|
+
return lines.join('\n')
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/** Render the closing message for the worker. */
|
|
438
|
+
function doneText(link, summary) {
|
|
439
|
+
return [
|
|
440
|
+
'【协作结束】',
|
|
441
|
+
'项目经理已确认本项目完成,本轮协作到此结束。',
|
|
442
|
+
'',
|
|
443
|
+
`项目总结:${summary || '(无)'}`,
|
|
444
|
+
'',
|
|
445
|
+
'不需要再执行新的任务,也不要再调用协作工具;如果手上还有未完成的工作,请停止并简要说明当前状态。',
|
|
446
|
+
`[[collab:${link.id}:done]]`,
|
|
447
|
+
].join('\n')
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/** Chinese label for a report status. */
|
|
451
|
+
function statusLabel(status) {
|
|
452
|
+
if (status === 'done') return '完成'
|
|
453
|
+
if (status === 'partial') return '部分完成'
|
|
454
|
+
if (status === 'blocked') return '受阻,需要决策'
|
|
455
|
+
if (status === 'unreported') return '未显式汇报'
|
|
456
|
+
return '未知'
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
// -------------------------------------------------------------- delivery
|
|
460
|
+
|
|
461
|
+
/** Resolve, resume, and wake one session with a prompt. */
|
|
462
|
+
async function deliver(sessionId, text, requestId, mode, signal) {
|
|
463
|
+
const controller = ctx.get('sessionController')
|
|
464
|
+
if (controller === undefined) throw new CollabError('当前环境缺少 sessionController,无法投递协作消息。')
|
|
465
|
+
const cancellation = signal ?? AbortSignal.timeout(PROMPT_TIMEOUT_MS)
|
|
466
|
+
try {
|
|
467
|
+
await controller.prompt(
|
|
468
|
+
{ requestId, sessionId, mode, content: [{ type: 'text', text }] },
|
|
469
|
+
cancellation,
|
|
470
|
+
)
|
|
471
|
+
} catch (error) {
|
|
472
|
+
throw new CollabError(deliveryFailure(error))
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
// ---------------------------------------------------------------- session helpers
|
|
477
|
+
|
|
478
|
+
/** Title of one session, or undefined. */
|
|
479
|
+
async function titleOf(sessionId) {
|
|
480
|
+
const query = ctx.get('sessionQuery')
|
|
481
|
+
if (query === undefined) return undefined
|
|
482
|
+
try {
|
|
483
|
+
const snapshot = await query.readTitle(sessionId)
|
|
484
|
+
return typeof snapshot?.title === 'string' ? snapshot.title : undefined
|
|
485
|
+
} catch {
|
|
486
|
+
return undefined
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
/** Recent, linkable conversations with titles when the query service allows it. */
|
|
491
|
+
async function candidateSessions(signal) {
|
|
492
|
+
const controller = ctx.get('sessionController')
|
|
493
|
+
const query = ctx.get('sessionQuery')
|
|
494
|
+
const archived = new Set(ctx.get('workspaceRegistry')?.archivedSessionIds ?? [])
|
|
495
|
+
const rows = []
|
|
496
|
+
if (controller !== undefined) {
|
|
497
|
+
const value = await controller.list({}, signal)
|
|
498
|
+
for (const item of value?.items ?? []) {
|
|
499
|
+
if (item?.blank === true) continue
|
|
500
|
+
if (item?.origin === 'subagent') continue
|
|
501
|
+
if (archived.has(item.sessionId)) continue
|
|
502
|
+
rows.push({
|
|
503
|
+
sessionId: item.sessionId,
|
|
504
|
+
title: undefined,
|
|
505
|
+
updatedAt: item.updatedAt,
|
|
506
|
+
running: item.running === true,
|
|
507
|
+
})
|
|
508
|
+
}
|
|
509
|
+
} else if (query !== undefined) {
|
|
510
|
+
const records = await query.listSessions(signal)
|
|
511
|
+
for (const record of records) {
|
|
512
|
+
if (record?.header?.origin === 'subagent') continue
|
|
513
|
+
if (archived.has(record.header.id)) continue
|
|
514
|
+
rows.push({
|
|
515
|
+
sessionId: record.header.id,
|
|
516
|
+
title: undefined,
|
|
517
|
+
updatedAt: record.header.createdAt,
|
|
518
|
+
running: record.live === true,
|
|
519
|
+
})
|
|
520
|
+
}
|
|
521
|
+
rows.sort((left, right) => right.updatedAt - left.updatedAt)
|
|
522
|
+
} else {
|
|
523
|
+
for (const agent of ctx.agents.list()) {
|
|
524
|
+
rows.push({ sessionId: agent.id, title: undefined, updatedAt: Date.now(), running: agent.status === 'running' })
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
if (query !== undefined && rows.length > 0) {
|
|
528
|
+
try {
|
|
529
|
+
const observations = await query.readTitleSnapshots(rows.slice(0, 60).map((row) => row.sessionId), signal)
|
|
530
|
+
const titles = new Map()
|
|
531
|
+
for (const observation of observations) {
|
|
532
|
+
if (observation.status !== 'fulfilled') continue
|
|
533
|
+
const title = observation.value?.title?.title
|
|
534
|
+
if (typeof title === 'string') titles.set(observation.sessionId, title)
|
|
535
|
+
}
|
|
536
|
+
for (const row of rows) row.title = titles.get(row.sessionId)
|
|
537
|
+
} catch {
|
|
538
|
+
// Titles are presentation only; ids still resolve links.
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
return rows
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
/** Resolve a peer written by the model: `new`, an exact id, or a title fragment. */
|
|
545
|
+
async function resolvePeer(rawPeer, signal) {
|
|
546
|
+
const peer = typeof rawPeer === 'string' ? rawPeer.trim() : ''
|
|
547
|
+
if (peer === '') throw new CollabError('peer 不能为空:传 sessionId、标题关键词,或 "new" 新建一个员工对话。')
|
|
548
|
+
if (peer === 'new' || peer === 'create') return { kind: 'new' }
|
|
549
|
+
let candidates = []
|
|
550
|
+
try {
|
|
551
|
+
candidates = await candidateSessions(signal)
|
|
552
|
+
} catch (error) {
|
|
553
|
+
ctx.logger.warn(`collab-pair: listing sessions failed: ${String(error)}`)
|
|
554
|
+
}
|
|
555
|
+
const exact = candidates.find((row) => row.sessionId === peer)
|
|
556
|
+
if (exact !== undefined) return { kind: 'existing', ...exact }
|
|
557
|
+
if (ctx.sessions.get(peer) !== undefined || ctx.agents.get(peer) !== undefined) {
|
|
558
|
+
return { kind: 'existing', sessionId: peer, title: await titleOf(peer), updatedAt: Date.now(), running: ctx.agents.get(peer)?.status === 'running' }
|
|
559
|
+
}
|
|
560
|
+
const needle = peer.toLowerCase()
|
|
561
|
+
const matches = candidates.filter((row) => typeof row.title === 'string' && row.title.toLowerCase().includes(needle))
|
|
562
|
+
if (matches.length === 1) return { kind: 'existing', ...matches[0] }
|
|
563
|
+
if (matches.length > 1) {
|
|
564
|
+
const list = matches.slice(0, 8).map((row) => `- ${row.sessionId} ${row.title ?? ''}`).join('\n')
|
|
565
|
+
throw new CollabError(`标题 "${peer}" 匹配到 ${matches.length} 个对话,请改用精确的 sessionId:\n${list}`)
|
|
566
|
+
}
|
|
567
|
+
if (candidates.length > 0) {
|
|
568
|
+
const list = candidates.slice(0, 8).map((row) => `- ${row.sessionId} ${row.title ?? '(未命名)'}`).join('\n')
|
|
569
|
+
throw new CollabError(`没有找到对话 "${peer}"。可先调用 collab_sessions 查看候选,最近的对话有:\n${list}`)
|
|
570
|
+
}
|
|
571
|
+
throw new CollabError(`没有找到对话 "${peer}",当前也没有可列出对话的服务。请传一个准确的 sessionId。`)
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
/** Create a fresh worker conversation in the manager's working directory. */
|
|
575
|
+
async function createWorkerSession(callerId, requestedCwd, signal) {
|
|
576
|
+
const controller = ctx.get('sessionController')
|
|
577
|
+
if (controller === undefined) throw new CollabError('当前环境不支持新建对话;请先手动创建一个对话再关联。')
|
|
578
|
+
const callerSession = ctx.sessions.get(callerId)
|
|
579
|
+
const cwd = typeof requestedCwd === 'string' && requestedCwd.trim() !== ''
|
|
580
|
+
? requestedCwd.trim()
|
|
581
|
+
: (callerSession === undefined ? undefined : ctx.get('workingDirectory')?.get(callerSession))
|
|
582
|
+
const created = await controller.create(cwd === undefined ? {} : { cwd })
|
|
583
|
+
const sessionId = created?.sessionId
|
|
584
|
+
if (typeof sessionId !== 'string') throw new CollabError('新建对话失败:没有返回 sessionId。')
|
|
585
|
+
const registry = ctx.get('workspaceRegistry')
|
|
586
|
+
if (registry !== undefined && cwd !== undefined) {
|
|
587
|
+
try {
|
|
588
|
+
const workspace = await registry.resolveByPath(cwd)
|
|
589
|
+
await workspace?.attachSession(sessionId)
|
|
590
|
+
} catch (error) {
|
|
591
|
+
ctx.logger.warn(`collab-pair: attaching new session ${sessionId} to its workspace failed: ${String(error)}`)
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
return sessionId
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
// ------------------------------------------------------------------- links
|
|
598
|
+
|
|
599
|
+
/** Resolve (and resume when needed) the live agent behind one worker session. */
|
|
600
|
+
async function resolveWorkerAgent(sessionId) {
|
|
601
|
+
const controller = ctx.get('sessionController')
|
|
602
|
+
if (controller === undefined || typeof controller.resolveAgent !== 'function') throw new CollabError('当前环境缺少 sessionController。')
|
|
603
|
+
let resolved
|
|
604
|
+
try {
|
|
605
|
+
resolved = await controller.resolveAgent(sessionId)
|
|
606
|
+
} catch (error) {
|
|
607
|
+
throw new CollabError(`无法打开员工对话 ${sessionId}:${error instanceof Error ? error.message : String(error)}`)
|
|
608
|
+
}
|
|
609
|
+
if (resolved === undefined || resolved === null || resolved.error !== undefined || resolved.agent === undefined) {
|
|
610
|
+
const failure = resolved?.error
|
|
611
|
+
throw new CollabError(`无法打开员工对话 ${sessionId}:${failure?.code ?? '未知错误'}${failure?.message ? `:${failure.message}` : ''}`)
|
|
612
|
+
}
|
|
613
|
+
return resolved.agent
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
/** Every link one manager owns, oldest first. */
|
|
617
|
+
function managerLinks(managerId, activeOnly = false) {
|
|
618
|
+
const ids = byManager.get(managerId)
|
|
619
|
+
if (ids === undefined) return []
|
|
620
|
+
const rows = []
|
|
621
|
+
for (const id of ids) {
|
|
622
|
+
const link = links.get(id)
|
|
623
|
+
if (link === undefined) continue
|
|
624
|
+
if (activeOnly && link.status !== ACTIVE) continue
|
|
625
|
+
rows.push(link)
|
|
626
|
+
}
|
|
627
|
+
rows.sort((left, right) => left.createdAt - right.createdAt)
|
|
628
|
+
return rows
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
/** The active link in which this session is the worker. */
|
|
632
|
+
function workerLink(sessionId) {
|
|
633
|
+
const linkId = byWorker.get(sessionId)
|
|
634
|
+
return linkId === undefined ? undefined : links.get(linkId)
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
/** Index one link by its manager and (while active) its worker. */
|
|
638
|
+
function index(link) {
|
|
639
|
+
links.set(link.id, link)
|
|
640
|
+
let managed = byManager.get(link.manager)
|
|
641
|
+
if (managed === undefined) {
|
|
642
|
+
managed = new Set()
|
|
643
|
+
byManager.set(link.manager, managed)
|
|
644
|
+
}
|
|
645
|
+
managed.add(link.id)
|
|
646
|
+
if (link.status === ACTIVE) byWorker.set(link.worker, link.id)
|
|
647
|
+
else if (byWorker.get(link.worker) === link.id) byWorker.delete(link.worker)
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
/** Drop one link from the in-memory index. */
|
|
651
|
+
function unindex(link) {
|
|
652
|
+
links.delete(link.id)
|
|
653
|
+
const managed = byManager.get(link.manager)
|
|
654
|
+
if (managed !== undefined) {
|
|
655
|
+
managed.delete(link.id)
|
|
656
|
+
if (managed.size === 0) byManager.delete(link.manager)
|
|
657
|
+
}
|
|
658
|
+
if (byWorker.get(link.worker) === link.id) byWorker.delete(link.worker)
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
/** Drop one link from memory and from durable storage. */
|
|
662
|
+
async function forget(link) {
|
|
663
|
+
unindex(link)
|
|
664
|
+
const domain = await ensureStorage()
|
|
665
|
+
if (domain === undefined) return
|
|
666
|
+
try {
|
|
667
|
+
await domain.table('links').delete(link.id)
|
|
668
|
+
} catch (error) {
|
|
669
|
+
ctx.logger.warn(`collab-pair: deleting link ${link.id} failed: ${String(error)}`)
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
/** Human list of one manager's active workers. */
|
|
674
|
+
function workerList(rows) {
|
|
675
|
+
return rows.map((link) => `- ${link.label || '(未命名员工)'}:${link.worker}`).join('\n')
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
/** Remove one of our role prefixes from a title. */
|
|
679
|
+
function stripKnownPrefix(title) {
|
|
680
|
+
for (const prefix of new Set([cfg.prefixManager, cfg.prefixWorker])) {
|
|
681
|
+
if (prefix !== '' && title.startsWith(prefix)) return title.slice(prefix.length).trimStart()
|
|
682
|
+
}
|
|
683
|
+
return title
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
/** Rename one session: live titles directly, cold ones through the resuming controller. */
|
|
687
|
+
async function renameSession(sessionId, title) {
|
|
688
|
+
const session = ctx.sessions.get(sessionId)
|
|
689
|
+
const titles = ctx.get('sessionTitle')
|
|
690
|
+
if (session !== undefined && titles !== undefined && typeof titles.rename === 'function') {
|
|
691
|
+
try {
|
|
692
|
+
titles.rename(session, title)
|
|
693
|
+
return true
|
|
694
|
+
} catch (error) {
|
|
695
|
+
ctx.logger.warn(`collab-pair: renaming live session ${sessionId} failed: ${String(error)}`)
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
const controller = ctx.get('sessionController')
|
|
699
|
+
if (controller === undefined || typeof controller.rename !== 'function') return false
|
|
700
|
+
try {
|
|
701
|
+
await controller.rename({ sessionId, title })
|
|
702
|
+
return true
|
|
703
|
+
} catch (error) {
|
|
704
|
+
ctx.logger.warn(`collab-pair: renaming session ${sessionId} failed: ${String(error)}`)
|
|
705
|
+
return false
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
/** Ensure one session title starts with its role prefix, without stacking. */
|
|
710
|
+
async function applyPrefix(sessionId, prefix) {
|
|
711
|
+
if (!cfg.addPrefix || prefix === '') return
|
|
712
|
+
const title = await titleOf(sessionId)
|
|
713
|
+
if (typeof title !== 'string' || title === '') return
|
|
714
|
+
if (title.startsWith(prefix)) return
|
|
715
|
+
await renameSession(sessionId, `${prefix}${stripKnownPrefix(title)}`)
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
/** Remove our role prefix from one session title, keeping the rest. */
|
|
719
|
+
async function clearPrefix(sessionId) {
|
|
720
|
+
if (!cfg.addPrefix) return
|
|
721
|
+
const title = await titleOf(sessionId)
|
|
722
|
+
if (typeof title !== 'string' || title === '') return
|
|
723
|
+
const stripped = stripKnownPrefix(title)
|
|
724
|
+
if (stripped !== title && stripped !== '') await renameSession(sessionId, stripped)
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
/** Resolve one of a manager's active workers by id, link id, or label. */
|
|
728
|
+
function resolveManagedLink(managerId, selector) {
|
|
729
|
+
const active = managerLinks(managerId, true)
|
|
730
|
+
if (active.length === 0) throw new CollabError('当前对话没有进行中的员工协作;先用 collab_link 关联一个员工。')
|
|
731
|
+
const text = typeof selector === 'string' ? selector.trim() : ''
|
|
732
|
+
if (text === '') {
|
|
733
|
+
if (active.length === 1) return active[0]
|
|
734
|
+
throw new CollabError(`当前对话有 ${active.length} 个员工,请用 worker 参数指定:\n${workerList(active)}`)
|
|
735
|
+
}
|
|
736
|
+
const exact = active.find((link) => link.worker === text || link.id === text)
|
|
737
|
+
if (exact !== undefined) return exact
|
|
738
|
+
const needle = text.toLowerCase()
|
|
739
|
+
const matches = active.filter((link) => typeof link.label === 'string' && link.label !== '' && link.label.toLowerCase().includes(needle))
|
|
740
|
+
if (matches.length === 1) return matches[0]
|
|
741
|
+
if (matches.length > 1) throw new CollabError(`"${text}" 匹配到多个员工,请用 sessionId 指定:\n${workerList(matches)}`)
|
|
742
|
+
throw new CollabError(`没有找到员工 "${text}"。当前员工:\n${workerList(active)}`)
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
/** Global board: every link, active first, with the labels a human needs. */
|
|
746
|
+
async function tasksBoard() {
|
|
747
|
+
const titles = new Map()
|
|
748
|
+
const titleFor = async (sessionId) => {
|
|
749
|
+
if (!titles.has(sessionId)) titles.set(sessionId, (await titleOf(sessionId)) ?? null)
|
|
750
|
+
return titles.get(sessionId)
|
|
751
|
+
}
|
|
752
|
+
const sorted = [...links.values()].sort((left, right) => {
|
|
753
|
+
const activeDelta = Number(right.status === ACTIVE) - Number(left.status === ACTIVE)
|
|
754
|
+
return activeDelta !== 0 ? activeDelta : right.updatedAt - left.updatedAt
|
|
755
|
+
})
|
|
756
|
+
const rows = []
|
|
757
|
+
for (const link of sorted) {
|
|
758
|
+
const managerTitle = await titleFor(link.manager)
|
|
759
|
+
const workerTitle = (await titleFor(link.worker)) ?? (link.label || null)
|
|
760
|
+
const workerAgent = ctx.agents.get(link.worker)
|
|
761
|
+
const managerAgent = ctx.agents.get(link.manager)
|
|
762
|
+
rows.push({
|
|
763
|
+
linkId: link.id,
|
|
764
|
+
manager: link.manager,
|
|
765
|
+
managerTitle: managerTitle ?? null,
|
|
766
|
+
worker: link.worker,
|
|
767
|
+
workerTitle: workerTitle ?? null,
|
|
768
|
+
status: link.status,
|
|
769
|
+
workerLive: workerAgent !== undefined,
|
|
770
|
+
workerRunning: workerAgent !== undefined && workerAgent.status === 'running',
|
|
771
|
+
managerRunning: managerAgent !== undefined && managerAgent.status === 'running',
|
|
772
|
+
round: link.round,
|
|
773
|
+
waitedSeconds: link.pending === null ? null : Math.max(0, Math.round((Date.now() - link.pending.dispatchedAt) / 1000)),
|
|
774
|
+
pending: link.pending === null ? null : {
|
|
775
|
+
round: link.pending.round,
|
|
776
|
+
task: clip(link.pending.task, 400),
|
|
777
|
+
acceptance: link.pending.acceptance === '' ? null : clip(link.pending.acceptance, 400),
|
|
778
|
+
reported: link.pending.report !== null,
|
|
779
|
+
dispatchedAt: isoTime(link.pending.dispatchedAt),
|
|
780
|
+
},
|
|
781
|
+
lastReport: link.lastReport === null ? null : {
|
|
782
|
+
round: link.lastReport.round,
|
|
783
|
+
status: link.lastReport.status,
|
|
784
|
+
summary: clip(link.lastReport.summary, 400),
|
|
785
|
+
turnReason: link.lastReport.turnReason,
|
|
786
|
+
relayedAt: isoTime(link.lastReport.relayedAt),
|
|
787
|
+
...(link.lastReport.deliveryError === undefined ? {} : { deliveryError: link.lastReport.deliveryError }),
|
|
788
|
+
},
|
|
789
|
+
createdAt: isoTime(link.createdAt),
|
|
790
|
+
updatedAt: isoTime(link.updatedAt),
|
|
791
|
+
})
|
|
792
|
+
}
|
|
793
|
+
return {
|
|
794
|
+
ok: true,
|
|
795
|
+
generatedAt: isoTime(Date.now()),
|
|
796
|
+
maxRounds: cfg.maxRounds,
|
|
797
|
+
activeCount: rows.filter((row) => row.status === ACTIVE).length,
|
|
798
|
+
totalCount: rows.length,
|
|
799
|
+
links: rows,
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
/** Send one round to the worker and record it as pending. */
|
|
804
|
+
async function dispatchRound(link, task, acceptance, signal, force) { if (link.status !== ACTIVE) throw new CollabError(`与该员工的协作已结束(${link.status}),不能继续派发。`)
|
|
805
|
+
if (link.pending !== null && !force) {
|
|
806
|
+
throw new CollabError(`第 ${link.pending.round} 轮仍在等待该员工回报,不要重复派发;需要覆盖请传 force=true。`)
|
|
807
|
+
}
|
|
808
|
+
if (link.round >= cfg.maxRounds) {
|
|
809
|
+
throw new CollabError(`已达到最大轮次 ${cfg.maxRounds},请验收成果并调用 collab_done 收尾。`)
|
|
810
|
+
}
|
|
811
|
+
const round = link.round + 1
|
|
812
|
+
const requestId = `cp-${link.id}-r${round}-to-worker`
|
|
813
|
+
const previous = link.pending
|
|
814
|
+
const previousRound = link.round
|
|
815
|
+
link.round = round
|
|
816
|
+
link.pending = {
|
|
817
|
+
round,
|
|
818
|
+
task,
|
|
819
|
+
acceptance,
|
|
820
|
+
requestId,
|
|
821
|
+
dispatchedAt: Date.now(),
|
|
822
|
+
report: null,
|
|
823
|
+
}
|
|
824
|
+
link.updatedAt = Date.now()
|
|
825
|
+
await persist(link)
|
|
826
|
+
try {
|
|
827
|
+
await deliver(link.worker, dispatchText(link, round, task, acceptance), requestId, 'queue', signal)
|
|
828
|
+
} catch (error) {
|
|
829
|
+
link.round = previousRound
|
|
830
|
+
link.pending = previous
|
|
831
|
+
link.updatedAt = Date.now()
|
|
832
|
+
await persist(link)
|
|
833
|
+
throw error
|
|
834
|
+
}
|
|
835
|
+
return { round, requestId }
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
/** Deliver the pending round's report to the manager. */
|
|
839
|
+
async function relayReport(link, snapshot, events, reason) {
|
|
840
|
+
const current = links.get(link.id)
|
|
841
|
+
if (current === undefined || current.status !== ACTIVE) return
|
|
842
|
+
const pending = current.pending
|
|
843
|
+
if (pending === null || pending.round !== snapshot.round) return
|
|
844
|
+
const report = pending.report ?? reportFrom(events)
|
|
845
|
+
const finalText = clip(lastAssistantText(events), cfg.maxRelayChars)
|
|
846
|
+
// A brand-new worker gets its title only after its first turn; prefix it now.
|
|
847
|
+
await applyPrefix(current.worker, cfg.prefixWorker)
|
|
848
|
+
const workerTitle = await titleOf(current.worker)
|
|
849
|
+
if (workerTitle !== undefined && workerTitle !== current.label) current.label = workerTitle
|
|
850
|
+
const status = report?.status ?? 'unreported'
|
|
851
|
+
current.pending = null
|
|
852
|
+
current.lastReport = {
|
|
853
|
+
round: pending.round,
|
|
854
|
+
status,
|
|
855
|
+
summary: report?.summary ?? '',
|
|
856
|
+
details: report?.details ?? '',
|
|
857
|
+
next: report?.next ?? '',
|
|
858
|
+
text: finalText,
|
|
859
|
+
turnReason: reasonText(reason),
|
|
860
|
+
relayedAt: Date.now(),
|
|
861
|
+
relayRequestId: `cp-${current.id}-r${pending.round}-to-manager`,
|
|
862
|
+
}
|
|
863
|
+
current.history = [
|
|
864
|
+
...(current.history ?? []),
|
|
865
|
+
{
|
|
866
|
+
round: pending.round,
|
|
867
|
+
task: clip(pending.task, 300),
|
|
868
|
+
status,
|
|
869
|
+
summary: clip(report?.summary ?? '', 500),
|
|
870
|
+
at: Date.now(),
|
|
871
|
+
},
|
|
872
|
+
].slice(-cfg.maxHistory)
|
|
873
|
+
current.updatedAt = Date.now()
|
|
874
|
+
await persist(current)
|
|
875
|
+
if (!cfg.autoRelay) return
|
|
876
|
+
try {
|
|
877
|
+
await deliver(
|
|
878
|
+
current.manager,
|
|
879
|
+
reportText({ link: current, pending, report, finalText, reason, workerTitle }),
|
|
880
|
+
current.lastReport.relayRequestId,
|
|
881
|
+
'queue',
|
|
882
|
+
AbortSignal.timeout(PROMPT_TIMEOUT_MS),
|
|
883
|
+
)
|
|
884
|
+
} catch (error) {
|
|
885
|
+
current.lastReport.deliveryError = String(error instanceof Error ? error.message : error)
|
|
886
|
+
await persist(current)
|
|
887
|
+
ctx.logger.warn(`collab-pair: delivering round ${pending.round} for ${current.worker} to the manager failed: ${String(error)}`)
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
|
|
891
|
+
/** Serialize relays per link so one turn cannot relay twice. */
|
|
892
|
+
function enqueueRelay(linkId, run) {
|
|
893
|
+
const previous = relays.get(linkId) ?? Promise.resolve()
|
|
894
|
+
const next = previous.then(run, run).catch((error) => {
|
|
895
|
+
ctx.logger.warn(`collab-pair: relay for ${linkId} failed: ${String(error)}`)
|
|
896
|
+
})
|
|
897
|
+
relays.set(linkId, next)
|
|
898
|
+
void next.finally(() => {
|
|
899
|
+
if (relays.get(linkId) === next) relays.delete(linkId)
|
|
900
|
+
})
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
/** Read the events of one completed turn. */
|
|
904
|
+
function turnEvents(session, turn, endSeq) {
|
|
905
|
+
const events = session.ownEvents()
|
|
906
|
+
let start = -1
|
|
907
|
+
for (const event of events) {
|
|
908
|
+
if (event.seq >= endSeq) break
|
|
909
|
+
if (event.type === 'turn/start' && event.data?.turn === turn) start = event.seq
|
|
910
|
+
}
|
|
911
|
+
if (start < 0) return undefined
|
|
912
|
+
return events.filter((event) => event.seq > start && event.seq <= endSeq)
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
/** Whether this turn is the one that claimed our dispatch prompt. */
|
|
916
|
+
function claimedBy(events, pending) {
|
|
917
|
+
const marker = `[[collab:${pending.linkId}:r${pending.round}]]`
|
|
918
|
+
for (const event of events) {
|
|
919
|
+
if (event.type !== 'user/message') continue
|
|
920
|
+
if (event.data?.source?.rpcId === pending.requestId) return true
|
|
921
|
+
if (messageText(event.data).includes(marker)) return true
|
|
922
|
+
}
|
|
923
|
+
return false
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
/** Structured report from a `collab_report` tool call inside the turn. */
|
|
927
|
+
function reportFrom(events) {
|
|
928
|
+
for (let index = events.length - 1; index >= 0; index--) {
|
|
929
|
+
const event = events[index]
|
|
930
|
+
if (event.type !== 'tool/call' || event.data?.name !== 'collab_report') continue
|
|
931
|
+
try {
|
|
932
|
+
const parsed = JSON.parse(event.data.arguments)
|
|
933
|
+
if (parsed === null || typeof parsed !== 'object' || typeof parsed.summary !== 'string') continue
|
|
934
|
+
return {
|
|
935
|
+
summary: parsed.summary,
|
|
936
|
+
status: REPORTS.has(parsed.status) ? parsed.status : 'partial',
|
|
937
|
+
details: typeof parsed.details === 'string' ? parsed.details : '',
|
|
938
|
+
next: typeof parsed.next === 'string' ? parsed.next : '',
|
|
939
|
+
reportedAt: event.time ?? Date.now(),
|
|
940
|
+
}
|
|
941
|
+
} catch {
|
|
942
|
+
// A malformed call leaves the final message as the only report.
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
return undefined
|
|
946
|
+
}
|
|
947
|
+
|
|
948
|
+
/** Last non-empty assistant text of one turn. */
|
|
949
|
+
function lastAssistantText(events) {
|
|
950
|
+
for (let index = events.length - 1; index >= 0; index--) {
|
|
951
|
+
const event = events[index]
|
|
952
|
+
if (event.type !== 'assistant/message') continue
|
|
953
|
+
const text = messageText(event.data)
|
|
954
|
+
if (text !== '') return text
|
|
955
|
+
}
|
|
956
|
+
return ''
|
|
957
|
+
}
|
|
958
|
+
|
|
959
|
+
/** Global post-commit listener: relay a worker turn that answered a dispatch. */
|
|
960
|
+
function onSessionEvent(session, event) {
|
|
961
|
+
if (event?.type !== 'turn/end') return
|
|
962
|
+
const linkId = byWorker.get(session.id)
|
|
963
|
+
if (linkId === undefined) return
|
|
964
|
+
const link = links.get(linkId)
|
|
965
|
+
if (link === undefined || link.status !== ACTIVE) return
|
|
966
|
+
const pending = link.pending
|
|
967
|
+
if (pending === null) return
|
|
968
|
+
const turn = event.data?.turn
|
|
969
|
+
if (!Number.isSafeInteger(turn)) return
|
|
970
|
+
let events
|
|
971
|
+
try {
|
|
972
|
+
events = turnEvents(session, turn, event.seq)
|
|
973
|
+
} catch (error) {
|
|
974
|
+
ctx.logger.warn(`collab-pair: reading the finished turn failed: ${String(error)}`)
|
|
975
|
+
return
|
|
976
|
+
}
|
|
977
|
+
if (events === undefined) return
|
|
978
|
+
if (!claimedBy(events, { ...pending, linkId: link.id })) return
|
|
979
|
+
const snapshot = { ...pending }
|
|
980
|
+
enqueueRelay(link.id, () => relayReport(link, snapshot, events, event.data?.reason))
|
|
981
|
+
}
|
|
982
|
+
|
|
983
|
+
// ------------------------------------------------------------------- tools
|
|
984
|
+
|
|
985
|
+
/** Register the collaboration tools. */
|
|
986
|
+
function registerTools() {
|
|
987
|
+
toolExecutors.sessions = register({
|
|
988
|
+
name: 'collab_sessions',
|
|
989
|
+
description:
|
|
990
|
+
'列出本机最近的对话(sessionId、标题、活跃时间、是否已加入协作),用于挑选协作对象。当用户要求把当前对话和另一个对话关联时先调用它;可用 query 按标题关键词过滤。',
|
|
991
|
+
parameters: {
|
|
992
|
+
type: 'object',
|
|
993
|
+
properties: {
|
|
994
|
+
query: { type: 'string', description: '可选:按标题关键词过滤。' },
|
|
995
|
+
limit: { type: 'number', description: '可选:最多返回多少条,默认 12,最大 40。' },
|
|
996
|
+
},
|
|
997
|
+
},
|
|
998
|
+
async execute(args, exec) {
|
|
999
|
+
const agent = requireAgent(exec)
|
|
1000
|
+
const limit = clampInt(args?.limit, 1, 40, 12)
|
|
1001
|
+
const query = typeof args?.query === 'string' ? args.query.trim().toLowerCase() : ''
|
|
1002
|
+
let rows = []
|
|
1003
|
+
try {
|
|
1004
|
+
rows = await candidateSessions(exec.signal)
|
|
1005
|
+
} catch (error) {
|
|
1006
|
+
throw new CollabError(`读取对话列表失败:${String(error instanceof Error ? error.message : error)}`)
|
|
1007
|
+
}
|
|
1008
|
+
const sessions = rows
|
|
1009
|
+
.filter((row) => row.sessionId !== agent.id)
|
|
1010
|
+
.filter((row) => query === '' || (row.title ?? '').toLowerCase().includes(query) || row.sessionId.toLowerCase().includes(query))
|
|
1011
|
+
.slice(0, limit)
|
|
1012
|
+
.map((row) => {
|
|
1013
|
+
const worker = workerLink(row.sessionId)
|
|
1014
|
+
const managed = managerLinks(row.sessionId, true)
|
|
1015
|
+
return {
|
|
1016
|
+
sessionId: row.sessionId,
|
|
1017
|
+
title: row.title ?? null,
|
|
1018
|
+
updatedAt: isoTime(row.updatedAt),
|
|
1019
|
+
running: row.running === true,
|
|
1020
|
+
linked: worker !== undefined
|
|
1021
|
+
? { role: 'worker', linkId: worker.id, status: worker.status }
|
|
1022
|
+
: managed.length > 0
|
|
1023
|
+
? { role: 'manager', workers: managed.length }
|
|
1024
|
+
: false,
|
|
1025
|
+
}
|
|
1026
|
+
})
|
|
1027
|
+
return {
|
|
1028
|
+
ok: true,
|
|
1029
|
+
current: {
|
|
1030
|
+
sessionId: agent.id,
|
|
1031
|
+
role: managerLinks(agent.id, true).length > 0 ? 'manager' : workerLink(agent.id) === undefined ? null : 'worker',
|
|
1032
|
+
},
|
|
1033
|
+
sessions,
|
|
1034
|
+
note: sessions.length === 0
|
|
1035
|
+
? '没有可关联的对话;可以用 collab_link 传 peer="new" 新建一个员工对话。'
|
|
1036
|
+
: '把选中的 sessionId 传给 collab_link 的 peer 参数即可关联。',
|
|
1037
|
+
}
|
|
1038
|
+
},
|
|
1039
|
+
})
|
|
1040
|
+
|
|
1041
|
+
toolExecutors.link = register({
|
|
1042
|
+
name: 'collab_link',
|
|
1043
|
+
description:
|
|
1044
|
+
'把当前对话与另一个对话关联:role=manager(默认)表示当前对话是项目经理、对方成为新的员工;一个项目经理可以关联多个员工。role=worker 表示当前对话成为对方的员工。peer 传 sessionId、标题关键词,或 "new"(新建一个员工对话)。',
|
|
1045
|
+
parameters: {
|
|
1046
|
+
type: 'object',
|
|
1047
|
+
properties: {
|
|
1048
|
+
peer: { type: 'string', description: 'sessionId、标题关键词,或 "new"。' },
|
|
1049
|
+
role: { type: 'string', enum: ['manager', 'worker'], description: '当前对话的角色,默认 manager。' },
|
|
1050
|
+
goal: { type: 'string', description: '可选:项目总目标;不填时由项目经理在对话中掌握。' },
|
|
1051
|
+
task: { type: 'string', description: '可选:关联成功后立即派发给该员工的第一轮任务。' },
|
|
1052
|
+
acceptance: { type: 'string', description: '可选:第一轮任务的验收标准。' },
|
|
1053
|
+
cwd: { type: 'string', description: '可选:peer="new" 时新对话的工作目录,默认与当前对话相同。' },
|
|
1054
|
+
},
|
|
1055
|
+
required: ['peer'],
|
|
1056
|
+
},
|
|
1057
|
+
async execute(args, exec) {
|
|
1058
|
+
const agent = requireAgent(exec)
|
|
1059
|
+
const role = args?.role === 'worker' ? 'worker' : 'manager'
|
|
1060
|
+
const managed = managerLinks(agent.id, true)
|
|
1061
|
+
const ownWorker = workerLink(agent.id)
|
|
1062
|
+
if (ownWorker !== undefined) {
|
|
1063
|
+
throw new CollabError(`当前对话已经是协作 ${ownWorker.id} 的员工,不能再加入其他协作;请先 collab_unlink。`)
|
|
1064
|
+
}
|
|
1065
|
+
if (role === 'worker' && managed.length > 0) {
|
|
1066
|
+
throw new CollabError(`当前对话正在管理 ${managed.length} 个员工,不能同时作为别人的员工。`)
|
|
1067
|
+
}
|
|
1068
|
+
const goal = typeof args?.goal === 'string' ? args.goal.trim() : ''
|
|
1069
|
+
let peerId
|
|
1070
|
+
let peerTitle
|
|
1071
|
+
const resolved = await resolvePeer(args?.peer, exec.signal)
|
|
1072
|
+
if (resolved.kind === 'new') {
|
|
1073
|
+
peerId = await createWorkerSession(agent.id, args?.cwd, exec.signal)
|
|
1074
|
+
} else {
|
|
1075
|
+
peerId = resolved.sessionId
|
|
1076
|
+
peerTitle = resolved.title
|
|
1077
|
+
}
|
|
1078
|
+
if (peerId === agent.id) throw new CollabError('不能把对话与它自己关联。')
|
|
1079
|
+
if (workerLink(peerId) !== undefined) {
|
|
1080
|
+
throw new CollabError(`目标对话 ${peerId} 已经是另一个协作的员工,请先解除那边的关联。`)
|
|
1081
|
+
}
|
|
1082
|
+
if (managerLinks(peerId, true).length > 0) {
|
|
1083
|
+
throw new CollabError(`目标对话 ${peerId} 正在管理其他员工,不能再担任员工或其他角色。`)
|
|
1084
|
+
}
|
|
1085
|
+
const manager = role === 'manager' ? agent.id : peerId
|
|
1086
|
+
const worker = role === 'manager' ? peerId : agent.id
|
|
1087
|
+
const link = {
|
|
1088
|
+
v: 1,
|
|
1089
|
+
id: `cp-${randomUUID().slice(0, 8)}`,
|
|
1090
|
+
manager,
|
|
1091
|
+
worker,
|
|
1092
|
+
label: role === 'manager' ? (typeof peerTitle === 'string' ? peerTitle : '') : '',
|
|
1093
|
+
goal,
|
|
1094
|
+
status: ACTIVE,
|
|
1095
|
+
round: 0,
|
|
1096
|
+
pending: null,
|
|
1097
|
+
lastReport: null,
|
|
1098
|
+
history: [],
|
|
1099
|
+
createdAt: Date.now(),
|
|
1100
|
+
updatedAt: Date.now(),
|
|
1101
|
+
}
|
|
1102
|
+
index(link)
|
|
1103
|
+
await persist(link)
|
|
1104
|
+
await applyPrefix(manager, cfg.prefixManager)
|
|
1105
|
+
await applyPrefix(worker, cfg.prefixWorker)
|
|
1106
|
+
let receipt = null
|
|
1107
|
+
const task = typeof args?.task === 'string' ? args.task.trim() : ''
|
|
1108
|
+
if (task !== '' && role === 'manager') {
|
|
1109
|
+
const acceptance = typeof args?.acceptance === 'string' ? args.acceptance.trim() : ''
|
|
1110
|
+
const sent = await dispatchRound(link, task, acceptance, exec.signal, false)
|
|
1111
|
+
receipt = { round: sent.round, dispatched: true }
|
|
1112
|
+
}
|
|
1113
|
+
let workerTitle = role === 'manager' ? (peerTitle ?? await titleOf(worker)) : await titleOf(worker)
|
|
1114
|
+
const prefixedTitle = await titleOf(worker)
|
|
1115
|
+
if (typeof prefixedTitle === 'string' && prefixedTitle !== '') workerTitle = prefixedTitle
|
|
1116
|
+
if (typeof workerTitle === 'string' && workerTitle !== link.label) {
|
|
1117
|
+
link.label = workerTitle
|
|
1118
|
+
await persist(link)
|
|
1119
|
+
}
|
|
1120
|
+
const managedNow = managerLinks(agent.id, true).length
|
|
1121
|
+
return {
|
|
1122
|
+
ok: true,
|
|
1123
|
+
linkId: link.id,
|
|
1124
|
+
role,
|
|
1125
|
+
manager,
|
|
1126
|
+
worker: { sessionId: worker, title: workerTitle ?? null },
|
|
1127
|
+
goal,
|
|
1128
|
+
round: link.round,
|
|
1129
|
+
receipt,
|
|
1130
|
+
message: role === 'manager'
|
|
1131
|
+
? (receipt === null
|
|
1132
|
+
? `已关联员工 ${worker}${managedNow > 1 ? `(当前共 ${managedNow} 个员工)` : ''}。用 collab_dispatch 派发任务。`
|
|
1133
|
+
: `已关联员工 ${worker}${managedNow > 1 ? `(当前共 ${managedNow} 个员工)` : ''},第一轮任务已派发。`)
|
|
1134
|
+
: '协作已建立,你被设为员工角色;项目经理派发任务后会收到【协作任务】消息。',
|
|
1135
|
+
}
|
|
1136
|
+
},
|
|
1137
|
+
})
|
|
1138
|
+
|
|
1139
|
+
toolExecutors.dispatch = register({
|
|
1140
|
+
name: 'collab_dispatch',
|
|
1141
|
+
description:
|
|
1142
|
+
'(仅项目经理)把本轮任务发给某个员工对话并立即返回。有多个员工时用 worker 指定(sessionId 或标题);只有一个员工时可省略。员工完成后产出与反馈会自动回到本对话。该员工上一轮尚未回报时不要重复派发(需要覆盖传 force=true)。',
|
|
1143
|
+
parameters: {
|
|
1144
|
+
type: 'object',
|
|
1145
|
+
properties: {
|
|
1146
|
+
task: { type: 'string', description: '本轮要员工完成的任务,写清目标、范围和交付物。' },
|
|
1147
|
+
worker: { type: 'string', description: '可选:目标员工的 sessionId 或标题关键词;只有一个员工时可省略。' },
|
|
1148
|
+
acceptance: { type: 'string', description: '可选:本轮验收标准。' },
|
|
1149
|
+
force: { type: 'boolean', description: '可选:该员工上一轮尚未回报时强制覆盖派发。' },
|
|
1150
|
+
},
|
|
1151
|
+
required: ['task'],
|
|
1152
|
+
},
|
|
1153
|
+
async execute(args, exec) {
|
|
1154
|
+
const agent = requireAgent(exec)
|
|
1155
|
+
const link = resolveManagedLink(agent.id, args?.worker)
|
|
1156
|
+
const task = typeof args?.task === 'string' ? args.task.trim() : ''
|
|
1157
|
+
if (task === '') throw new CollabError('task 不能为空。')
|
|
1158
|
+
const acceptance = typeof args?.acceptance === 'string' ? args.acceptance.trim() : ''
|
|
1159
|
+
const sent = await dispatchRound(link, task, acceptance, exec.signal, args?.force === true)
|
|
1160
|
+
return {
|
|
1161
|
+
ok: true,
|
|
1162
|
+
linkId: link.id,
|
|
1163
|
+
round: sent.round,
|
|
1164
|
+
worker: link.worker,
|
|
1165
|
+
message: `第 ${sent.round} 轮任务已派发给员工 ${link.worker}。该员工完成后,产出与反馈会自动作为用户消息回到本对话。`,
|
|
1166
|
+
}
|
|
1167
|
+
},
|
|
1168
|
+
when: ({ agent }) => managerLinks(agent.id, true).length > 0,
|
|
1169
|
+
})
|
|
1170
|
+
|
|
1171
|
+
toolExecutors.report = register({
|
|
1172
|
+
name: 'collab_report',
|
|
1173
|
+
description:
|
|
1174
|
+
'(仅员工)向插件汇报本轮任务结果:summary 是交付物/结论摘要,status 取 done(完成)、partial(部分完成)、blocked(受阻需决策),details 写细节,next 写建议。调用后结束本轮回复,插件会把汇报与你的最终产出一起回传给项目经理。',
|
|
1175
|
+
parameters: {
|
|
1176
|
+
type: 'object',
|
|
1177
|
+
properties: {
|
|
1178
|
+
summary: { type: 'string', description: '交付物或结论摘要。' },
|
|
1179
|
+
status: { type: 'string', enum: ['done', 'partial', 'blocked'], description: '本轮状态。' },
|
|
1180
|
+
details: { type: 'string', description: '可选:细节、改动、验证结果。' },
|
|
1181
|
+
next: { type: 'string', description: '可选:给项目经理的建议或下一步。' },
|
|
1182
|
+
},
|
|
1183
|
+
required: ['summary', 'status'],
|
|
1184
|
+
},
|
|
1185
|
+
async execute(args, exec) {
|
|
1186
|
+
const agent = requireAgent(exec)
|
|
1187
|
+
const link = workerLink(agent.id)
|
|
1188
|
+
if (link === undefined) throw new CollabError('当前对话没有进行中的协作任务;你还没有被分配任务。')
|
|
1189
|
+
if (link.pending === null) throw new CollabError('当前没有等待回报的任务;汇报会在下一轮任务派发后生效。')
|
|
1190
|
+
const summary = typeof args?.summary === 'string' ? args.summary.trim() : ''
|
|
1191
|
+
if (summary === '') throw new CollabError('summary 不能为空。')
|
|
1192
|
+
const status = REPORTS.has(args?.status) ? args.status : 'partial'
|
|
1193
|
+
link.pending.report = {
|
|
1194
|
+
summary,
|
|
1195
|
+
status,
|
|
1196
|
+
details: typeof args?.details === 'string' ? args.details.trim() : '',
|
|
1197
|
+
next: typeof args?.next === 'string' ? args.next.trim() : '',
|
|
1198
|
+
reportedAt: Date.now(),
|
|
1199
|
+
}
|
|
1200
|
+
link.updatedAt = Date.now()
|
|
1201
|
+
await persist(link)
|
|
1202
|
+
return {
|
|
1203
|
+
ok: true,
|
|
1204
|
+
round: link.pending.round,
|
|
1205
|
+
status,
|
|
1206
|
+
message: '汇报已记录。请结束本轮回复;插件会把这份汇报与你的最终产出一起回传给项目经理。',
|
|
1207
|
+
}
|
|
1208
|
+
},
|
|
1209
|
+
when: ({ agent }) => workerLink(agent.id) !== undefined,
|
|
1210
|
+
})
|
|
1211
|
+
|
|
1212
|
+
toolExecutors.status = register({
|
|
1213
|
+
name: 'collab_status',
|
|
1214
|
+
description:
|
|
1215
|
+
'查看协作状态:项目经理能看到所有员工(轮次、待回报任务、最近回报);员工能看到自己的项目经理与当前任务。',
|
|
1216
|
+
parameters: { type: 'object', properties: {} },
|
|
1217
|
+
async execute(_args, exec) {
|
|
1218
|
+
const agent = requireAgent(exec)
|
|
1219
|
+
const managed = managerLinks(agent.id)
|
|
1220
|
+
const active = managed.filter((link) => link.status === ACTIVE)
|
|
1221
|
+
if (active.length > 0) {
|
|
1222
|
+
const workers = []
|
|
1223
|
+
for (const link of managed) {
|
|
1224
|
+
const title = await titleOf(link.worker)
|
|
1225
|
+
if (title !== undefined && title !== link.label) link.label = title
|
|
1226
|
+
workers.push({
|
|
1227
|
+
linkId: link.id,
|
|
1228
|
+
worker: link.worker,
|
|
1229
|
+
title: title ?? (link.label || null),
|
|
1230
|
+
status: link.status,
|
|
1231
|
+
round: link.round,
|
|
1232
|
+
pending: link.pending === null
|
|
1233
|
+
? null
|
|
1234
|
+
: {
|
|
1235
|
+
round: link.pending.round,
|
|
1236
|
+
task: clip(link.pending.task, 1200),
|
|
1237
|
+
acceptance: link.pending.acceptance || null,
|
|
1238
|
+
dispatchedAt: isoTime(link.pending.dispatchedAt),
|
|
1239
|
+
waitedSeconds: Math.max(0, Math.round((Date.now() - link.pending.dispatchedAt) / 1000)),
|
|
1240
|
+
reported: link.pending.report !== null,
|
|
1241
|
+
},
|
|
1242
|
+
lastReport: link.lastReport === null
|
|
1243
|
+
? null
|
|
1244
|
+
: {
|
|
1245
|
+
round: link.lastReport.round,
|
|
1246
|
+
status: link.lastReport.status,
|
|
1247
|
+
summary: link.lastReport.summary,
|
|
1248
|
+
details: link.lastReport.details,
|
|
1249
|
+
next: link.lastReport.next,
|
|
1250
|
+
turnReason: link.lastReport.turnReason,
|
|
1251
|
+
relayedAt: link.lastReport.relayedAt,
|
|
1252
|
+
...(link.lastReport.deliveryError === undefined ? {} : { deliveryError: link.lastReport.deliveryError }),
|
|
1253
|
+
},
|
|
1254
|
+
history: link.history,
|
|
1255
|
+
})
|
|
1256
|
+
}
|
|
1257
|
+
return {
|
|
1258
|
+
linked: true,
|
|
1259
|
+
storage: storageState,
|
|
1260
|
+
...(storageError === null ? {} : { storageError }),
|
|
1261
|
+
engine: ENGINE,
|
|
1262
|
+
role: 'manager',
|
|
1263
|
+
manager: { sessionId: agent.id, title: (await titleOf(agent.id)) ?? null },
|
|
1264
|
+
maxRounds: cfg.maxRounds,
|
|
1265
|
+
activeCount: active.length,
|
|
1266
|
+
totalCount: managed.length,
|
|
1267
|
+
workers,
|
|
1268
|
+
}
|
|
1269
|
+
}
|
|
1270
|
+
const link = workerLink(agent.id)
|
|
1271
|
+
if (link === undefined) {
|
|
1272
|
+
return {
|
|
1273
|
+
linked: false,
|
|
1274
|
+
storage: storageState,
|
|
1275
|
+
...(storageError === null ? {} : { storageError }),
|
|
1276
|
+
engine: ENGINE,
|
|
1277
|
+
hint: '当前对话没有协作关联。用 collab_sessions 查看可关联的对话,再用 collab_link 建立关联(peer="new" 可新建员工对话)。',
|
|
1278
|
+
}
|
|
1279
|
+
}
|
|
1280
|
+
const managerTitle = await titleOf(link.manager)
|
|
1281
|
+
return {
|
|
1282
|
+
linked: true,
|
|
1283
|
+
storage: storageState,
|
|
1284
|
+
...(storageError === null ? {} : { storageError }),
|
|
1285
|
+
engine: ENGINE,
|
|
1286
|
+
linkId: link.id,
|
|
1287
|
+
role: 'worker',
|
|
1288
|
+
manager: { sessionId: link.manager, title: managerTitle ?? null },
|
|
1289
|
+
goal: link.goal || null,
|
|
1290
|
+
status: link.status,
|
|
1291
|
+
round: link.round,
|
|
1292
|
+
maxRounds: cfg.maxRounds,
|
|
1293
|
+
pending: link.pending === null
|
|
1294
|
+
? null
|
|
1295
|
+
: {
|
|
1296
|
+
round: link.pending.round,
|
|
1297
|
+
task: clip(link.pending.task, 1200),
|
|
1298
|
+
acceptance: link.pending.acceptance || null,
|
|
1299
|
+
dispatchedAt: isoTime(link.pending.dispatchedAt),
|
|
1300
|
+
reported: link.pending.report !== null,
|
|
1301
|
+
},
|
|
1302
|
+
lastReport: link.lastReport,
|
|
1303
|
+
history: link.history,
|
|
1304
|
+
}
|
|
1305
|
+
},
|
|
1306
|
+
})
|
|
1307
|
+
|
|
1308
|
+
toolExecutors.configure = register({
|
|
1309
|
+
name: 'collab_configure',
|
|
1310
|
+
description:
|
|
1311
|
+
'(仅项目经理)配置某个员工的 agent 预设或模型,不用切到员工对话。只传 worker 时返回可选预设;传 preset 设置预设;传 provider+model 设置模型。有多个员工时用 worker 指定。',
|
|
1312
|
+
parameters: {
|
|
1313
|
+
type: 'object',
|
|
1314
|
+
properties: {
|
|
1315
|
+
worker: { type: 'string', description: '可选:员工 sessionId 或标题;只有一个员工时可省略。' },
|
|
1316
|
+
preset: { type: 'string', description: '可选:agent 预设 id(如 standard / ptc / minimal)。' },
|
|
1317
|
+
provider: { type: 'string', description: '可选:模型供应商 id(配合 model)。' },
|
|
1318
|
+
model: { type: 'string', description: '可选:模型 id。' },
|
|
1319
|
+
reasoningEffort: { type: 'string', description: '可选:推理强度。' },
|
|
1320
|
+
},
|
|
1321
|
+
},
|
|
1322
|
+
async execute(args, exec) {
|
|
1323
|
+
const agent = requireAgent(exec)
|
|
1324
|
+
const link = resolveManagedLink(agent.id, args?.worker)
|
|
1325
|
+
const presetId = typeof args?.preset === 'string' ? args.preset.trim() : ''
|
|
1326
|
+
const modelId = typeof args?.model === 'string' ? args.model.trim() : ''
|
|
1327
|
+
const providerId = typeof args?.provider === 'string' ? args.provider.trim() : ''
|
|
1328
|
+
const presets = ctx.get('agentPresets')
|
|
1329
|
+
if (presetId === '' && modelId === '') {
|
|
1330
|
+
const roster = presets === undefined ? [] : await presets.list()
|
|
1331
|
+
return {
|
|
1332
|
+
ok: true,
|
|
1333
|
+
worker: link.worker,
|
|
1334
|
+
presets: roster.map((preset) => preset.id),
|
|
1335
|
+
hint: presets === undefined
|
|
1336
|
+
? '当前环境没有 agentPresets 服务。'
|
|
1337
|
+
: '传 preset 设置代理预设;传 provider+model 设置模型。',
|
|
1338
|
+
}
|
|
1339
|
+
}
|
|
1340
|
+
const configured = []
|
|
1341
|
+
if (presetId !== '') {
|
|
1342
|
+
if (presets === undefined || typeof presets.select !== 'function') throw new CollabError('当前环境没有 agentPresets 服务,无法设置预设。')
|
|
1343
|
+
const roster = await presets.list()
|
|
1344
|
+
const matched = roster.find((preset) => preset.id === presetId) ?? roster.find((preset) => preset.name === presetId)
|
|
1345
|
+
if (matched === undefined) throw new CollabError(`没有预设 "${presetId}";可用:${roster.map((preset) => preset.id).join(' / ')}`)
|
|
1346
|
+
const workerAgent = await resolveWorkerAgent(link.worker)
|
|
1347
|
+
const accepted = await presets.select(workerAgent, matched.id)
|
|
1348
|
+
configured.push({ kind: 'preset', value: accepted })
|
|
1349
|
+
}
|
|
1350
|
+
if (modelId !== '') {
|
|
1351
|
+
if (providerId === '') throw new CollabError('设置模型时还需要 provider。')
|
|
1352
|
+
const controller = ctx.get('sessionController')
|
|
1353
|
+
if (controller === undefined || typeof controller.selectModel !== 'function') throw new CollabError('当前环境缺少 sessionController,无法设置模型。')
|
|
1354
|
+
const effort = typeof args?.reasoningEffort === 'string' ? args.reasoningEffort.trim() : ''
|
|
1355
|
+
const selected = await controller.selectModel({
|
|
1356
|
+
sessionId: link.worker,
|
|
1357
|
+
provider: providerId,
|
|
1358
|
+
model: modelId,
|
|
1359
|
+
...(effort === '' ? {} : { reasoningEffort: effort }),
|
|
1360
|
+
})
|
|
1361
|
+
configured.push({ kind: 'model', value: selected?.selected ?? { provider: providerId, model: modelId } })
|
|
1362
|
+
}
|
|
1363
|
+
link.updatedAt = Date.now()
|
|
1364
|
+
await persist(link)
|
|
1365
|
+
return {
|
|
1366
|
+
ok: true,
|
|
1367
|
+
worker: link.worker,
|
|
1368
|
+
configured,
|
|
1369
|
+
message: '配置已应用;该员工下一轮会按新配置运行。',
|
|
1370
|
+
}
|
|
1371
|
+
},
|
|
1372
|
+
when: ({ agent }) => managerLinks(agent.id, true).length > 0,
|
|
1373
|
+
})
|
|
1374
|
+
|
|
1375
|
+
toolExecutors.done = register({
|
|
1376
|
+
name: 'collab_done',
|
|
1377
|
+
description:
|
|
1378
|
+
'(仅项目经理)宣布某个员工的项目完成:记录总结并结束与该员工的协作。有多个员工时用 worker 指定;all=true 结束全部员工。请在验收通过后调用。',
|
|
1379
|
+
parameters: {
|
|
1380
|
+
type: 'object',
|
|
1381
|
+
properties: {
|
|
1382
|
+
summary: { type: 'string', description: '项目最终总结:交付了什么、在哪里、如何验证。' },
|
|
1383
|
+
worker: { type: 'string', description: '可选:目标员工的 sessionId 或标题关键词。' },
|
|
1384
|
+
all: { type: 'boolean', description: '可选:结束全部进行中的员工协作。' },
|
|
1385
|
+
},
|
|
1386
|
+
required: ['summary'],
|
|
1387
|
+
},
|
|
1388
|
+
async execute(args, exec) {
|
|
1389
|
+
const agent = requireAgent(exec)
|
|
1390
|
+
const active = managerLinks(agent.id, true)
|
|
1391
|
+
if (active.length === 0) throw new CollabError('当前对话没有进行中的员工协作。')
|
|
1392
|
+
const summary = typeof args?.summary === 'string' ? args.summary.trim() : ''
|
|
1393
|
+
if (summary === '') throw new CollabError('summary 不能为空。')
|
|
1394
|
+
let targets
|
|
1395
|
+
if (args?.all === true) {
|
|
1396
|
+
targets = active
|
|
1397
|
+
} else if (typeof args?.worker === 'string' && args.worker.trim() !== '') {
|
|
1398
|
+
targets = [resolveManagedLink(agent.id, args.worker)]
|
|
1399
|
+
} else if (active.length === 1) {
|
|
1400
|
+
targets = [active[0]]
|
|
1401
|
+
} else {
|
|
1402
|
+
throw new CollabError(`当前对话有 ${active.length} 个员工,请用 worker 指定或传 all=true:\n${workerList(active)}`)
|
|
1403
|
+
}
|
|
1404
|
+
const closed = []
|
|
1405
|
+
const notified = []
|
|
1406
|
+
for (const link of targets) {
|
|
1407
|
+
link.status = DONE
|
|
1408
|
+
link.pending = null
|
|
1409
|
+
link.finalSummary = clip(summary, 4000)
|
|
1410
|
+
link.closedAt = Date.now()
|
|
1411
|
+
link.updatedAt = Date.now()
|
|
1412
|
+
index(link)
|
|
1413
|
+
await persist(link)
|
|
1414
|
+
await clearPrefix(link.worker)
|
|
1415
|
+
closed.push({ linkId: link.id, worker: link.worker })
|
|
1416
|
+
if (cfg.notifyWorkerOnDone) {
|
|
1417
|
+
try {
|
|
1418
|
+
await deliver(link.worker, doneText(link, link.finalSummary), `cp-${link.id}-done-to-worker`, 'queue', AbortSignal.timeout(PROMPT_TIMEOUT_MS))
|
|
1419
|
+
notified.push(link.worker)
|
|
1420
|
+
} catch (error) {
|
|
1421
|
+
ctx.logger.warn(`collab-pair: notifying ${link.worker} of completion failed: ${String(error)}`)
|
|
1422
|
+
}
|
|
1423
|
+
}
|
|
1424
|
+
}
|
|
1425
|
+
if (managerLinks(agent.id, true).length === 0) await clearPrefix(agent.id)
|
|
1426
|
+
return {
|
|
1427
|
+
ok: true,
|
|
1428
|
+
closed,
|
|
1429
|
+
workerNotified: notified,
|
|
1430
|
+
message: `已结束 ${closed.length} 个员工协作;历史记录仍保留在 collab_status 中。`,
|
|
1431
|
+
}
|
|
1432
|
+
},
|
|
1433
|
+
when: ({ agent }) => managerLinks(agent.id, true).length > 0,
|
|
1434
|
+
})
|
|
1435
|
+
|
|
1436
|
+
toolExecutors.unlink = register({
|
|
1437
|
+
name: 'collab_unlink',
|
|
1438
|
+
description:
|
|
1439
|
+
'解除并删除协作关联(双方都可调用)。项目经理解除某个员工(多个员工时用 worker 指定,all=true 解除全部);员工调用时解除自己与项目经理的关联。',
|
|
1440
|
+
parameters: {
|
|
1441
|
+
type: 'object',
|
|
1442
|
+
properties: {
|
|
1443
|
+
worker: { type: 'string', description: '可选(项目经理):目标员工的 sessionId 或标题关键词。' },
|
|
1444
|
+
all: { type: 'boolean', description: '可选(项目经理):解除全部员工。' },
|
|
1445
|
+
reason: { type: 'string', description: '可选:解除原因。' },
|
|
1446
|
+
notify: { type: 'boolean', description: '可选:是否通知对方对话(默认 false)。' },
|
|
1447
|
+
},
|
|
1448
|
+
},
|
|
1449
|
+
async execute(args, exec) {
|
|
1450
|
+
const agent = requireAgent(exec)
|
|
1451
|
+
const ownWorker = workerLink(agent.id)
|
|
1452
|
+
if (ownWorker !== undefined) {
|
|
1453
|
+
let notified = false
|
|
1454
|
+
if (args?.notify === true) {
|
|
1455
|
+
const reason = typeof args?.reason === 'string' ? args.reason.trim() : ''
|
|
1456
|
+
try {
|
|
1457
|
+
await deliver(ownWorker.manager, ['【协作结束】', '员工已退出本次协作。', ...(reason === '' ? [] : ['', `原因:${reason}`]), `[[collab:${ownWorker.id}:unlink]]`].join('\n'), `cp-${ownWorker.id}-unlink-to-manager`, 'queue', AbortSignal.timeout(PROMPT_TIMEOUT_MS))
|
|
1458
|
+
notified = true
|
|
1459
|
+
} catch (error) {
|
|
1460
|
+
ctx.logger.warn(`collab-pair: notifying the manager of unlink failed: ${String(error)}`)
|
|
1461
|
+
}
|
|
1462
|
+
}
|
|
1463
|
+
const linkId = ownWorker.id
|
|
1464
|
+
const managerId = ownWorker.manager
|
|
1465
|
+
await forget(ownWorker)
|
|
1466
|
+
await clearPrefix(agent.id)
|
|
1467
|
+
if (managerLinks(managerId, true).length === 0) await clearPrefix(managerId)
|
|
1468
|
+
return { ok: true, removed: [{ linkId, worker: agent.id }], peerNotified: notified }
|
|
1469
|
+
}
|
|
1470
|
+
const active = managerLinks(agent.id, true)
|
|
1471
|
+
if (active.length === 0) throw new CollabError('当前对话没有进行中的员工协作,无需解除。')
|
|
1472
|
+
let targets
|
|
1473
|
+
if (args?.all === true) {
|
|
1474
|
+
targets = active
|
|
1475
|
+
} else if (typeof args?.worker === 'string' && args.worker.trim() !== '') {
|
|
1476
|
+
targets = [resolveManagedLink(agent.id, args.worker)]
|
|
1477
|
+
} else if (active.length === 1) {
|
|
1478
|
+
targets = [active[0]]
|
|
1479
|
+
} else {
|
|
1480
|
+
throw new CollabError(`当前对话有 ${active.length} 个员工,请用 worker 指定或传 all=true:\n${workerList(active)}`)
|
|
1481
|
+
}
|
|
1482
|
+
const removed = []
|
|
1483
|
+
let notified = 0
|
|
1484
|
+
for (const link of targets) {
|
|
1485
|
+
if (args?.notify === true) {
|
|
1486
|
+
const reason = typeof args?.reason === 'string' ? args.reason.trim() : ''
|
|
1487
|
+
try {
|
|
1488
|
+
await deliver(link.worker, ['【协作结束】', '项目经理已解除本次协作。', ...(reason === '' ? [] : ['', `原因:${reason}`]), `[[collab:${link.id}:unlink]]`].join('\n'), `cp-${link.id}-unlink-to-worker`, 'queue', AbortSignal.timeout(PROMPT_TIMEOUT_MS))
|
|
1489
|
+
notified += 1
|
|
1490
|
+
} catch (error) {
|
|
1491
|
+
ctx.logger.warn(`collab-pair: notifying ${link.worker} of unlink failed: ${String(error)}`)
|
|
1492
|
+
}
|
|
1493
|
+
}
|
|
1494
|
+
removed.push({ linkId: link.id, worker: link.worker })
|
|
1495
|
+
await forget(link)
|
|
1496
|
+
await clearPrefix(link.worker)
|
|
1497
|
+
}
|
|
1498
|
+
if (managerLinks(agent.id, true).length === 0) await clearPrefix(agent.id)
|
|
1499
|
+
return { ok: true, removed, peerNotified: notified > 0 }
|
|
1500
|
+
},
|
|
1501
|
+
when: ({ agent }) => managerLinks(agent.id, true).length > 0 || workerLink(agent.id) !== undefined,
|
|
1502
|
+
})
|
|
1503
|
+
}
|
|
1504
|
+
|
|
1505
|
+
/** Whether one session manages at least one active worker. */
|
|
1506
|
+
function isManager(sessionId) {
|
|
1507
|
+
return managerLinks(sessionId, true).length > 0
|
|
1508
|
+
}
|
|
1509
|
+
|
|
1510
|
+
/** Whether one session is an active worker. */
|
|
1511
|
+
function isWorker(sessionId) {
|
|
1512
|
+
return workerLink(sessionId) !== undefined
|
|
1513
|
+
}
|
|
1514
|
+
|
|
1515
|
+
/** Require the calling agent. */
|
|
1516
|
+
function requireAgent(exec) {
|
|
1517
|
+
const agent = exec?.agent
|
|
1518
|
+
if (agent === undefined) throw new CollabError('协作工具只能在对话中调用。')
|
|
1519
|
+
return agent
|
|
1520
|
+
}
|
|
1521
|
+
|
|
1522
|
+
/** Register one tool with canonical JSON output and keep its executor for the command. */
|
|
1523
|
+
function register(tool) {
|
|
1524
|
+
const { when, ...definition } = tool
|
|
1525
|
+
ctx.tools.register({
|
|
1526
|
+
...definition,
|
|
1527
|
+
output: {
|
|
1528
|
+
schema: { type: 'object' },
|
|
1529
|
+
render: (_args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }],
|
|
1530
|
+
},
|
|
1531
|
+
}, when === undefined ? {} : { when })
|
|
1532
|
+
return definition
|
|
1533
|
+
}
|
|
1534
|
+
|
|
1535
|
+
/**
|
|
1536
|
+
* Register `/collab`, the human/UI entry point. Every action reuses the
|
|
1537
|
+
* matching tool executor, so the settings page and the model share one
|
|
1538
|
+
* implementation and one set of role checks.
|
|
1539
|
+
*/
|
|
1540
|
+
function registerCommand() {
|
|
1541
|
+
const actions = {
|
|
1542
|
+
status: 'status',
|
|
1543
|
+
link: 'link',
|
|
1544
|
+
dispatch: 'dispatch',
|
|
1545
|
+
configure: 'configure',
|
|
1546
|
+
done: 'done',
|
|
1547
|
+
unlink: 'unlink',
|
|
1548
|
+
sessions: 'sessions',
|
|
1549
|
+
}
|
|
1550
|
+
ctx.commands.register({
|
|
1551
|
+
name: 'collab',
|
|
1552
|
+
description: '双对话协作:查看全部任务、关联员工、配置预设、派发任务、收尾或解除。',
|
|
1553
|
+
input: {
|
|
1554
|
+
hint: 'tasks | status | link --peer <id|new> | configure --preset <id> | dispatch --worker <id> --task ... | done --worker <id> --summary ... | unlink --worker <id>',
|
|
1555
|
+
},
|
|
1556
|
+
handler: async (invocation) => {
|
|
1557
|
+
try {
|
|
1558
|
+
const { action, args } = parseCommandBody(invocation.rawInput)
|
|
1559
|
+
if (action === 'tasks' || action === 'board') {
|
|
1560
|
+
return { kind: 'success', text: JSON.stringify(await tasksBoard()) }
|
|
1561
|
+
}
|
|
1562
|
+
const key = actions[action]
|
|
1563
|
+
const executor = key === undefined ? undefined : toolExecutors[key]
|
|
1564
|
+
if (executor === undefined) {
|
|
1565
|
+
return { kind: 'error', text: `未知操作 "${action}";可用:${Object.keys(actions).join(' / ')}` }
|
|
1566
|
+
}
|
|
1567
|
+
const value = await executor.execute(args, { agent: invocation.agent, signal: invocation.signal })
|
|
1568
|
+
return { kind: 'success', text: JSON.stringify(compactCommandValue(key, value)) }
|
|
1569
|
+
} catch (error) {
|
|
1570
|
+
return { kind: 'error', text: error instanceof Error ? error.message : String(error) }
|
|
1571
|
+
}
|
|
1572
|
+
},
|
|
1573
|
+
})
|
|
1574
|
+
}
|
|
1575
|
+
|
|
1576
|
+
/** Keep command results out of the session log's long-form fields. */
|
|
1577
|
+
function compactCommandValue(key, value) {
|
|
1578
|
+
if (key !== 'status' || value === null || typeof value !== 'object' || value.linked !== true) return value
|
|
1579
|
+
if (value.role === 'manager' && Array.isArray(value.workers)) {
|
|
1580
|
+
return {
|
|
1581
|
+
...value,
|
|
1582
|
+
workers: value.workers.map((worker) => ({
|
|
1583
|
+
...worker,
|
|
1584
|
+
lastReport: worker.lastReport === null ? null : {
|
|
1585
|
+
round: worker.lastReport.round,
|
|
1586
|
+
status: worker.lastReport.status,
|
|
1587
|
+
summary: worker.lastReport.summary,
|
|
1588
|
+
turnReason: worker.lastReport.turnReason,
|
|
1589
|
+
relayedAt: worker.lastReport.relayedAt,
|
|
1590
|
+
...(worker.lastReport.deliveryError === undefined ? {} : { deliveryError: worker.lastReport.deliveryError }),
|
|
1591
|
+
},
|
|
1592
|
+
history: Array.isArray(worker.history) ? worker.history.slice(-3) : [],
|
|
1593
|
+
})),
|
|
1594
|
+
}
|
|
1595
|
+
}
|
|
1596
|
+
const { lastReport, ...rest } = value
|
|
1597
|
+
if (lastReport === null || typeof lastReport !== 'object') return { ...rest, lastReport: lastReport ?? null }
|
|
1598
|
+
return {
|
|
1599
|
+
...rest,
|
|
1600
|
+
lastReport: {
|
|
1601
|
+
round: lastReport.round,
|
|
1602
|
+
status: lastReport.status,
|
|
1603
|
+
summary: lastReport.summary,
|
|
1604
|
+
details: lastReport.details,
|
|
1605
|
+
next: lastReport.next,
|
|
1606
|
+
turnReason: lastReport.turnReason,
|
|
1607
|
+
relayedAt: lastReport.relayedAt,
|
|
1608
|
+
...(lastReport.deliveryError === undefined ? {} : { deliveryError: lastReport.deliveryError }),
|
|
1609
|
+
},
|
|
1610
|
+
}
|
|
1611
|
+
}
|
|
1612
|
+
}
|