dsh-agent-control-center 0.2.0 → 0.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 +45 -0
- package/README.md +6 -4
- package/README.zh.md +6 -4
- package/client.js +1997 -147
- package/docs/01-CONTRACT.md +1 -1
- package/docs/05-ACCEPTANCE-EVIDENCE.md +39 -0
- package/docs/07-GUIDE.md +1 -1
- package/docs/09-ARCHITECTURE.md +2 -2
- package/index.js +3 -1
- package/lib/modules/a-agents.js +90 -0
- package/lib/modules/j-instruction.js +624 -0
- package/lib/modules/k-export.js +540 -0
- package/package.json +1 -1
- package/scripts/verify.mjs +2 -0
- package/src/client/app.js +91 -3
- package/src/client/i18n/common.js +6 -0
- package/src/client/i18n/export.js +174 -0
- package/src/client/i18n/instruction.js +236 -0
- package/src/client/kernel.js +13 -0
- package/src/client/pages/agents.js +1 -0
- package/src/client/pages/diagnostics.js +1 -0
- package/src/client/pages/export.js +664 -0
- package/src/client/pages/instruction.js +648 -0
- package/src/client/pages/meta.js +1 -0
- package/src/client/pages/overview.js +1 -0
- package/src/client/pages/recovery.js +1 -0
- package/src/client/pages/sessions.js +1 -0
- package/src/client/pages/templates.js +1 -0
- package/src/client/pages/tools.js +1 -0
- package/src/client/pages/usage.js +1 -0
|
@@ -0,0 +1,540 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* K · Read-only session export — turns one recorded session into text the user
|
|
3
|
+
* can take away (Markdown or JSON). It never writes, deletes, archives or
|
|
4
|
+
* resumes anything: the only inputs are the host's own session-query records,
|
|
5
|
+
* and the only output is a response body.
|
|
6
|
+
*
|
|
7
|
+
* Rendering rules:
|
|
8
|
+
* - events are appended one at a time and the export stops **before** an event
|
|
9
|
+
* that would push the response past `maxBytes`, so a truncated export never
|
|
10
|
+
* contains a half-written event;
|
|
11
|
+
* - tool results keep their `isError` flag and a bounded preview, not the raw
|
|
12
|
+
* payload, and the token counters come from the host's `usage`, never a guess;
|
|
13
|
+
* - fences inside a message are escaped so the Markdown cannot be broken by
|
|
14
|
+
* content the model or a tool produced.
|
|
15
|
+
*
|
|
16
|
+
* @module dsh-agent-control-center/modules/export
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
/** Default response budget for one export. */
|
|
20
|
+
const DEFAULT_MAX_BYTES = 256 * 1024
|
|
21
|
+
/** Hard ceiling, whatever the caller asks for. */
|
|
22
|
+
const MAX_MAX_BYTES = 1024 * 1024
|
|
23
|
+
/** Sibling calls share one deadline so a slow host cannot hang the page. */
|
|
24
|
+
const SIBLING_TIMEOUT_MS = 5000
|
|
25
|
+
/** Longest single text block kept verbatim before it is clipped. */
|
|
26
|
+
const MAX_BLOCK_CHARS = 8192
|
|
27
|
+
/** Tool arguments are shown clipped; their bodies can be enormous. */
|
|
28
|
+
const MAX_ARGUMENT_CHARS = 400
|
|
29
|
+
/** Tool result preview length. */
|
|
30
|
+
const MAX_RESULT_CHARS = 600
|
|
31
|
+
const MAX_TITLE_CHARS = 200
|
|
32
|
+
const MAX_SESSIONS = 200
|
|
33
|
+
const FORMATS = Object.freeze(['markdown', 'json'])
|
|
34
|
+
|
|
35
|
+
const SIBLING_TIMEOUT = Symbol('sibling-timeout')
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* @param {unknown} value
|
|
39
|
+
* @returns {string}
|
|
40
|
+
*/
|
|
41
|
+
function text(value) {
|
|
42
|
+
return typeof value === 'string' ? value : ''
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* @param {unknown} value
|
|
47
|
+
* @returns {boolean}
|
|
48
|
+
*/
|
|
49
|
+
function plainObject(value) {
|
|
50
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* @param {unknown} value
|
|
55
|
+
* @returns {number | null}
|
|
56
|
+
*/
|
|
57
|
+
function finiteNumber(value) {
|
|
58
|
+
return typeof value === 'number' && Number.isFinite(value) ? value : null
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** @param {unknown} error @returns {string} */
|
|
62
|
+
function errorMessage(error) {
|
|
63
|
+
if (plainObject(error) && typeof /** @type {Record<string, unknown>} */ (error).message === 'string') {
|
|
64
|
+
return /** @type {string} */ (/** @type {Record<string, unknown>} */ (error).message)
|
|
65
|
+
}
|
|
66
|
+
return String(error)
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** @param {number} value @returns {string} */
|
|
70
|
+
function isoTime(value) {
|
|
71
|
+
try {
|
|
72
|
+
return new Date(value).toISOString()
|
|
73
|
+
} catch {
|
|
74
|
+
return 'invalid-date'
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Flatten one message's `content` into plain text. Content blocks are the
|
|
80
|
+
* model-facing representation; non-text blocks are named instead of dropped so
|
|
81
|
+
* an export never silently loses an attachment.
|
|
82
|
+
* @param {unknown} content
|
|
83
|
+
* @returns {string}
|
|
84
|
+
*/
|
|
85
|
+
function contentText(content) {
|
|
86
|
+
if (typeof content === 'string') return content
|
|
87
|
+
if (!Array.isArray(content)) return ''
|
|
88
|
+
/** @type {string[]} */
|
|
89
|
+
const parts = []
|
|
90
|
+
for (const block of content) {
|
|
91
|
+
if (!plainObject(block)) continue
|
|
92
|
+
const type = text(/** @type {Record<string, unknown>} */ (block).type)
|
|
93
|
+
if (type === 'text') {
|
|
94
|
+
parts.push(text(/** @type {Record<string, unknown>} */ (block).text))
|
|
95
|
+
continue
|
|
96
|
+
}
|
|
97
|
+
if (type.length > 0) parts.push(`[${type}]`)
|
|
98
|
+
}
|
|
99
|
+
return parts.join('\n\n')
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** @param {string} value @param {number} max @returns {string} */
|
|
103
|
+
function clip(value, max) {
|
|
104
|
+
return value.length <= max ? value : `${value.slice(0, max)}…(已截断 ${value.length - max} 字符)`
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Keep a value from ending a fenced block early.
|
|
109
|
+
* @param {string} value
|
|
110
|
+
* @returns {string}
|
|
111
|
+
*/
|
|
112
|
+
function escapeFence(value) {
|
|
113
|
+
return value.replace(/```/g, '```')
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Normalize one recorded event into the export row shape. Unknown event types
|
|
118
|
+
* are reported by name, never invented as content.
|
|
119
|
+
* @param {Record<string, unknown>} event
|
|
120
|
+
* @param {number} index
|
|
121
|
+
* @returns {Record<string, unknown> | null}
|
|
122
|
+
*/
|
|
123
|
+
function toRow(event, index) {
|
|
124
|
+
const type = text(event.type)
|
|
125
|
+
const time = finiteNumber(event.time)
|
|
126
|
+
const data = plainObject(event.data) ? /** @type {Record<string, unknown>} */ (event.data) : {}
|
|
127
|
+
const seq = finiteNumber(event.seq) ?? index
|
|
128
|
+
if (type === 'user/message') {
|
|
129
|
+
const source = plainObject(data.source) ? /** @type {Record<string, unknown>} */ (data.source) : {}
|
|
130
|
+
return {
|
|
131
|
+
seq,
|
|
132
|
+
at: time === null ? null : isoTime(time),
|
|
133
|
+
type,
|
|
134
|
+
role: 'user',
|
|
135
|
+
injected: text(source.kind).length > 0 && text(source.kind) !== 'user' ? text(source.kind) : null,
|
|
136
|
+
text: clip(contentText(data.content), MAX_BLOCK_CHARS),
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
if (type === 'assistant/message') {
|
|
140
|
+
const usage = plainObject(data.usage) ? /** @type {Record<string, unknown>} */ (data.usage) : null
|
|
141
|
+
return {
|
|
142
|
+
seq,
|
|
143
|
+
at: time === null ? null : isoTime(time),
|
|
144
|
+
type,
|
|
145
|
+
role: 'assistant',
|
|
146
|
+
interrupted: data.interrupted === true,
|
|
147
|
+
text: clip(contentText(data.content), MAX_BLOCK_CHARS),
|
|
148
|
+
usage: usage === null
|
|
149
|
+
? null
|
|
150
|
+
: {
|
|
151
|
+
inputTokens: finiteNumber(usage.inputTokens),
|
|
152
|
+
outputTokens: finiteNumber(usage.outputTokens),
|
|
153
|
+
cacheReadTokens: finiteNumber(usage.cacheReadTokens),
|
|
154
|
+
cacheWriteTokens: finiteNumber(usage.cacheWriteTokens),
|
|
155
|
+
},
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
if (type === 'tool/call') {
|
|
159
|
+
return {
|
|
160
|
+
seq,
|
|
161
|
+
at: time === null ? null : isoTime(time),
|
|
162
|
+
type,
|
|
163
|
+
role: 'tool',
|
|
164
|
+
toolCallId: text(data.callId),
|
|
165
|
+
name: text(data.name),
|
|
166
|
+
arguments: clip(text(data.arguments), MAX_ARGUMENT_CHARS),
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
if (type === 'tool/result') {
|
|
170
|
+
const message = plainObject(data.message) ? /** @type {Record<string, unknown>} */ (data.message) : {}
|
|
171
|
+
return {
|
|
172
|
+
seq,
|
|
173
|
+
at: time === null ? null : isoTime(time),
|
|
174
|
+
type,
|
|
175
|
+
role: 'tool',
|
|
176
|
+
toolCallId: text(message.toolCallId),
|
|
177
|
+
isError: message.isError === true,
|
|
178
|
+
text: clip(contentText(message.content), MAX_RESULT_CHARS),
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
if (type === 'turn/start' || type === 'turn/end' || type === 'step/start' || type === 'step/end') {
|
|
182
|
+
return { seq, at: time === null ? null : isoTime(time), type, role: 'system' }
|
|
183
|
+
}
|
|
184
|
+
return null
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* @param {Record<string, unknown>} session
|
|
189
|
+
* @param {Array<Record<string, unknown>>} rows
|
|
190
|
+
* @param {boolean} includeToolResults
|
|
191
|
+
* @returns {string}
|
|
192
|
+
*/
|
|
193
|
+
function renderMarkdown(session, rows, includeToolResults) {
|
|
194
|
+
/** @type {string[]} */
|
|
195
|
+
const lines = []
|
|
196
|
+
const title = text(session.title).length > 0 ? clip(text(session.title), MAX_TITLE_CHARS) : `Session ${text(session.id).slice(0, 8)}`
|
|
197
|
+
lines.push(`# ${escapeFence(title)}`, '')
|
|
198
|
+
lines.push(`- Session: \`${text(session.id)}\``)
|
|
199
|
+
if (text(session.cwd).length > 0) lines.push(`- Working directory: \`${escapeFence(text(session.cwd))}\``)
|
|
200
|
+
if (typeof session.createdAt === 'number') lines.push(`- Created: ${isoTime(session.createdAt)}`)
|
|
201
|
+
if (typeof session.updatedAt === 'number') lines.push(`- Updated: ${isoTime(session.updatedAt)}`)
|
|
202
|
+
lines.push(`- Events exported: ${rows.length}`, '', '---', '')
|
|
203
|
+
let pendingCalls = 0
|
|
204
|
+
for (const row of rows) {
|
|
205
|
+
const at = row.at === null ? '' : ` · ${/** @type {string} */ (row.at)}`
|
|
206
|
+
if (row.type === 'user/message') {
|
|
207
|
+
const label = row.injected === null || row.injected === undefined ? 'User' : `User (${row.injected})`
|
|
208
|
+
lines.push(`## ${label}${at}`, '', escapeFence(/** @type {string} */ (row.text)), '')
|
|
209
|
+
continue
|
|
210
|
+
}
|
|
211
|
+
if (row.type === 'assistant/message') {
|
|
212
|
+
const interrupted = row.interrupted === true ? ' · interrupted' : ''
|
|
213
|
+
lines.push(`## Assistant${at}${interrupted}`, '', escapeFence(/** @type {string} */ (row.text)), '')
|
|
214
|
+
const usage = plainObject(row.usage) ? /** @type {Record<string, unknown>} */ (row.usage) : null
|
|
215
|
+
if (usage !== null && typeof usage.outputTokens === 'number') {
|
|
216
|
+
lines.push(
|
|
217
|
+
'<details><summary>Token usage</summary>',
|
|
218
|
+
'',
|
|
219
|
+
`- input (uncached): ${String(usage.inputTokens)}`,
|
|
220
|
+
`- output: ${String(usage.outputTokens)}`,
|
|
221
|
+
`- cache read: ${String(usage.cacheReadTokens)}`,
|
|
222
|
+
`- cache write: ${String(usage.cacheWriteTokens)}`,
|
|
223
|
+
'',
|
|
224
|
+
'</details>',
|
|
225
|
+
'',
|
|
226
|
+
)
|
|
227
|
+
}
|
|
228
|
+
continue
|
|
229
|
+
}
|
|
230
|
+
if (row.type === 'tool/call') {
|
|
231
|
+
pendingCalls += 1
|
|
232
|
+
lines.push(`### Tool call: ${text(row.name) || '(unknown tool)'}${at}`, '')
|
|
233
|
+
if (text(row.arguments).length > 0) {
|
|
234
|
+
lines.push('```json', escapeFence(text(row.arguments)), '```', '')
|
|
235
|
+
}
|
|
236
|
+
continue
|
|
237
|
+
}
|
|
238
|
+
if (row.type === 'tool/result') {
|
|
239
|
+
if (includeToolResults !== true) continue
|
|
240
|
+
const failed = row.isError === true ? ' (error)' : ''
|
|
241
|
+
const preview = text(row.text).length > 0 ? escapeFence(clip(text(row.text), MAX_RESULT_CHARS)) : '(no content)'
|
|
242
|
+
lines.push(`> Result${failed}${at}`, '>', ...preview.split('\n').map((line) => `> ${line}`), '')
|
|
243
|
+
continue
|
|
244
|
+
}
|
|
245
|
+
if (row.type === 'turn/end') {
|
|
246
|
+
lines.push(`_Turn ended${at}_`, '')
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
if (pendingCalls > 0 && includeToolResults !== true) lines.push('_Tool results are omitted in this export._', '')
|
|
250
|
+
return lines.join('\n').replace(/\n{3,}/g, '\n\n')
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
const createModule = (core) => {
|
|
254
|
+
const { util, errors } = core
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* Call a sibling module method through the registry.
|
|
258
|
+
* @param {string} method @param {Record<string, unknown>} params @returns {Promise<Record<string, any>>}
|
|
259
|
+
*/
|
|
260
|
+
async function sibling(method, params = {}) {
|
|
261
|
+
const registry = core.registry
|
|
262
|
+
if (registry === undefined || typeof registry.dispatch !== 'function') {
|
|
263
|
+
return { ok: false, code: 'not_ready', reason: '模块注册表尚未就绪' }
|
|
264
|
+
}
|
|
265
|
+
try {
|
|
266
|
+
const value = await Promise.race([
|
|
267
|
+
registry.dispatch(method, params, { internal: true }),
|
|
268
|
+
new Promise((resolve) => {
|
|
269
|
+
const timer = setTimeout(() => resolve(SIBLING_TIMEOUT), SIBLING_TIMEOUT_MS)
|
|
270
|
+
if (typeof timer.unref === 'function') timer.unref()
|
|
271
|
+
}),
|
|
272
|
+
])
|
|
273
|
+
if (value === SIBLING_TIMEOUT) return { ok: false, code: 'not_ready', reason: '兄弟模块响应超时', hint: method }
|
|
274
|
+
return { ok: true, value }
|
|
275
|
+
} catch (error) {
|
|
276
|
+
return {
|
|
277
|
+
ok: false,
|
|
278
|
+
code: plainObject(error) && typeof /** @type {Record<string, unknown>} */ (error).code === 'string'
|
|
279
|
+
? /** @type {string} */ (/** @type {Record<string, unknown>} */ (error).code)
|
|
280
|
+
: 'internal',
|
|
281
|
+
reason: errorMessage(error),
|
|
282
|
+
hint: method,
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/** @returns {Record<string, any> | undefined} */
|
|
288
|
+
function service(name) {
|
|
289
|
+
try {
|
|
290
|
+
return /** @type {Record<string, any> | undefined} */ (core.ctx.get(name))
|
|
291
|
+
} catch {
|
|
292
|
+
return undefined
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** @returns {{ available: boolean, reason?: string, hint?: string, supportsRead: boolean }} */
|
|
297
|
+
function capability() {
|
|
298
|
+
const query = service('sessionQuery')
|
|
299
|
+
if (query === undefined || query === null) {
|
|
300
|
+
return { available: false, supportsRead: false, reason: '宿主未提供 sessionQuery 服务', hint: '该部署无法读取会话记录,导出不可用' }
|
|
301
|
+
}
|
|
302
|
+
if (typeof query.readSession !== 'function') {
|
|
303
|
+
return { available: false, supportsRead: false, reason: 'sessionQuery 缺少 readSession,无法读取事件本体', hint: 'listEvents 只返回摘要,不能作为导出内容' }
|
|
304
|
+
}
|
|
305
|
+
return { available: true, supportsRead: true }
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* Read one session's events.
|
|
310
|
+
* @param {string} sessionId @returns {Promise<{ ok: true, snapshot: Record<string, any>, events: any[] } | { ok: false, code: string, reason: string, hint?: string }>}
|
|
311
|
+
*/
|
|
312
|
+
async function readSession(sessionId) {
|
|
313
|
+
const cap = capability()
|
|
314
|
+
if (!cap.available) return { ok: false, code: 'not_supported', reason: cap.reason ?? '不可用', hint: cap.hint }
|
|
315
|
+
try {
|
|
316
|
+
const snapshot = await service('sessionQuery').readSession(sessionId)
|
|
317
|
+
const events = Array.isArray(snapshot?.events) ? snapshot.events : []
|
|
318
|
+
return { ok: true, snapshot: plainObject(snapshot) ? snapshot : {}, events }
|
|
319
|
+
} catch (error) {
|
|
320
|
+
return { ok: false, code: 'internal', reason: '读取会话日志失败', hint: errorMessage(error) }
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* Session metadata from the sessions module (titles/archive state live there).
|
|
326
|
+
* @param {string} sessionId @returns {Promise<Record<string, any> | null>}
|
|
327
|
+
*/
|
|
328
|
+
async function sessionRow(sessionId) {
|
|
329
|
+
const listed = await sibling('sessions.list', { page: 1, limit: 500, query: '', archived: false })
|
|
330
|
+
if (!listed.ok) {
|
|
331
|
+
const archived = await sibling('sessions.list', { page: 1, limit: 500, query: '', archived: true })
|
|
332
|
+
if (!archived.ok) return null
|
|
333
|
+
return findRow(archived.value, sessionId)
|
|
334
|
+
}
|
|
335
|
+
return findRow(listed.value, sessionId) ?? findRowFromArchived(sessionId)
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/** @param {Record<string, any>} value @param {string} id @returns {Record<string, any> | null} */
|
|
339
|
+
function findRow(value, id) {
|
|
340
|
+
const rows = Array.isArray(value?.rows) ? value.rows : Array.isArray(value?.items) ? value.items : []
|
|
341
|
+
for (const row of rows) {
|
|
342
|
+
if (text(row?.id) === id) return row
|
|
343
|
+
}
|
|
344
|
+
return null
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/** @param {string} id @returns {Promise<Record<string, any> | null>} */
|
|
348
|
+
async function findRowFromArchived(id) {
|
|
349
|
+
const archived = await sibling('sessions.list', { page: 1, limit: 500, query: '', archived: true })
|
|
350
|
+
return archived.ok ? findRow(archived.value, id) : null
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* Render rows within the byte budget.
|
|
355
|
+
* @param {Record<string, any>} session
|
|
356
|
+
* @param {Array<Record<string, unknown>>} rows
|
|
357
|
+
* @param {'markdown' | 'json'} format
|
|
358
|
+
* @param {number} maxBytes
|
|
359
|
+
* @param {boolean} includeToolResults
|
|
360
|
+
*/
|
|
361
|
+
function renderWithin(session, rows, format, maxBytes, includeToolResults) {
|
|
362
|
+
const build = (/** @type {Array<Record<string, unknown>>} */ kept) => {
|
|
363
|
+
if (format === 'markdown') return renderMarkdown(session, kept, includeToolResults)
|
|
364
|
+
return `${JSON.stringify({ version: 1, session, events: kept }, null, 2)}\n`
|
|
365
|
+
}
|
|
366
|
+
const totalBytes = Buffer.byteLength(build(rows), 'utf8')
|
|
367
|
+
if (totalBytes <= maxBytes) {
|
|
368
|
+
return { text: build(rows), bytes: totalBytes, totalBytes, omittedEvents: 0, truncated: false }
|
|
369
|
+
}
|
|
370
|
+
/** @type {Array<Record<string, unknown>>} */
|
|
371
|
+
const kept = []
|
|
372
|
+
for (const row of rows) {
|
|
373
|
+
const candidate = [...kept, row]
|
|
374
|
+
if (Buffer.byteLength(build(candidate), 'utf8') > maxBytes) break
|
|
375
|
+
kept.push(row)
|
|
376
|
+
}
|
|
377
|
+
const text = build(kept)
|
|
378
|
+
return {
|
|
379
|
+
text,
|
|
380
|
+
bytes: Buffer.byteLength(text, 'utf8'),
|
|
381
|
+
totalBytes,
|
|
382
|
+
omittedEvents: rows.length - kept.length,
|
|
383
|
+
truncated: true,
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
return {
|
|
388
|
+
id: 'export',
|
|
389
|
+
title: 'nav.export',
|
|
390
|
+
order: 110,
|
|
391
|
+
requires: ['sessionQuery'],
|
|
392
|
+
|
|
393
|
+
async init() {},
|
|
394
|
+
|
|
395
|
+
probe: () => {
|
|
396
|
+
const cap = capability()
|
|
397
|
+
if (!cap.available) return { state: 'BLOCKED', detail: cap.reason ?? '不可用' }
|
|
398
|
+
// A FULL module carries no detail: the read-only guarantee is stated by
|
|
399
|
+
// `export.diagnostics().policy` instead.
|
|
400
|
+
return { state: 'FULL', detail: '' }
|
|
401
|
+
},
|
|
402
|
+
|
|
403
|
+
methods: {
|
|
404
|
+
/** Capability and limit self-description for the page header. */
|
|
405
|
+
'export.diagnostics': async () => ({
|
|
406
|
+
available: capability().available,
|
|
407
|
+
formats: [...FORMATS],
|
|
408
|
+
limits: { defaultBytes: DEFAULT_MAX_BYTES, maxBytes: MAX_MAX_BYTES },
|
|
409
|
+
includeToolResultsDefault: true,
|
|
410
|
+
source: 'plugin',
|
|
411
|
+
policy: {
|
|
412
|
+
readOnly: true,
|
|
413
|
+
writesSessionLog: false,
|
|
414
|
+
deletesSessions: false,
|
|
415
|
+
archivesSessions: false,
|
|
416
|
+
externalNetwork: false,
|
|
417
|
+
note: '导出只从宿主已记录的会话读取,不修改、不删除、不上传。',
|
|
418
|
+
},
|
|
419
|
+
}),
|
|
420
|
+
|
|
421
|
+
/**
|
|
422
|
+
* Export statistics for one session, before rendering anything.
|
|
423
|
+
* @param {unknown} params
|
|
424
|
+
*/
|
|
425
|
+
'export.summary': async (params) => {
|
|
426
|
+
const p = util.paramsObject(params)
|
|
427
|
+
const id = util.strParam(p, 'id', { max: 200 })
|
|
428
|
+
const cap = capability()
|
|
429
|
+
if (!cap.available) return { available: false, reason: cap.reason, hint: cap.hint }
|
|
430
|
+
const read = await readSession(id)
|
|
431
|
+
if (!read.ok) return { available: false, reason: read.reason, hint: read.hint }
|
|
432
|
+
const rows = read.events.map(toRow).filter((row) => row !== null)
|
|
433
|
+
/** @type {Record<string, number>} */
|
|
434
|
+
const counts = { events: read.events.length, userMessages: 0, assistantMessages: 0, toolCalls: 0, toolResults: 0, toolErrors: 0, errors: 0 }
|
|
435
|
+
for (const row of rows) {
|
|
436
|
+
if (row.type === 'user/message') counts.userMessages += 1
|
|
437
|
+
else if (row.type === 'assistant/message') counts.assistantMessages += 1
|
|
438
|
+
else if (row.type === 'tool/call') counts.toolCalls += 1
|
|
439
|
+
else if (row.type === 'tool/result') {
|
|
440
|
+
counts.toolResults += 1
|
|
441
|
+
if (row.isError === true) counts.toolErrors += 1
|
|
442
|
+
}
|
|
443
|
+
if (row.isError === true) counts.errors += 1
|
|
444
|
+
}
|
|
445
|
+
const row = await sessionRow(id)
|
|
446
|
+
return {
|
|
447
|
+
available: true,
|
|
448
|
+
sessionId: id,
|
|
449
|
+
title: text(row?.title) || null,
|
|
450
|
+
source: 'plugin',
|
|
451
|
+
counts,
|
|
452
|
+
estimatedBytes: {
|
|
453
|
+
markdown: Buffer.byteLength(renderMarkdown({ id }, rows, true), 'utf8'),
|
|
454
|
+
json: Buffer.byteLength(JSON.stringify({ version: 1, session: { id }, events: rows }, null, 2), 'utf8'),
|
|
455
|
+
},
|
|
456
|
+
formats: [...FORMATS],
|
|
457
|
+
limits: { defaultBytes: DEFAULT_MAX_BYTES, maxBytes: MAX_MAX_BYTES },
|
|
458
|
+
warnings: read.events.length !== rows.length ? [`${read.events.length - rows.length} 个事件类型不在导出范围内(如 turn/step 之外的内部事件)`] : [],
|
|
459
|
+
}
|
|
460
|
+
},
|
|
461
|
+
|
|
462
|
+
/**
|
|
463
|
+
* Render one session.
|
|
464
|
+
* @param {unknown} params
|
|
465
|
+
*/
|
|
466
|
+
'export.session': async (params) => {
|
|
467
|
+
const p = util.paramsObject(params)
|
|
468
|
+
const id = util.strParam(p, 'id', { max: 200 })
|
|
469
|
+
const format = util.strParam(p, 'format', { max: 16, required: false, fallback: 'markdown' })
|
|
470
|
+
if (!FORMATS.includes(format)) {
|
|
471
|
+
throw errors.badRequest(`format 只支持 ${FORMATS.join(' / ')}`, { hint: `收到 ${format}` })
|
|
472
|
+
}
|
|
473
|
+
const maxBytes = Math.trunc(util.numParam(p, 'maxBytes', { min: 1024, max: MAX_MAX_BYTES, fallback: DEFAULT_MAX_BYTES }))
|
|
474
|
+
const includeToolResults = util.boolParam(p, 'includeToolResults', true)
|
|
475
|
+
const cap = capability()
|
|
476
|
+
if (!cap.available) {
|
|
477
|
+
return { available: false, reason: cap.reason, hint: cap.hint, format, sessionId: id }
|
|
478
|
+
}
|
|
479
|
+
const read = await readSession(id)
|
|
480
|
+
if (!read.ok) return { available: false, reason: read.reason, hint: read.hint, format, sessionId: id }
|
|
481
|
+
const rows = read.events.map(toRow).filter((row) => row !== null)
|
|
482
|
+
const row = await sessionRow(id)
|
|
483
|
+
const session = {
|
|
484
|
+
id,
|
|
485
|
+
title: text(row?.title) || null,
|
|
486
|
+
cwd: text(row?.cwd) || null,
|
|
487
|
+
createdAt: finiteNumber(row?.createdAt),
|
|
488
|
+
updatedAt: finiteNumber(row?.updatedAt),
|
|
489
|
+
eventCount: read.events.length,
|
|
490
|
+
}
|
|
491
|
+
const rendered = renderWithin(session, rows, /** @type {'markdown' | 'json'} */ (format), maxBytes, includeToolResults)
|
|
492
|
+
return {
|
|
493
|
+
available: true,
|
|
494
|
+
sessionId: id,
|
|
495
|
+
format,
|
|
496
|
+
source: 'plugin',
|
|
497
|
+
text: rendered.text,
|
|
498
|
+
bytes: rendered.bytes,
|
|
499
|
+
totalBytes: rendered.totalBytes,
|
|
500
|
+
truncated: rendered.truncated,
|
|
501
|
+
omittedEvents: rendered.omittedEvents,
|
|
502
|
+
includeToolResults,
|
|
503
|
+
limits: { maxBytes, defaultBytes: DEFAULT_MAX_BYTES },
|
|
504
|
+
generatedAt: new Date().toISOString(),
|
|
505
|
+
warnings: rendered.truncated
|
|
506
|
+
? [`超出 ${maxBytes} 字节上限,已省略 ${rendered.omittedEvents} 个事件(按事件边界截断,不含半个事件)`]
|
|
507
|
+
: [],
|
|
508
|
+
}
|
|
509
|
+
},
|
|
510
|
+
|
|
511
|
+
/**
|
|
512
|
+
* Sessions available for export, newest first.
|
|
513
|
+
* @param {unknown} params
|
|
514
|
+
*/
|
|
515
|
+
'export.sessions': async (params) => {
|
|
516
|
+
const p = util.paramsObject(params)
|
|
517
|
+
const limit = Math.trunc(util.numParam(p, 'limit', { min: 1, max: MAX_SESSIONS, fallback: 50 }))
|
|
518
|
+
const query = util.strParam(p, 'query', { max: 200, required: false, fallback: '' }).trim()
|
|
519
|
+
const listed = await sibling('sessions.list', { page: 1, limit, query })
|
|
520
|
+
if (!listed.ok) return { available: false, reason: listed.reason, hint: listed.hint, items: [] }
|
|
521
|
+
const rows = Array.isArray(listed.value?.items) ? listed.value.items : Array.isArray(listed.value?.rows) ? listed.value.rows : []
|
|
522
|
+
return {
|
|
523
|
+
available: true,
|
|
524
|
+
total: listed.value?.total ?? rows.length,
|
|
525
|
+
items: rows.slice(0, limit).map((row) => ({
|
|
526
|
+
id: text(row?.id),
|
|
527
|
+
title: text(row?.title) || null,
|
|
528
|
+
updatedAt: finiteNumber(row?.updatedAt),
|
|
529
|
+
eventCount: finiteNumber(row?.eventCount),
|
|
530
|
+
archived: row?.archived === true,
|
|
531
|
+
origin: text(row?.origin) || null,
|
|
532
|
+
sizeBytes: finiteNumber(row?.sizeBytes),
|
|
533
|
+
})),
|
|
534
|
+
}
|
|
535
|
+
},
|
|
536
|
+
},
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
export default createModule
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-agent-control-center",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "DSH Agent Control Center: AGENTS.md editing with backups, tool inventory, sessions, real token usage, agent metadata, diagnostics and templates in one settings page.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
package/scripts/verify.mjs
CHANGED
|
@@ -113,6 +113,8 @@ const MODULES = [
|
|
|
113
113
|
['templates', 'lib/modules/g-templates.js', 'src/client/pages/templates.js', 'src/client/i18n/templates.js', 'tests/templates.test.mjs'],
|
|
114
114
|
['overview', 'lib/modules/h-overview.js', 'src/client/pages/overview.js', 'src/client/i18n/overview.js', 'tests/overview.test.mjs'],
|
|
115
115
|
['recovery', 'lib/modules/i-recovery.js', 'src/client/pages/recovery.js', 'src/client/i18n/recovery.js', 'tests/recovery.test.mjs'],
|
|
116
|
+
['instruction', 'lib/modules/j-instruction.js', 'src/client/pages/instruction.js', 'src/client/i18n/instruction.js', 'tests/instruction.test.mjs'],
|
|
117
|
+
['export', 'lib/modules/k-export.js', 'src/client/pages/export.js', 'src/client/i18n/export.js', 'tests/export.test.mjs'],
|
|
116
118
|
]
|
|
117
119
|
|
|
118
120
|
const present = []
|