dsh-agent-control-center 0.1.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 +116 -0
- package/README.md +217 -83
- package/README.zh.md +159 -58
- package/client.js +7660 -2005
- package/cordis.patch.yml +5 -0
- package/docs/01-CONTRACT.md +3 -2
- package/docs/05-ACCEPTANCE-EVIDENCE.md +81 -0
- package/docs/06-UX-OPTIMIZATION.md +57 -0
- package/docs/07-GUIDE.md +327 -0
- package/docs/08-COMPATIBILITY.md +202 -0
- package/docs/09-ARCHITECTURE.md +333 -0
- package/docs/ROADMAP.md +448 -0
- package/index.js +67 -2
- package/lib/core/cache.js +277 -0
- package/lib/core/compat.js +877 -0
- package/lib/core/errors.js +14 -1
- package/lib/core/http.js +22 -0
- package/lib/core/index.js +53 -2
- package/lib/core/paths.js +6 -0
- package/lib/core/registry.js +21 -5
- package/lib/core/util.js +4 -1
- package/lib/modules/a-agents.js +104 -4
- package/lib/modules/b-tools.js +169 -26
- package/lib/modules/f-diagnostics.js +109 -17
- package/lib/modules/g-templates.js +18 -0
- package/lib/modules/i-recovery.js +84 -23
- package/lib/modules/j-instruction.js +624 -0
- package/lib/modules/k-export.js +540 -0
- package/package.json +1 -1
- package/scripts/release.mjs +81 -0
- package/scripts/verify.mjs +12 -0
- package/src/client/app.js +684 -118
- package/src/client/i18n/agents.js +96 -0
- package/src/client/i18n/common.js +36 -0
- package/src/client/i18n/diagnostics.js +52 -0
- package/src/client/i18n/export.js +174 -0
- package/src/client/i18n/instruction.js +236 -0
- package/src/client/i18n/meta.js +72 -0
- package/src/client/i18n/overview.js +38 -0
- package/src/client/i18n/recovery.js +66 -0
- package/src/client/i18n/sessions.js +64 -0
- package/src/client/i18n/templates.js +88 -0
- package/src/client/i18n/tools.js +96 -0
- package/src/client/i18n/usage.js +42 -0
- package/src/client/kernel.js +327 -40
- package/src/client/pages/agents.js +637 -354
- package/src/client/pages/diagnostics.js +526 -177
- package/src/client/pages/export.js +664 -0
- package/src/client/pages/instruction.js +648 -0
- package/src/client/pages/meta.js +553 -193
- package/src/client/pages/overview.js +255 -34
- package/src/client/pages/recovery.js +332 -131
- package/src/client/pages/sessions.js +470 -307
- package/src/client/pages/templates.js +691 -381
- package/src/client/pages/tools.js +559 -206
- package/src/client/pages/usage.js +235 -57
|
@@ -0,0 +1,624 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* J · Instruction preview — what the model actually received.
|
|
3
|
+
*
|
|
4
|
+
* Two read-only views of the same instruction surface:
|
|
5
|
+
* - `files`: module A's render of the discovered instruction chain in the host's
|
|
6
|
+
* own format (`agents.render`), available without a session;
|
|
7
|
+
* - `session`: the durable `user/message` events whose `source.kind` is
|
|
8
|
+
* `agent-instructions`, which is the exact text the host injected.
|
|
9
|
+
*
|
|
10
|
+
* This module never writes an instruction file, never executes a tool, never
|
|
11
|
+
* appends a session event and never calls `agents.save`. Host capabilities are
|
|
12
|
+
* read on demand and a missing source degrades to `{ available: false, reason }`
|
|
13
|
+
* instead of fabricating data.
|
|
14
|
+
* @module dsh-agent-control-center/modules/instruction
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
/** Sibling modules are called through the registry; a slow one must not stall the page. */
|
|
18
|
+
const SIBLING_TIMEOUT_MS = 4000
|
|
19
|
+
/** Sentinel resolved by the sibling timeout race. */
|
|
20
|
+
const SIBLING_TIMEOUT = Symbol('instruction-sibling-timeout')
|
|
21
|
+
/** Single-response ceiling: the HTTP layer must never receive a larger body. */
|
|
22
|
+
const RESPONSE_MAX_BYTES = 2 * 1024 * 1024
|
|
23
|
+
/** JSON envelope estimate reserved while clipping one item's text. */
|
|
24
|
+
const ITEM_ENVELOPE_BYTES = 96
|
|
25
|
+
/** Halving passes allowed by the final serialized-size guards. */
|
|
26
|
+
const MAX_CLIP_PASSES = 12
|
|
27
|
+
/** Remote failure messages are bounded before they enter a hint. */
|
|
28
|
+
const ERROR_HINT_MAX = 160
|
|
29
|
+
|
|
30
|
+
/** @param {unknown} value @returns {number} */
|
|
31
|
+
function byteLength(value) {
|
|
32
|
+
return Buffer.byteLength(String(value ?? ''), 'utf8')
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** @param {unknown} value @returns {number} */
|
|
36
|
+
function jsonBytes(value) {
|
|
37
|
+
return byteLength(JSON.stringify(value))
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Trim a UTF-8 string without splitting a code point.
|
|
42
|
+
* @param {string} value
|
|
43
|
+
* @param {number} maxBytes
|
|
44
|
+
* @returns {string}
|
|
45
|
+
*/
|
|
46
|
+
function truncateUtf8(value, maxBytes) {
|
|
47
|
+
const bytes = Buffer.from(value, 'utf8')
|
|
48
|
+
if (bytes.length <= maxBytes) return value
|
|
49
|
+
let end = Math.max(0, Math.trunc(maxBytes))
|
|
50
|
+
while (end > 0 && (bytes.readUInt8(end) & 0xc0) === 0x80) end -= 1
|
|
51
|
+
return bytes.subarray(0, end).toString('utf8')
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Session events carry `time` in epoch milliseconds; pages read ISO strings.
|
|
56
|
+
* @param {unknown} value
|
|
57
|
+
* @returns {string | null}
|
|
58
|
+
*/
|
|
59
|
+
function isoTime(value) {
|
|
60
|
+
if (typeof value !== 'number' || !Number.isFinite(value)) return null
|
|
61
|
+
try {
|
|
62
|
+
return new Date(value).toISOString()
|
|
63
|
+
} catch {
|
|
64
|
+
return null
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** @param {unknown} value @returns {number | null} */
|
|
69
|
+
function finiteNumber(value) {
|
|
70
|
+
return typeof value === 'number' && Number.isFinite(value) ? value : null
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** @param {unknown} value @returns {string | null} */
|
|
74
|
+
function textOrNull(value) {
|
|
75
|
+
return typeof value === 'string' ? value : null
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** @param {unknown} value @returns {string | null} */
|
|
79
|
+
function stringOrNull(value) {
|
|
80
|
+
return typeof value === 'string' && value.length > 0 ? value : null
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* @param {Record<string, any>} core
|
|
85
|
+
*/
|
|
86
|
+
export default function createModule(core) {
|
|
87
|
+
const util = core.util
|
|
88
|
+
const errors = core.errors
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Read one host service on demand. A missing service is undefined, never a
|
|
92
|
+
* thrown lookup.
|
|
93
|
+
* @param {string} name
|
|
94
|
+
* @returns {any}
|
|
95
|
+
*/
|
|
96
|
+
function service(name) {
|
|
97
|
+
try {
|
|
98
|
+
return core.ctx.get(name)
|
|
99
|
+
} catch {
|
|
100
|
+
return undefined
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* @param {string} reason
|
|
106
|
+
* @param {string} [hint]
|
|
107
|
+
* @returns {{ available: false, reason: string, hint?: string }}
|
|
108
|
+
*/
|
|
109
|
+
function unavailable(reason, hint) {
|
|
110
|
+
return { available: false, reason: String(reason), ...(hint === undefined ? {} : { hint: String(hint) }) }
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Validate params through the shared helper, then add a page-facing hint on
|
|
115
|
+
* failure so the UI can explain what the method expects.
|
|
116
|
+
* @param {unknown} params
|
|
117
|
+
* @returns {Record<string, unknown>}
|
|
118
|
+
*/
|
|
119
|
+
function paramsOf(params) {
|
|
120
|
+
try {
|
|
121
|
+
return util.paramsObject(params)
|
|
122
|
+
} catch (error) {
|
|
123
|
+
throw errors.badRequest(String(error?.message ?? 'params 必须是对象'), {
|
|
124
|
+
hint: '请求参数必须是 JSON 对象;本模块只读取指令内容,不写入任何文件',
|
|
125
|
+
cause: error,
|
|
126
|
+
})
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* @param {Record<string, unknown>} params
|
|
132
|
+
* @returns {string}
|
|
133
|
+
*/
|
|
134
|
+
function sessionIdOf(params) {
|
|
135
|
+
try {
|
|
136
|
+
return util.strParam(params, 'sessionId', { max: 200 })
|
|
137
|
+
} catch (error) {
|
|
138
|
+
throw errors.badRequest(String(error?.message ?? '参数 sessionId 无效'), {
|
|
139
|
+
hint: 'sessionId 取自宿主会话列表;本模块只读取该会话已落盘的指令事件',
|
|
140
|
+
cause: error,
|
|
141
|
+
})
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* @param {Record<string, unknown>} params
|
|
147
|
+
* @returns {string | undefined}
|
|
148
|
+
*/
|
|
149
|
+
function cwdOf(params) {
|
|
150
|
+
if (params.cwd === undefined || params.cwd === null) return undefined
|
|
151
|
+
try {
|
|
152
|
+
return util.strParam(params, 'cwd', { max: 4096 })
|
|
153
|
+
} catch (error) {
|
|
154
|
+
throw errors.badRequest(String(error?.message ?? '参数 cwd 无效'), {
|
|
155
|
+
hint: 'cwd 必须是目录绝对路径;省略时由模块 A 按会话或进程工作目录解析',
|
|
156
|
+
cause: error,
|
|
157
|
+
})
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Call a sibling module through the registry instead of importing it.
|
|
163
|
+
* @param {string} method
|
|
164
|
+
* @param {Record<string, unknown>} [params]
|
|
165
|
+
* @param {number} [timeoutMs]
|
|
166
|
+
* @returns {Promise<{ ok: true, value: unknown } | { ok: false, reason: string, hint?: string, code?: string }>}
|
|
167
|
+
*/
|
|
168
|
+
async function sibling(method, params = {}, timeoutMs = SIBLING_TIMEOUT_MS) {
|
|
169
|
+
if (core.registry === undefined || typeof core.registry.dispatch !== 'function') {
|
|
170
|
+
return unavailableSibling('模块注册表尚未就绪', method)
|
|
171
|
+
}
|
|
172
|
+
try {
|
|
173
|
+
const value = await Promise.race([
|
|
174
|
+
core.registry.dispatch(method, params, { internal: true }),
|
|
175
|
+
new Promise((resolve) => {
|
|
176
|
+
const timer = setTimeout(() => resolve(SIBLING_TIMEOUT), timeoutMs)
|
|
177
|
+
if (typeof timer.unref === 'function') timer.unref()
|
|
178
|
+
}),
|
|
179
|
+
])
|
|
180
|
+
if (value === SIBLING_TIMEOUT) {
|
|
181
|
+
return unavailableSibling(`模块 A 响应超时(>${timeoutMs}ms)`, method)
|
|
182
|
+
}
|
|
183
|
+
return { ok: true, value }
|
|
184
|
+
} catch (error) {
|
|
185
|
+
return unavailableSibling(String(error?.message ?? error), stringOrNull(error?.hint) ?? method, stringOrNull(error?.code) ?? undefined)
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* @param {string} reason
|
|
191
|
+
* @param {string} [hint]
|
|
192
|
+
* @param {string} [code]
|
|
193
|
+
* @returns {{ ok: false, reason: string, hint?: string, code?: string }}
|
|
194
|
+
*/
|
|
195
|
+
function unavailableSibling(reason, hint, code) {
|
|
196
|
+
return { ok: false, reason: String(reason), ...(hint === undefined ? {} : { hint: String(hint) }), ...(code === undefined ? {} : { code }) }
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** @param {unknown} budget @returns {{ bytes: number | null, renderedBytes: number | null, fits: boolean, files: number | null }} */
|
|
200
|
+
function chainSummary(budget) {
|
|
201
|
+
const record = budget !== null && typeof budget === 'object' ? /** @type {Record<string, any>} */ (budget) : {}
|
|
202
|
+
return {
|
|
203
|
+
bytes: finiteNumber(record.bytes),
|
|
204
|
+
renderedBytes: finiteNumber(record.renderedBytes),
|
|
205
|
+
fits: record.fits === true,
|
|
206
|
+
files: finiteNumber(record.files),
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Project one module-A discovery row onto the fields the preview page needs.
|
|
212
|
+
* The whole row stays in module A; text and raw bytes never leave it.
|
|
213
|
+
* @param {unknown} item
|
|
214
|
+
*/
|
|
215
|
+
function fileRow(item) {
|
|
216
|
+
const record = item !== null && typeof item === 'object' ? /** @type {Record<string, any>} */ (item) : {}
|
|
217
|
+
return {
|
|
218
|
+
path: textOrNull(record.path),
|
|
219
|
+
displayPath: textOrNull(record.displayPath),
|
|
220
|
+
source: textOrNull(record.source),
|
|
221
|
+
bytes: finiteNumber(record.bytes),
|
|
222
|
+
hash: textOrNull(record.hash),
|
|
223
|
+
inEffectiveChain: record.inEffectiveChain === true,
|
|
224
|
+
deduped: record.deduped === true,
|
|
225
|
+
dedupedBy: textOrNull(record.dedupedBy),
|
|
226
|
+
budgetOmitted: record.budgetOmitted === true,
|
|
227
|
+
budgetTruncated: record.budgetTruncated === true,
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Files view: module A's chain discovery, projected to metadata only.
|
|
233
|
+
* @param {string | undefined} cwd
|
|
234
|
+
* @returns {Promise<Record<string, any>>}
|
|
235
|
+
*/
|
|
236
|
+
async function chainValue(cwd) {
|
|
237
|
+
const result = await sibling('agents.files', cwd === undefined ? {} : { cwd })
|
|
238
|
+
if (!result.ok) {
|
|
239
|
+
return unavailable(`模块 A 不可用:${result.reason}`, result.hint ?? '请确认 AGENTS.md 模块已加载;本模块不直接读取文件')
|
|
240
|
+
}
|
|
241
|
+
const value = result.value
|
|
242
|
+
if (value === null || typeof value !== 'object' || /** @type {Record<string, any>} */ (value).available !== true) {
|
|
243
|
+
const record = value !== null && typeof value === 'object' ? /** @type {Record<string, any>} */ (value) : {}
|
|
244
|
+
return unavailable(
|
|
245
|
+
textOrNull(record.reason) ?? '模块 A 未返回可用的指令链',
|
|
246
|
+
textOrNull(record.hint) ?? '请在 AGENTS.md 页面确认指令链可读,再回到本页刷新',
|
|
247
|
+
)
|
|
248
|
+
}
|
|
249
|
+
const record = /** @type {Record<string, any>} */ (value)
|
|
250
|
+
const items = Array.isArray(record.items) ? record.items : []
|
|
251
|
+
const payload = {
|
|
252
|
+
available: true,
|
|
253
|
+
cwd: textOrNull(record.cwd) ?? (cwd === undefined ? null : cwd),
|
|
254
|
+
projectRoot: textOrNull(record.projectRoot),
|
|
255
|
+
cwdSource: textOrNull(record.cwdSource),
|
|
256
|
+
budget: {
|
|
257
|
+
maxBytes: finiteNumber(record.budget?.maxBytes),
|
|
258
|
+
source: textOrNull(record.budget?.source),
|
|
259
|
+
},
|
|
260
|
+
chains: {
|
|
261
|
+
userGlobal: chainSummary(record.chains?.userGlobal),
|
|
262
|
+
project: chainSummary(record.chains?.project),
|
|
263
|
+
},
|
|
264
|
+
files: items.map(fileRow),
|
|
265
|
+
warnings: Array.isArray(record.warnings) ? record.warnings.map((warning) => String(warning)) : [],
|
|
266
|
+
}
|
|
267
|
+
return capChainResponse(payload)
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* Keep a chain response under the single-response ceiling. Dropping rows is
|
|
272
|
+
* only reachable for an unusually large warning list or file set, so it is
|
|
273
|
+
* flagged explicitly instead of silently shrinking the page.
|
|
274
|
+
* @param {Record<string, any>} payload
|
|
275
|
+
*/
|
|
276
|
+
function capChainResponse(payload) {
|
|
277
|
+
if (jsonBytes(payload) <= RESPONSE_MAX_BYTES) return payload
|
|
278
|
+
const files = Array.isArray(payload.files) ? payload.files : []
|
|
279
|
+
const warnings = Array.isArray(payload.warnings) ? payload.warnings : []
|
|
280
|
+
const original = files.length + warnings.length
|
|
281
|
+
while (jsonBytes(payload) > RESPONSE_MAX_BYTES && files.length > 0) files.pop()
|
|
282
|
+
while (jsonBytes(payload) > RESPONSE_MAX_BYTES && warnings.length > 0) warnings.pop()
|
|
283
|
+
const kept = files.length + warnings.length
|
|
284
|
+
return kept === original ? payload : { ...payload, truncated: true }
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* Files view: module A's rendered text, passed through unchanged apart from the
|
|
289
|
+
* `mode` marker and a final size guard.
|
|
290
|
+
* @param {string | undefined} cwd
|
|
291
|
+
* @returns {Promise<Record<string, any>>}
|
|
292
|
+
*/
|
|
293
|
+
async function previewValue(cwd) {
|
|
294
|
+
const result = await sibling('agents.render', cwd === undefined ? {} : { cwd })
|
|
295
|
+
if (!result.ok) {
|
|
296
|
+
return {
|
|
297
|
+
available: false,
|
|
298
|
+
mode: 'files',
|
|
299
|
+
cwd: cwd === undefined ? null : cwd,
|
|
300
|
+
reason: `模块 A 不可用:${result.reason}`,
|
|
301
|
+
hint: result.hint === undefined ? '请确认 AGENTS.md 模块已加载;本模块不直接读取或渲染文件' : result.hint,
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
const value = result.value
|
|
305
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
|
306
|
+
return {
|
|
307
|
+
available: false,
|
|
308
|
+
mode: 'files',
|
|
309
|
+
cwd: cwd === undefined ? null : cwd,
|
|
310
|
+
reason: '模块 A 未返回预览结果',
|
|
311
|
+
hint: '请重试;若持续失败,检查 AGENTS.md 页面的指令链读取是否正常',
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
/** @type {Record<string, any>} */
|
|
315
|
+
const payload = { .../** @type {Record<string, any>} */ (value), mode: 'files' }
|
|
316
|
+
if (payload.cwd === undefined) payload.cwd = cwd === undefined ? null : cwd
|
|
317
|
+
if (payload.available !== true) {
|
|
318
|
+
payload.available = false
|
|
319
|
+
if (textOrNull(payload.reason) === null) payload.reason = '宿主未返回可用的指令预览'
|
|
320
|
+
if (payload.hint === undefined) payload.hint = '指令预算或文件读取不可用;可查看会话精确视图或 AGENTS.md 页面'
|
|
321
|
+
return payload
|
|
322
|
+
}
|
|
323
|
+
return capPreviewResponse(payload)
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* Clip a rendered preview only when it would exceed the response ceiling.
|
|
328
|
+
* `truncated` from module A is an array of budget-truncated files, so the
|
|
329
|
+
* clipping flag is separate and the note says the text was shortened here.
|
|
330
|
+
* @param {Record<string, any>} payload
|
|
331
|
+
*/
|
|
332
|
+
function capPreviewResponse(payload) {
|
|
333
|
+
let result = payload
|
|
334
|
+
let passes = 0
|
|
335
|
+
while (jsonBytes(result) > RESPONSE_MAX_BYTES && typeof result.text === 'string' && result.text.length > 0 && passes < MAX_CLIP_PASSES) {
|
|
336
|
+
result = {
|
|
337
|
+
...result,
|
|
338
|
+
text: truncateUtf8(result.text, Math.floor(byteLength(result.text) / 2)),
|
|
339
|
+
exact: false,
|
|
340
|
+
responseTruncated: true,
|
|
341
|
+
note: `${textOrNull(result.note) ?? ''}(响应超过 2 MiB,文本已截断;完整文本请以会话精确视图为准)`,
|
|
342
|
+
}
|
|
343
|
+
passes += 1
|
|
344
|
+
}
|
|
345
|
+
return result
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/**
|
|
349
|
+
* Text blocks of one message, concatenated the way the instruction renderer
|
|
350
|
+
* joins them. A string content is accepted as-is for older logs.
|
|
351
|
+
* @param {unknown} data
|
|
352
|
+
* @returns {string}
|
|
353
|
+
*/
|
|
354
|
+
function messageTextOf(data) {
|
|
355
|
+
const content = data !== null && typeof data === 'object' ? /** @type {Record<string, any>} */ (data).content : undefined
|
|
356
|
+
if (typeof content === 'string') return content
|
|
357
|
+
if (!Array.isArray(content)) return ''
|
|
358
|
+
/** @type {string[]} */
|
|
359
|
+
const parts = []
|
|
360
|
+
for (const block of content) {
|
|
361
|
+
if (block === null || typeof block !== 'object') continue
|
|
362
|
+
const record = /** @type {Record<string, unknown>} */ (block)
|
|
363
|
+
if (record.type !== 'text' || typeof record.text !== 'string') continue
|
|
364
|
+
if (record.text.length > 0) parts.push(record.text)
|
|
365
|
+
}
|
|
366
|
+
return parts.join('\n\n')
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/**
|
|
370
|
+
* Every durable agent-instruction block in event order. Nothing is inferred:
|
|
371
|
+
* only `user/message` events with the exact durable source are kept.
|
|
372
|
+
* @param {readonly any[]} events
|
|
373
|
+
* @returns {Array<{ seq: number, at: string | null, baseline: boolean, bytes: number, text: string, truncated: boolean }>}
|
|
374
|
+
*/
|
|
375
|
+
function instructionItems(events) {
|
|
376
|
+
/** @type {Array<{ seq: number, at: string | null, baseline: boolean, bytes: number, text: string, truncated: boolean }>} */
|
|
377
|
+
const items = []
|
|
378
|
+
for (const event of events) {
|
|
379
|
+
if (event === null || typeof event !== 'object') continue
|
|
380
|
+
const record = /** @type {Record<string, any>} */ (event)
|
|
381
|
+
if (record.type !== 'user/message') continue
|
|
382
|
+
const source = record.data?.source
|
|
383
|
+
if (source === null || typeof source !== 'object' || source.kind !== 'agent-instructions') continue
|
|
384
|
+
const text = messageTextOf(record.data)
|
|
385
|
+
items.push({
|
|
386
|
+
seq: typeof record.seq === 'number' ? record.seq : -1,
|
|
387
|
+
at: isoTime(record.time),
|
|
388
|
+
baseline: source.baseline === true,
|
|
389
|
+
bytes: byteLength(text),
|
|
390
|
+
text,
|
|
391
|
+
truncated: false,
|
|
392
|
+
})
|
|
393
|
+
}
|
|
394
|
+
return items
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
/**
|
|
398
|
+
* Response budget in event order: the item that crosses 2 MiB is clipped and
|
|
399
|
+
* later items are kept as empty, explicitly `truncated` rows so seq/bytes
|
|
400
|
+
* metadata stays visible. The final serialized-size guard below handles JSON
|
|
401
|
+
* escaping overhead this estimate cannot see.
|
|
402
|
+
* @param {Array<{ seq: number, at: string | null, baseline: boolean, bytes: number, text: string, truncated: boolean }>} items
|
|
403
|
+
*/
|
|
404
|
+
function applyOrderedBudget(items) {
|
|
405
|
+
let used = 2
|
|
406
|
+
let exhausted = false
|
|
407
|
+
for (const item of items) {
|
|
408
|
+
if (exhausted) {
|
|
409
|
+
item.text = ''
|
|
410
|
+
item.truncated = true
|
|
411
|
+
used += jsonBytes(item)
|
|
412
|
+
continue
|
|
413
|
+
}
|
|
414
|
+
const size = jsonBytes(item)
|
|
415
|
+
if (used + size <= RESPONSE_MAX_BYTES) {
|
|
416
|
+
used += size
|
|
417
|
+
continue
|
|
418
|
+
}
|
|
419
|
+
exhausted = true
|
|
420
|
+
const remaining = RESPONSE_MAX_BYTES - used
|
|
421
|
+
item.text = remaining > ITEM_ENVELOPE_BYTES ? truncateUtf8(item.text, remaining - ITEM_ENVELOPE_BYTES) : ''
|
|
422
|
+
item.truncated = true
|
|
423
|
+
used += jsonBytes(item)
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/**
|
|
428
|
+
* Exact view: replay one logical session log and keep only the durable
|
|
429
|
+
* instruction blocks.
|
|
430
|
+
* @param {Record<string, unknown>} params - already validated by {@link paramsOf}.
|
|
431
|
+
* @returns {Promise<Record<string, any>>}
|
|
432
|
+
*/
|
|
433
|
+
async function sessionValue(params) {
|
|
434
|
+
const sessionId = sessionIdOf(params)
|
|
435
|
+
const includeChanges = util.boolParam(params, 'includeChanges', true)
|
|
436
|
+
const sessionQuery = service('sessionQuery')
|
|
437
|
+
if (sessionQuery === undefined || sessionQuery === null || typeof sessionQuery.readSession !== 'function') {
|
|
438
|
+
return { available: false, mode: 'session', reason: '宿主未提供 sessionQuery.readSession' }
|
|
439
|
+
}
|
|
440
|
+
let snapshot
|
|
441
|
+
try {
|
|
442
|
+
snapshot = await sessionQuery.readSession(sessionId)
|
|
443
|
+
} catch (error) {
|
|
444
|
+
throw errors.notFound('无法读取该会话的指令事件', {
|
|
445
|
+
hint: `sessionQuery.readSession 失败:${util.redact(String(error?.message ?? error), ERROR_HINT_MAX)};会话可能不存在、尚未落盘或日志不可读,本模块不会修改会话`,
|
|
446
|
+
})
|
|
447
|
+
}
|
|
448
|
+
const events = Array.isArray(snapshot?.events) ? snapshot.events : []
|
|
449
|
+
let items = instructionItems(events)
|
|
450
|
+
if (!includeChanges) {
|
|
451
|
+
/** @type {Record<string, any> | null} */
|
|
452
|
+
let lastBaseline = null
|
|
453
|
+
for (const item of items) if (item.baseline) lastBaseline = item
|
|
454
|
+
items = lastBaseline === null ? [] : [lastBaseline]
|
|
455
|
+
}
|
|
456
|
+
applyOrderedBudget(items)
|
|
457
|
+
/** @returns {Record<string, any>} */
|
|
458
|
+
const project = () => ({ available: true, mode: 'session', exact: true, sessionId, items, count: items.length })
|
|
459
|
+
return capSessionResponse(project())
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
/**
|
|
463
|
+
* Final serialized-size guard for the session response: halve the last
|
|
464
|
+
* non-empty text, and only drop tail rows if metadata alone still exceeds the
|
|
465
|
+
* ceiling.
|
|
466
|
+
* @param {Record<string, any>} payload
|
|
467
|
+
*/
|
|
468
|
+
function capSessionResponse(payload) {
|
|
469
|
+
let result = payload
|
|
470
|
+
let passes = 0
|
|
471
|
+
while (jsonBytes(result) > RESPONSE_MAX_BYTES && passes < MAX_CLIP_PASSES) {
|
|
472
|
+
let trimmed = false
|
|
473
|
+
for (let index = result.items.length - 1; index >= 0; index -= 1) {
|
|
474
|
+
const item = result.items[index]
|
|
475
|
+
if (typeof item.text !== 'string' || item.text.length === 0) continue
|
|
476
|
+
item.text = truncateUtf8(item.text, Math.floor(byteLength(item.text) / 2))
|
|
477
|
+
item.truncated = true
|
|
478
|
+
trimmed = true
|
|
479
|
+
break
|
|
480
|
+
}
|
|
481
|
+
if (!trimmed) break
|
|
482
|
+
result.count = result.items.length
|
|
483
|
+
passes += 1
|
|
484
|
+
}
|
|
485
|
+
while (jsonBytes(result) > RESPONSE_MAX_BYTES && result.items.length > 0) {
|
|
486
|
+
result.items.pop()
|
|
487
|
+
result.count = result.items.length
|
|
488
|
+
}
|
|
489
|
+
return result
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
/**
|
|
493
|
+
* Latest committed baseline block; a session without a retained baseline
|
|
494
|
+
* falls back to its last instruction event.
|
|
495
|
+
* @param {readonly Record<string, any>[]} items
|
|
496
|
+
* @returns {Record<string, any> | null}
|
|
497
|
+
*/
|
|
498
|
+
function latestBaselineItem(items) {
|
|
499
|
+
for (let index = items.length - 1; index >= 0; index -= 1) {
|
|
500
|
+
if (items[index].baseline === true) return items[index]
|
|
501
|
+
}
|
|
502
|
+
return items.length > 0 ? items[items.length - 1] : null
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
/** Files view: the module is FULL only when the host `fs` service is present. */
|
|
506
|
+
function fsReady() {
|
|
507
|
+
const caps = core.caps
|
|
508
|
+
if (caps !== undefined && typeof caps.get === 'function') {
|
|
509
|
+
return caps.get('fs')?.present === true
|
|
510
|
+
}
|
|
511
|
+
const fs = service('fs')
|
|
512
|
+
return fs !== undefined && fs !== null
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
return {
|
|
516
|
+
id: 'instruction',
|
|
517
|
+
title: 'nav.instruction',
|
|
518
|
+
order: 40,
|
|
519
|
+
requires: ['fs'],
|
|
520
|
+
async init() {
|
|
521
|
+
// Read-only module: no warm-up, no host probe that could delay activation.
|
|
522
|
+
},
|
|
523
|
+
probe: () => (fsReady()
|
|
524
|
+
? { state: 'FULL', detail: '' }
|
|
525
|
+
: { state: 'BLOCKED', detail: '宿主未提供 fs 服务,无法读取指令文件' }),
|
|
526
|
+
methods: {
|
|
527
|
+
/** Small capability note for the navigation badge and the Overview page. */
|
|
528
|
+
'instruction.summary': async () => {
|
|
529
|
+
const agents = await sibling('agents.summary')
|
|
530
|
+
const moduleA = agents.ok === true
|
|
531
|
+
&& agents.value !== null
|
|
532
|
+
&& typeof agents.value === 'object'
|
|
533
|
+
&& /** @type {Record<string, any>} */ (agents.value).available === true
|
|
534
|
+
const summary = /** @type {Record<string, any>} */ ({
|
|
535
|
+
available: true,
|
|
536
|
+
exactView: 'session',
|
|
537
|
+
approximationView: 'files',
|
|
538
|
+
moduleA,
|
|
539
|
+
note: '只读:不写入任何指令文件',
|
|
540
|
+
})
|
|
541
|
+
if (moduleA) {
|
|
542
|
+
const maxBytes = /** @type {Record<string, any>} */ (agents.value).bytes?.maxBytes
|
|
543
|
+
summary.budgetMissing = !(typeof maxBytes === 'number' && Number.isFinite(maxBytes) && maxBytes > 0)
|
|
544
|
+
}
|
|
545
|
+
return summary
|
|
546
|
+
},
|
|
547
|
+
/** File-side chain metadata projected from module A's discovery. */
|
|
548
|
+
'instruction.chain': async (params) => {
|
|
549
|
+
const p = paramsOf(params)
|
|
550
|
+
return chainValue(cwdOf(p))
|
|
551
|
+
},
|
|
552
|
+
/** File-side rendered text passed through from module A. */
|
|
553
|
+
'instruction.preview': async (params) => {
|
|
554
|
+
const p = paramsOf(params)
|
|
555
|
+
return previewValue(cwdOf(p))
|
|
556
|
+
},
|
|
557
|
+
/** Exact instruction blocks recorded in one session log. */
|
|
558
|
+
'instruction.session': async (params) => {
|
|
559
|
+
const p = paramsOf(params)
|
|
560
|
+
return sessionValue(p)
|
|
561
|
+
},
|
|
562
|
+
/** Compare the files approximation with the session's last baseline block. */
|
|
563
|
+
'instruction.compare': async (params) => {
|
|
564
|
+
const p = paramsOf(params)
|
|
565
|
+
const cwd = cwdOf(p)
|
|
566
|
+
const [filesSide, sessionSide] = await Promise.all([previewValue(cwd), sessionValue(p)])
|
|
567
|
+
if (filesSide.available !== true) {
|
|
568
|
+
return {
|
|
569
|
+
available: false,
|
|
570
|
+
reason: textOrNull(filesSide.reason) ?? '文件侧预览不可用',
|
|
571
|
+
hint: textOrNull(filesSide.hint) ?? '请确认 AGENTS.md 模块与指令预算可用',
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
if (sessionSide.available !== true) {
|
|
575
|
+
return {
|
|
576
|
+
available: false,
|
|
577
|
+
reason: textOrNull(sessionSide.reason) ?? '会话侧不可用',
|
|
578
|
+
hint: textOrNull(sessionSide.hint) ?? '会话精确视图需要宿主 sessionQuery.readSession;可改用 instruction.preview 查看文件侧',
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
const items = Array.isArray(sessionSide.items) ? sessionSide.items : []
|
|
582
|
+
const baseline = latestBaselineItem(items)
|
|
583
|
+
const filesBytes = finiteNumber(filesSide.bytes) ?? 0
|
|
584
|
+
const sessionBytes = baseline === null ? 0 : /** @type {number} */ (baseline.bytes)
|
|
585
|
+
const sameText = baseline !== null
|
|
586
|
+
&& baseline.truncated !== true
|
|
587
|
+
&& typeof filesSide.text === 'string'
|
|
588
|
+
&& filesSide.text === baseline.text
|
|
589
|
+
/** @type {string[]} */
|
|
590
|
+
const explanations = []
|
|
591
|
+
if (!sameText) {
|
|
592
|
+
if (sessionBytes < filesBytes) {
|
|
593
|
+
explanations.push('会话侧更小:基线写入后指令文件变大,或当时触发了预算截断/精简提示。')
|
|
594
|
+
} else if (sessionBytes > filesBytes) {
|
|
595
|
+
explanations.push('会话侧更大:基线写入时指令文件比现在多,之后有文件被删除或缩短。')
|
|
596
|
+
} else {
|
|
597
|
+
explanations.push('字节数相同但内容不同:同一预算下的文件内容已变化。')
|
|
598
|
+
}
|
|
599
|
+
if (filesSide.exact !== true) {
|
|
600
|
+
explanations.push('文件侧不是精确文本(存在省略或截断),差异可能由重组近似造成。')
|
|
601
|
+
}
|
|
602
|
+
if (baseline !== null && baseline.truncated === true) {
|
|
603
|
+
explanations.push('会话侧基线块在本次响应里被截断,逐字节比较不可信。')
|
|
604
|
+
}
|
|
605
|
+
explanations.push('会话侧是写入当时的快照,文件侧是现在磁盘上的内容;两者不同通常说明指令在会话开始后被改过。')
|
|
606
|
+
}
|
|
607
|
+
return {
|
|
608
|
+
available: true,
|
|
609
|
+
mode: 'compare',
|
|
610
|
+
filesBytes,
|
|
611
|
+
sessionBytes,
|
|
612
|
+
deltaBytes: sessionBytes - filesBytes,
|
|
613
|
+
sameText,
|
|
614
|
+
exactFiles: filesSide.exact === true,
|
|
615
|
+
sessionItems: finiteNumber(sessionSide.count) ?? items.length,
|
|
616
|
+
sessionSeq: baseline === null ? null : baseline.seq,
|
|
617
|
+
sessionAt: baseline === null ? null : baseline.at,
|
|
618
|
+
explanations,
|
|
619
|
+
note: '对比只读:files 侧是按预算重组的近似文本(exactFiles 表示是否精确),session 侧取最后一条 baseline 指令块(无 baseline 时取最后一条指令事件);sameText 为逐字节比较,任一侧文本被截断时为 false。',
|
|
620
|
+
}
|
|
621
|
+
},
|
|
622
|
+
},
|
|
623
|
+
}
|
|
624
|
+
}
|