dsh-agent-control-center 0.3.1 → 0.4.1
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 +85 -0
- package/README.md +6 -4
- package/README.zh.md +6 -4
- package/client.js +1142 -18
- package/docs/01-CONTRACT.md +1 -1
- package/docs/05-ACCEPTANCE-EVIDENCE.md +79 -0
- package/docs/07-GUIDE.md +1 -1
- package/docs/08-COMPATIBILITY.md +23 -4
- package/docs/09-ARCHITECTURE.md +2 -2
- package/docs/12-PLUGIN-HEALTH.md +49 -0
- package/docs/13-PAGE-REGRESSION-0.4.0.md +47 -0
- package/index.js +4 -1
- package/lib/core/caps.js +28 -7
- package/lib/core/compat.js +16 -5
- package/lib/core/http.js +17 -1
- package/lib/core/index.js +15 -1
- package/lib/core/store.js +5 -1
- package/lib/core/tools-view.js +92 -0
- package/lib/modules/b-tools.js +62 -38
- package/lib/modules/e-meta.js +12 -10
- package/lib/modules/j-instruction.js +162 -2
- package/lib/modules/l-health.js +862 -0
- package/package.json +1 -1
- package/scripts/verify.mjs +1 -0
- package/src/client/i18n/health.js +260 -0
- package/src/client/pages/health.js +832 -0
- package/src/client/pages/tools.js +42 -16
package/lib/modules/b-tools.js
CHANGED
|
@@ -21,6 +21,7 @@
|
|
|
21
21
|
* @module dsh-agent-control-center/modules/tools
|
|
22
22
|
*/
|
|
23
23
|
import { createCache, resolveCacheTtlMs, scheduleWarmup, withCacheMeta } from '../core/cache.js'
|
|
24
|
+
import { isExecutable, readDefinitions, readSchemaProjection, toolsApiKind } from '../core/tools-view.js'
|
|
24
25
|
|
|
25
26
|
/** List descriptions are truncated; `tools.detail` carries the full text. */
|
|
26
27
|
const DESCRIPTION_LIMIT = 240
|
|
@@ -206,12 +207,7 @@ export default function createModule(core) {
|
|
|
206
207
|
* @param {unknown} scope
|
|
207
208
|
*/
|
|
208
209
|
function readView(tools, scope) {
|
|
209
|
-
|
|
210
|
-
const definitions = tools.definitions()
|
|
211
|
-
return { ok: true, definitions: Array.isArray(definitions) ? definitions : [] }
|
|
212
|
-
}
|
|
213
|
-
const definitions = tools.definitions(scope)
|
|
214
|
-
return { ok: true, definitions: Array.isArray(definitions) ? definitions : [] }
|
|
210
|
+
return readDefinitions(tools, scope)
|
|
215
211
|
}
|
|
216
212
|
|
|
217
213
|
/** @param {string} name @param {{ inGlobal: boolean, scopes: string[] }} checks */
|
|
@@ -240,8 +236,8 @@ export default function createModule(core) {
|
|
|
240
236
|
*/
|
|
241
237
|
async function registrySnapshot(options = {}) {
|
|
242
238
|
const tools = service('tools')
|
|
243
|
-
if (tools === undefined ||
|
|
244
|
-
return unavailable('宿主未提供 tools 服务(或缺少 definitions 方法)', '工具清单只能来自宿主工具注册表;本模块不做磁盘推断')
|
|
239
|
+
if (tools === undefined || toolsApiKind(tools) === null) {
|
|
240
|
+
return unavailable('宿主未提供 tools 服务(或缺少 getAll/definitions 方法)', '工具清单只能来自宿主工具注册表;本模块不做磁盘推断')
|
|
245
241
|
}
|
|
246
242
|
const globalView = readView(tools, undefined)
|
|
247
243
|
const globalByName = new Map()
|
|
@@ -251,17 +247,7 @@ export default function createModule(core) {
|
|
|
251
247
|
}
|
|
252
248
|
}
|
|
253
249
|
|
|
254
|
-
|
|
255
|
-
if (typeof tools.schemas === 'function') {
|
|
256
|
-
try {
|
|
257
|
-
const schemas = tools.schemas()
|
|
258
|
-
schemaProjection = { available: true, count: Array.isArray(schemas) ? schemas.length : null, reason: null }
|
|
259
|
-
} catch (error) {
|
|
260
|
-
schemaProjection = { available: false, count: null, reason: util.redact(String(error?.message ?? error), 200) }
|
|
261
|
-
}
|
|
262
|
-
} else {
|
|
263
|
-
schemaProjection = { available: false, count: null, reason: '宿主 tools 服务没有 schemas(),无法核对模型面投影' }
|
|
264
|
-
}
|
|
250
|
+
const schemaProjection = readSchemaProjection(tools)
|
|
265
251
|
|
|
266
252
|
const agentsService = service('agents')
|
|
267
253
|
let liveAgents = []
|
|
@@ -448,6 +434,32 @@ export default function createModule(core) {
|
|
|
448
434
|
* `maxSessions` and a soft deadline and reports every truncation.
|
|
449
435
|
* @param {{ from: number, to: number, maxSessions: number, timeBudgetMs: number, sampleLimit: number }} options
|
|
450
436
|
*/
|
|
437
|
+
/**
|
|
438
|
+
* Fold results keyed by the scan bounds. The page issues summary + list +
|
|
439
|
+
* detail in sequence; without this memo each one re-reads the same sessions.
|
|
440
|
+
*/
|
|
441
|
+
const historyMemo = new Map()
|
|
442
|
+
|
|
443
|
+
/** @param {{ from: number, to: number, maxSessions: number, timeBudgetMs: number, sampleLimit: number, refresh?: boolean }} options */
|
|
444
|
+
async function sharedHistory(options) {
|
|
445
|
+
const key = `${options.from}|${options.to}|${options.maxSessions}|${options.timeBudgetMs}|${options.sampleLimit}`
|
|
446
|
+
const ttl = typeof core.config?.cacheTtlMs === 'number' ? core.config.cacheTtlMs : 60 * 1000
|
|
447
|
+
const entry = historyMemo.get(key)
|
|
448
|
+
const now = Date.now()
|
|
449
|
+
if (options.refresh !== true && entry !== undefined && now - entry.at < ttl) {
|
|
450
|
+
return withCacheMeta({ value: entry.value, cached: true, ageMs: now - entry.at })
|
|
451
|
+
}
|
|
452
|
+
const value = await aggregateHistory(options)
|
|
453
|
+
// A degraded block is worth keeping too: the next request avoids the
|
|
454
|
+
// failure path without pretending it succeeded.
|
|
455
|
+
historyMemo.set(key, { at: Date.now(), value })
|
|
456
|
+
if (historyMemo.size > 24) {
|
|
457
|
+
const oldest = [...historyMemo.entries()].sort((left, right) => left[1].at - right[1].at)[0]
|
|
458
|
+
if (oldest !== undefined) historyMemo.delete(oldest[0])
|
|
459
|
+
}
|
|
460
|
+
return withCacheMeta({ value, cached: false, ageMs: 0 })
|
|
461
|
+
}
|
|
462
|
+
|
|
451
463
|
async function aggregateHistory(options) {
|
|
452
464
|
const query = service('sessionQuery')
|
|
453
465
|
if (query === undefined || typeof query.listSessions !== 'function' || typeof query.readSession !== 'function') {
|
|
@@ -664,6 +676,10 @@ export default function createModule(core) {
|
|
|
664
676
|
totals: history.totals,
|
|
665
677
|
errorState: history.errorState,
|
|
666
678
|
failuresWithoutIdentity: history.failuresWithoutIdentity,
|
|
679
|
+
// Freshness of the shared history fold (the way to force a re-read is
|
|
680
|
+
// `refresh: true` on the request).
|
|
681
|
+
cached: history.cached === true,
|
|
682
|
+
cacheAgeMs: typeof history.cacheAgeMs === 'number' ? history.cacheAgeMs : 0,
|
|
667
683
|
}
|
|
668
684
|
}
|
|
669
685
|
|
|
@@ -706,13 +722,8 @@ export default function createModule(core) {
|
|
|
706
722
|
const visible = view.names.has(name)
|
|
707
723
|
if (!visible) return { id: view.id, available: true, visible: false, conditional: null }
|
|
708
724
|
let conditional = null
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
conditional = registry.tools.executable(name, view.agent) === undefined
|
|
712
|
-
} catch {
|
|
713
|
-
conditional = null
|
|
714
|
-
}
|
|
715
|
-
}
|
|
725
|
+
const executable = isExecutable(registry.tools, name, view.agent)
|
|
726
|
+
if (executable !== null) conditional = executable === false
|
|
716
727
|
const shadowed = globalDefinition !== undefined && view.names.get(name) !== globalDefinition
|
|
717
728
|
return { id: view.id, available: true, visible: true, conditional, shadowed }
|
|
718
729
|
})
|
|
@@ -825,6 +836,8 @@ export default function createModule(core) {
|
|
|
825
836
|
return {
|
|
826
837
|
maxSessions: util.numParam(params, 'maxSessions', { min: 1, max: 200, fallback: DEFAULTS.maxSessions }),
|
|
827
838
|
timeBudgetMs: util.numParam(params, 'timeBudgetMs', { min: 100, max: 20000, fallback: DEFAULTS.timeBudgetMs }),
|
|
839
|
+
// The host cache serves repeat reads; an explicit refresh re-reads sessions.
|
|
840
|
+
refresh: util.boolParam(params, 'refresh', false),
|
|
828
841
|
}
|
|
829
842
|
}
|
|
830
843
|
|
|
@@ -861,12 +874,13 @@ export default function createModule(core) {
|
|
|
861
874
|
}
|
|
862
875
|
const current = resolveCurrentAgent(registry.agentViews, agentId)
|
|
863
876
|
const history = includeHistory
|
|
864
|
-
? await
|
|
877
|
+
? await sharedHistory({
|
|
865
878
|
from: window.from,
|
|
866
879
|
to: window.to,
|
|
867
880
|
maxSessions: historyOptions.maxSessions,
|
|
868
881
|
timeBudgetMs: historyOptions.timeBudgetMs,
|
|
869
882
|
sampleLimit: 5,
|
|
883
|
+
refresh: historyOptions.refresh,
|
|
870
884
|
})
|
|
871
885
|
: unavailable('按参数关闭了历史调用统计(includeHistory=false)')
|
|
872
886
|
|
|
@@ -924,12 +938,13 @@ export default function createModule(core) {
|
|
|
924
938
|
return { available: false, reason: registry.reason, hint: registry.hint, name }
|
|
925
939
|
}
|
|
926
940
|
const current = resolveCurrentAgent(registry.agentViews, agentId)
|
|
927
|
-
const history = await
|
|
941
|
+
const history = await sharedHistory({
|
|
928
942
|
from: window.from,
|
|
929
943
|
to: window.to,
|
|
930
944
|
maxSessions: historyOptions.maxSessions,
|
|
931
945
|
timeBudgetMs: historyOptions.timeBudgetMs,
|
|
932
946
|
sampleLimit,
|
|
947
|
+
refresh: historyOptions.refresh,
|
|
933
948
|
})
|
|
934
949
|
const known = registry.globalByName.has(name)
|
|
935
950
|
|| registry.agentViews.some((view) => view.available && view.names.has(name))
|
|
@@ -937,19 +952,24 @@ export default function createModule(core) {
|
|
|
937
952
|
|| (history.available === true && history.byTool.has(name))
|
|
938
953
|
if (!known) throw core.errors.notFound(`工具不存在:${name}`, { hint: '注册表与历史事件中都没有该名称' })
|
|
939
954
|
|
|
940
|
-
const
|
|
955
|
+
const globalDefinition = registry.globalByName.get(name)
|
|
956
|
+
const scopedDefinition = globalDefinition === undefined
|
|
957
|
+
? [...registry.agentViews, ...registry.presetViews]
|
|
958
|
+
.filter((view) => view.available === true && view.names instanceof Map)
|
|
959
|
+
.map((view) => view.names.get(name))
|
|
960
|
+
.find((candidate) => candidate !== undefined && candidate !== null)
|
|
961
|
+
: undefined
|
|
962
|
+
const definition = globalDefinition === undefined ? scopedDefinition : globalDefinition
|
|
963
|
+
const schemaSource = globalDefinition !== undefined ? 'global' : definition === undefined ? null : 'scoped'
|
|
941
964
|
const inspected = definition === undefined ? null : inspectDefinition(definition)
|
|
942
965
|
const item = buildItem(name, registry, { history, current, includePresets })
|
|
943
966
|
const agentVisibility = registry.agentViews.map((view) => {
|
|
944
967
|
if (!view.available) return { id: view.id, available: false, visible: null, reason: view.reason }
|
|
945
968
|
const visible = view.names.has(name)
|
|
946
969
|
let conditional = null
|
|
947
|
-
if (visible
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
} catch {
|
|
951
|
-
conditional = null
|
|
952
|
-
}
|
|
970
|
+
if (visible) {
|
|
971
|
+
const executable = isExecutable(registry.tools, name, view.agent)
|
|
972
|
+
if (executable !== null) conditional = executable === false
|
|
953
973
|
}
|
|
954
974
|
return {
|
|
955
975
|
id: view.id,
|
|
@@ -1011,8 +1031,12 @@ export default function createModule(core) {
|
|
|
1011
1031
|
source: item.source,
|
|
1012
1032
|
registered: item.registered,
|
|
1013
1033
|
registeredWhere: item.registeredWhere,
|
|
1034
|
+
// Where the schema came from: the global registry, a scoped view, or
|
|
1035
|
+
// nowhere (a name seen only in history has no definition to read).
|
|
1036
|
+
schemaSource,
|
|
1037
|
+
definitionAvailable: inspected !== null,
|
|
1014
1038
|
definition: inspected === null
|
|
1015
|
-
? unavailable('
|
|
1039
|
+
? unavailable('该名称只出现在历史事件里,全局与 Scoped 注册视图都没有它的定义,因此 schema 不可读')
|
|
1016
1040
|
: {
|
|
1017
1041
|
available: true,
|
|
1018
1042
|
descriptionLength: inspected.descriptionLength,
|
|
@@ -1200,8 +1224,8 @@ export default function createModule(core) {
|
|
|
1200
1224
|
},
|
|
1201
1225
|
probe: () => {
|
|
1202
1226
|
const tools = service('tools')
|
|
1203
|
-
if (tools === undefined ||
|
|
1204
|
-
return { state: 'BLOCKED', detail: '宿主未提供 tools 服务(definitions)' }
|
|
1227
|
+
if (tools === undefined || toolsApiKind(tools) === null) {
|
|
1228
|
+
return { state: 'BLOCKED', detail: '宿主未提供 tools 服务(getAll/definitions)' }
|
|
1205
1229
|
}
|
|
1206
1230
|
const query = service('sessionQuery')
|
|
1207
1231
|
if (query === undefined || typeof query.listSessions !== 'function' || typeof query.readSession !== 'function') {
|
package/lib/modules/e-meta.js
CHANGED
|
@@ -29,6 +29,7 @@
|
|
|
29
29
|
*/
|
|
30
30
|
import path from 'node:path'
|
|
31
31
|
import { ensureDir, writeJsonAtomic } from '../core/atomic.js'
|
|
32
|
+
import { isExecutable, readDefinitions, toolsApiKind } from '../core/tools-view.js'
|
|
32
33
|
|
|
33
34
|
const EXPORT_SCHEMA_VERSION = 1
|
|
34
35
|
const EXPORT_KIND = 'dsh-agent-control-center/config-export'
|
|
@@ -280,15 +281,15 @@ export default function createModule(core) {
|
|
|
280
281
|
/** Visible tool count for one Agent (`tools.definitions(agent)`), never executes. */
|
|
281
282
|
function toolCountOf(agent) {
|
|
282
283
|
const tools = service('tools')
|
|
283
|
-
if (tools === undefined ||
|
|
284
|
+
if (tools === undefined || toolsApiKind(tools) === null) {
|
|
284
285
|
return unavailable('宿主未提供 tools 服务')
|
|
285
286
|
}
|
|
286
287
|
try {
|
|
287
|
-
const definitions = tools.definitions
|
|
288
|
+
const definitions = readDefinitions(tools, agent).definitions
|
|
288
289
|
return {
|
|
289
290
|
available: true,
|
|
290
291
|
value: Array.isArray(definitions) ? definitions.length : 0,
|
|
291
|
-
basis: '
|
|
292
|
+
basis: 'Agent 作用域可见数(readDefinitions(agent);0.2.3 起为 getAll(agent))(统计口径为可见工具,不是执行探活)',
|
|
292
293
|
}
|
|
293
294
|
} catch (error) {
|
|
294
295
|
return unavailable('读取 Agent 可见工具失败', redactText(error?.message ?? error, 160))
|
|
@@ -355,7 +356,7 @@ export default function createModule(core) {
|
|
|
355
356
|
async function toolsForPresets(presetIds) {
|
|
356
357
|
const tools = service('tools')
|
|
357
358
|
const presets = service('agentPresets')
|
|
358
|
-
if (tools === undefined ||
|
|
359
|
+
if (tools === undefined || toolsApiKind(tools) === null) {
|
|
359
360
|
return { available: false, reason: '宿主未提供 tools 服务', results: new Map() }
|
|
360
361
|
}
|
|
361
362
|
if (presets === undefined || typeof presets.acquireScope !== 'function') {
|
|
@@ -366,21 +367,22 @@ export default function createModule(core) {
|
|
|
366
367
|
let lease
|
|
367
368
|
try {
|
|
368
369
|
lease = await presets.acquireScope(presetId)
|
|
369
|
-
const definitions = tools
|
|
370
|
+
const definitions = readDefinitions(tools, lease.key).definitions
|
|
370
371
|
const names = Array.isArray(definitions) ? definitions.map((definition) => text(definition?.name)).filter((name) => name.length > 0) : []
|
|
371
372
|
let conditional = null
|
|
372
|
-
|
|
373
|
+
const capabilityKnown = typeof tools?.executable === 'function' || typeof tools?.get === 'function'
|
|
374
|
+
if (capabilityKnown) {
|
|
373
375
|
conditional = 0
|
|
374
376
|
for (const name of names) {
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
} catch {
|
|
377
|
+
const executable = isExecutable(tools, name, lease.key)
|
|
378
|
+
if (executable === null) {
|
|
378
379
|
conditional = null
|
|
379
380
|
break
|
|
380
381
|
}
|
|
382
|
+
if (executable === false) conditional += 1
|
|
381
383
|
}
|
|
382
384
|
}
|
|
383
|
-
results.set(presetId, { available: true, visible: names.length, conditional, basis: '
|
|
385
|
+
results.set(presetId, { available: true, visible: names.length, conditional, basis: '作用域可见数(readDefinitions(lease.key);0.2.3 起为 getAll);acquireScope 租约已释放' })
|
|
384
386
|
} catch (error) {
|
|
385
387
|
results.set(presetId, unavailable('读取预设可见工具失败', redactText(error?.message ?? error, 160)))
|
|
386
388
|
} finally {
|
|
@@ -26,6 +26,12 @@ const ITEM_ENVELOPE_BYTES = 96
|
|
|
26
26
|
const MAX_CLIP_PASSES = 12
|
|
27
27
|
/** Remote failure messages are bounded before they enter a hint. */
|
|
28
28
|
const ERROR_HINT_MAX = 160
|
|
29
|
+
/** One instruction-size sample is recorded at most this often per working directory. */
|
|
30
|
+
const TREND_MIN_INTERVAL_MS = 10 * 60 * 1000
|
|
31
|
+
/** Samples kept in `state.json`; the cap is on the whole ledger, oldest dropped first. */
|
|
32
|
+
const TREND_MAX_SAMPLES = 500
|
|
33
|
+
/** Samples older than this are pruned; the page groups them by local day. */
|
|
34
|
+
const TREND_RETENTION_DAYS = 180
|
|
29
35
|
|
|
30
36
|
/** @param {unknown} value @returns {number} */
|
|
31
37
|
function byteLength(value) {
|
|
@@ -83,6 +89,87 @@ function stringOrNull(value) {
|
|
|
83
89
|
/**
|
|
84
90
|
* @param {Record<string, any>} core
|
|
85
91
|
*/
|
|
92
|
+
/**
|
|
93
|
+
* Append one instruction-size sample to the plugin's own state document.
|
|
94
|
+
*
|
|
95
|
+
* Sampling is throttled per working directory so a page that refreshes often
|
|
96
|
+
* cannot bloat `state.json`, and the ledger is pruned by age and count inside
|
|
97
|
+
* the same atomic read-modify-write that stores it. Failures are reported to
|
|
98
|
+
* the caller but never break the read-only view being displayed.
|
|
99
|
+
*
|
|
100
|
+
* @param {Record<string, any>} storage plugin storage (`core.storage`)
|
|
101
|
+
* @param {{ cwd: string | null, projectRoot: string | null, userGlobalBytes: number, projectBytes: number, totalBytes: number, maxBytes: number | null, exact: boolean }} sample
|
|
102
|
+
* @returns {Promise<{ recorded: boolean, reason?: string }>}
|
|
103
|
+
*/
|
|
104
|
+
async function appendTrendSample(storage, sample) {
|
|
105
|
+
if (typeof storage?.updateState !== 'function') return { recorded: false, reason: '插件存储不可用' }
|
|
106
|
+
const at = Date.now()
|
|
107
|
+
/** @type {{ recorded: boolean, reason?: string }} */
|
|
108
|
+
let outcome = { recorded: false }
|
|
109
|
+
try {
|
|
110
|
+
if (typeof storage.ensureLayout === 'function') await storage.ensureLayout()
|
|
111
|
+
await storage.updateState((/** @type {Record<string, any>} */ state) => {
|
|
112
|
+
const current = state.trend !== null && typeof state.trend === 'object' && Array.isArray(state.trend.samples)
|
|
113
|
+
? state.trend
|
|
114
|
+
: { version: 1, samples: [] }
|
|
115
|
+
const samples = current.samples.filter((/** @type {any} */ entry) => entry !== null && typeof entry === 'object' && Number.isFinite(entry.at))
|
|
116
|
+
const last = samples[samples.length - 1]
|
|
117
|
+
if (last !== undefined && last.cwd === sample.cwd && at - last.at < TREND_MIN_INTERVAL_MS) {
|
|
118
|
+
outcome = { recorded: false, reason: '距上次采样不足 10 分钟' }
|
|
119
|
+
state.trend = { ...current, version: 1, samples }
|
|
120
|
+
return
|
|
121
|
+
}
|
|
122
|
+
samples.push({ at, ...sample })
|
|
123
|
+
const cutoff = at - TREND_RETENTION_DAYS * 24 * 60 * 60 * 1000
|
|
124
|
+
const kept = samples.filter((/** @type {any} */ entry) => entry.at >= cutoff).slice(-TREND_MAX_SAMPLES)
|
|
125
|
+
state.trend = { version: 1, samples: kept }
|
|
126
|
+
outcome = { recorded: true }
|
|
127
|
+
})
|
|
128
|
+
} catch (error) {
|
|
129
|
+
return { recorded: false, reason: `采样失败:${String(/** @type {any} */ (error)?.message ?? error).slice(0, 120)}` }
|
|
130
|
+
}
|
|
131
|
+
return outcome
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Group recorded samples by local calendar day.
|
|
136
|
+
* @param {any[]} samples
|
|
137
|
+
* @param {number} days window size, ending today
|
|
138
|
+
* @returns {{ day: string, samples: number, avgBytes: number, maxBytes: number, lastBytes: number, budget: number | null }[]}
|
|
139
|
+
*/
|
|
140
|
+
function groupTrendByDay(samples, days) {
|
|
141
|
+
const now = new Date()
|
|
142
|
+
/** @type {Map<string, any[]>} */
|
|
143
|
+
const byDay = new Map()
|
|
144
|
+
for (let index = days - 1; index >= 0; index -= 1) {
|
|
145
|
+
const date = new Date(now.getFullYear(), now.getMonth(), now.getDate() - index)
|
|
146
|
+
byDay.set(dayKey(date), [])
|
|
147
|
+
}
|
|
148
|
+
for (const sample of samples) {
|
|
149
|
+
const date = new Date(sample.at)
|
|
150
|
+
const key = dayKey(date)
|
|
151
|
+
const bucket = byDay.get(key)
|
|
152
|
+
if (bucket !== undefined) bucket.push(sample)
|
|
153
|
+
}
|
|
154
|
+
return [...byDay.entries()].map(([day, entries]) => ({
|
|
155
|
+
day,
|
|
156
|
+
samples: entries.length,
|
|
157
|
+
avgBytes: entries.length === 0 ? 0 : Math.round(entries.reduce((total, entry) => total + (finiteNumber(entry.totalBytes) ?? 0), 0) / entries.length),
|
|
158
|
+
maxBytes: entries.length === 0 ? 0 : Math.max(...entries.map((entry) => finiteNumber(entry.totalBytes) ?? 0)),
|
|
159
|
+
lastBytes: entries.length === 0 ? 0 : finiteNumber(entries[entries.length - 1].totalBytes) ?? 0,
|
|
160
|
+
budget: entries.length === 0 ? null : finiteNumber(entries[entries.length - 1].maxBytes),
|
|
161
|
+
}))
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* @param {Date} date
|
|
166
|
+
* @returns {string} `YYYY-MM-DD` in local time, the same key the usage ledger uses
|
|
167
|
+
*/
|
|
168
|
+
function dayKey(date) {
|
|
169
|
+
const pad = (/** @type {number} */ value) => String(value).padStart(2, '0')
|
|
170
|
+
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`
|
|
171
|
+
}
|
|
172
|
+
|
|
86
173
|
export default function createModule(core) {
|
|
87
174
|
const util = core.util
|
|
88
175
|
const errors = core.errors
|
|
@@ -424,6 +511,32 @@ export default function createModule(core) {
|
|
|
424
511
|
}
|
|
425
512
|
}
|
|
426
513
|
|
|
514
|
+
/**
|
|
515
|
+
* Record one sample from a files-side payload. Best-effort: a failed write
|
|
516
|
+
* must not break the view the caller is about to render.
|
|
517
|
+
* @param {Record<string, any>} value
|
|
518
|
+
* @returns {Promise<void>}
|
|
519
|
+
*/
|
|
520
|
+
async function recordTrend(value) {
|
|
521
|
+
if (value === null || typeof value !== 'object' || value.available !== true) return
|
|
522
|
+
const budget = value.budget !== null && typeof value.budget === 'object' ? value.budget : {}
|
|
523
|
+
const userGlobal = budget.userGlobal !== null && typeof budget.userGlobal === 'object' ? budget.userGlobal : {}
|
|
524
|
+
const project = budget.project !== null && typeof budget.project === 'object' ? budget.project : {}
|
|
525
|
+
try {
|
|
526
|
+
await appendTrendSample(core.storage, {
|
|
527
|
+
cwd: typeof value.cwd === 'string' ? value.cwd : null,
|
|
528
|
+
projectRoot: typeof value.projectRoot === 'string' ? value.projectRoot : null,
|
|
529
|
+
userGlobalBytes: finiteNumber(userGlobal.bytes) ?? 0,
|
|
530
|
+
projectBytes: finiteNumber(project.bytes) ?? 0,
|
|
531
|
+
totalBytes: finiteNumber(value.bytes) ?? 0,
|
|
532
|
+
maxBytes: finiteNumber(budget.maxBytes),
|
|
533
|
+
exact: value.exact === true,
|
|
534
|
+
})
|
|
535
|
+
} catch {
|
|
536
|
+
/* the trend ledger is a nicety; it must never fail the rendered view */
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
|
|
427
540
|
/**
|
|
428
541
|
* Exact view: replay one logical session log and keep only the durable
|
|
429
542
|
* instruction blocks.
|
|
@@ -549,10 +662,57 @@ export default function createModule(core) {
|
|
|
549
662
|
const p = paramsOf(params)
|
|
550
663
|
return chainValue(cwdOf(p))
|
|
551
664
|
},
|
|
552
|
-
/** File-side rendered text passed through from module A. */
|
|
665
|
+
/** File-side rendered text passed through from module A (also samples the size ledger). */
|
|
553
666
|
'instruction.preview': async (params) => {
|
|
554
667
|
const p = paramsOf(params)
|
|
555
|
-
|
|
668
|
+
const value = await previewValue(cwdOf(p))
|
|
669
|
+
await recordTrend(value)
|
|
670
|
+
return value
|
|
671
|
+
},
|
|
672
|
+
/**
|
|
673
|
+
* Instruction-size trend: samples recorded whenever a files-side view is
|
|
674
|
+
* produced, grouped by local day. Read-only; nothing here touches an
|
|
675
|
+
* instruction file.
|
|
676
|
+
*/
|
|
677
|
+
'instruction.trend': async (params) => {
|
|
678
|
+
const p = paramsOf(params)
|
|
679
|
+
const days = Math.trunc(util.numParam(p, 'days', { min: 1, max: 180, fallback: 30 }))
|
|
680
|
+
/** @type {Record<string, any>} */
|
|
681
|
+
let trend = { version: 1, samples: [] }
|
|
682
|
+
try {
|
|
683
|
+
if (typeof core.storage?.readState === 'function') {
|
|
684
|
+
const state = await core.storage.readState()
|
|
685
|
+
if (state.trend !== null && typeof state.trend === 'object' && Array.isArray(state.trend.samples)) trend = state.trend
|
|
686
|
+
}
|
|
687
|
+
} catch (error) {
|
|
688
|
+
return {
|
|
689
|
+
available: false,
|
|
690
|
+
reason: '读取趋势数据失败',
|
|
691
|
+
hint: util.redact(String(/** @type {any} */ (error)?.message ?? error), ERROR_HINT_MAX),
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
const samples = trend.samples.filter((/** @type {any} */ entry) => entry !== null && typeof entry === 'object' && Number.isFinite(entry.at))
|
|
695
|
+
const series = groupTrendByDay(samples, days)
|
|
696
|
+
const recorded = series.filter((entry) => entry.samples > 0)
|
|
697
|
+
const first = recorded[0]
|
|
698
|
+
const last = recorded[recorded.length - 1]
|
|
699
|
+
return {
|
|
700
|
+
available: true,
|
|
701
|
+
mode: 'trend',
|
|
702
|
+
days,
|
|
703
|
+
series,
|
|
704
|
+
recordedDays: recorded.length,
|
|
705
|
+
totalSamples: samples.length,
|
|
706
|
+
deltaBytes: first === undefined || last === undefined ? 0 : last.lastBytes - first.avgBytes,
|
|
707
|
+
firstDay: first === undefined ? null : first.day,
|
|
708
|
+
lastDay: last === undefined ? null : last.day,
|
|
709
|
+
budget: last === undefined ? null : last.budget,
|
|
710
|
+
overBudgetDays: recorded.filter((entry) => entry.budget !== null && entry.maxBytes > entry.budget).length,
|
|
711
|
+
minIntervalMs: TREND_MIN_INTERVAL_MS,
|
|
712
|
+
retentionDays: TREND_RETENTION_DAYS,
|
|
713
|
+
maxSamples: TREND_MAX_SAMPLES,
|
|
714
|
+
note: '样本在每次生成「按文件」视图时记录(同一目录 10 分钟内只记一次,最多 500 条、保留 180 天);只记录字节与预算,不记录指令内容。',
|
|
715
|
+
}
|
|
556
716
|
},
|
|
557
717
|
/** Exact instruction blocks recorded in one session log. */
|
|
558
718
|
'instruction.session': async (params) => {
|