@cheemsup/dsh-plugin-console 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +85 -2
- package/cordis.patch.yml +5 -0
- package/lib/client.activity.js +222 -0
- package/lib/client.apply.js +171 -0
- package/lib/client.changes.js +206 -0
- package/lib/client.cleanup.js +270 -0
- package/lib/client.control.js +242 -0
- package/lib/client.dialog.js +77 -0
- package/lib/client.draft.js +280 -0
- package/lib/client.editor-messages.js +421 -0
- package/lib/client.editor-store.js +266 -0
- package/lib/client.editor.js +433 -0
- package/lib/client.effects.js +115 -0
- package/lib/client.influence.js +361 -0
- package/lib/client.js +216 -0
- package/lib/client.page.js +584 -0
- package/lib/client.plugin-filters.js +62 -0
- package/lib/client.plugins.js +504 -0
- package/lib/client.preview-messages.js +495 -0
- package/lib/client.preview-raw.js +132 -0
- package/lib/client.preview-store.js +128 -0
- package/lib/client.preview-tools.js +194 -0
- package/lib/client.preview.js +447 -0
- package/lib/client.schema.js +327 -0
- package/lib/client.search.js +408 -0
- package/lib/client.session-detail.js +503 -0
- package/lib/client.sessions.js +495 -0
- package/lib/client.shared.js +559 -0
- package/lib/client.store.js +452 -0
- package/lib/client.styles.js +524 -0
- package/lib/client.template-card.js +240 -0
- package/lib/client.tools.js +366 -0
- package/lib/client.workspace-picker.js +204 -0
- package/lib/host/activity.js +252 -0
- package/lib/host/assembly-preview.js +244 -0
- package/lib/host/attribution.js +307 -0
- package/lib/host/catalog.js +133 -0
- package/lib/host/categorize.js +40 -0
- package/lib/host/constants.js +66 -0
- package/lib/host/control.js +159 -0
- package/lib/host/entries.js +289 -0
- package/lib/host/fiber.js +86 -0
- package/lib/host/fs.js +99 -0
- package/lib/host/health.js +178 -0
- package/lib/host/http.js +65 -0
- package/lib/host/impact.js +132 -0
- package/lib/host/layers.js +132 -0
- package/lib/host/masks.js +145 -0
- package/lib/host/modes.js +96 -0
- package/lib/host/names.js +44 -0
- package/lib/host/patch-scan.js +103 -0
- package/lib/host/preview-conditions.js +281 -0
- package/lib/host/preview-contexts.js +174 -0
- package/lib/host/preview-envelope.js +31 -0
- package/lib/host/preview-instructions.js +450 -0
- package/lib/host/preview-messages.js +284 -0
- package/lib/host/preview-modules.js +233 -0
- package/lib/host/preview-skills.js +200 -0
- package/lib/host/prompt.js +213 -0
- package/lib/host/recipe-overlay.js +209 -0
- package/lib/host/request-preview.js +114 -0
- package/lib/host/routes/activation.js +96 -0
- package/lib/host/routes/activity.js +22 -0
- package/lib/host/routes/apply.js +93 -0
- package/lib/host/routes/cleanup.js +62 -0
- package/lib/host/routes/control.js +22 -0
- package/lib/host/routes/impact.js +19 -0
- package/lib/host/routes/operations.js +22 -0
- package/lib/host/routes/preview.js +58 -0
- package/lib/host/routes/session-influence.js +23 -0
- package/lib/host/routes/snapshot.js +21 -0
- package/lib/host/routes/template.js +54 -0
- package/lib/host/routes/templates.js +28 -0
- package/lib/host/scope-impact.js +125 -0
- package/lib/host/session-events.js +39 -0
- package/lib/host/session-influence.js +475 -0
- package/lib/host/sessions.js +293 -0
- package/lib/host/snapshot.js +218 -0
- package/lib/host/source-scan.js +225 -0
- package/lib/host/templates/cleanup.js +219 -0
- package/lib/host/templates/inheritance.js +144 -0
- package/lib/host/templates/materialize.js +317 -0
- package/lib/host/templates/message-overlay.js +184 -0
- package/lib/host/templates/repository.js +323 -0
- package/lib/host/templates/store.js +131 -0
- package/lib/host/tool-set.js +150 -0
- package/lib/host/tools.js +129 -0
- package/lib/index.js +103 -0
- package/package.json +111 -4
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 工作区选择控件:已创建的工作区下拉 + 「新建工作区…」。
|
|
3
|
+
*
|
|
4
|
+
* 工作区是首请求的条件。已创建的工作区直接选;「新建工作区…」打开系统文件夹选择器,
|
|
5
|
+
* 选中后通过 DSH 的 `workspaces.create({ path })` 幂等登记(与 DSH 自己的「添加工作区」
|
|
6
|
+
* 同一条路径),再把该路径作为条件。插件不把这项能力放进 `inject`:选择器缺席时下拉
|
|
7
|
+
* 仍然可用,只是新建会失败并写原因。
|
|
8
|
+
*
|
|
9
|
+
* 本文件是一个包内 chunk:入口用 `require.async('./client.workspace-picker.js')` 取它。
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
window.__ModuleLoader__.load({
|
|
13
|
+
id: '@cheemsup/dsh-plugin-console',
|
|
14
|
+
chunk: 'client.workspace-picker.js',
|
|
15
|
+
factory: (require) => {
|
|
16
|
+
const React = require('react')
|
|
17
|
+
const { createElement: h, useCallback, useState } = React
|
|
18
|
+
|
|
19
|
+
return function create() {
|
|
20
|
+
/** 「新建工作区…」只用于触发选择器,不是可停留的选项。 */
|
|
21
|
+
const NEW_WORKSPACE = '__pt_new_workspace__'
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* 读一个客户端服务。插件没有 inject 这些服务:缺席时只是少一个入口。
|
|
25
|
+
* @param {object | null} ctx - 浏览器插件上下文。
|
|
26
|
+
* @param {string} name - 服务名。
|
|
27
|
+
* @returns {unknown} 服务实例或 undefined。
|
|
28
|
+
*/
|
|
29
|
+
function serviceOf(ctx, name) {
|
|
30
|
+
try {
|
|
31
|
+
return typeof ctx?.get === 'function' ? ctx.get(name) : ctx?.[name]
|
|
32
|
+
} catch {
|
|
33
|
+
return undefined
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* 取 DSH 自己的目录选择能力。
|
|
39
|
+
*
|
|
40
|
+
* 优先用 `uiWorkspace.pickDirectory()`——它就是「添加工作区」走的同一条路径,
|
|
41
|
+
* 错误与取消语义已经处理好;服务缺席时再退到 `remote.directoryPicker.pick()`。
|
|
42
|
+
* @param {object | null} ctx - 浏览器插件上下文。
|
|
43
|
+
* @returns {object | null} `{ pick: () => Promise<string | null> }`。
|
|
44
|
+
*/
|
|
45
|
+
function directoryPickerOf(ctx) {
|
|
46
|
+
const uiWorkspace = serviceOf(ctx, 'uiWorkspace')
|
|
47
|
+
if (typeof uiWorkspace?.pickDirectory === 'function') {
|
|
48
|
+
return { pick: () => uiWorkspace.pickDirectory() }
|
|
49
|
+
}
|
|
50
|
+
const picker = serviceOf(ctx, 'remote')?.directoryPicker
|
|
51
|
+
if (typeof picker?.pick === 'function') {
|
|
52
|
+
return {
|
|
53
|
+
pick: async () => {
|
|
54
|
+
const result = await picker.pick()
|
|
55
|
+
if (result?.ok !== true) throw new Error(result?.error?.message ?? '目录选择失败')
|
|
56
|
+
return result.value
|
|
57
|
+
},
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return null
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* 「新建工作区」的完整动作:打开选择器 → 幂等登记 → 返回路径。
|
|
65
|
+
*
|
|
66
|
+
* 取消返回 null(不是错误);登记失败把原因留在 `error` 里。一次只允许一个
|
|
67
|
+
* 选择器在跑:原生对话框无法从浏览器关闭,重复点击只会叠出多个。
|
|
68
|
+
* @param {object | null} runtimeCtx - 浏览器插件上下文。
|
|
69
|
+
* @returns {object} `{ pick, busy, error }`。
|
|
70
|
+
*/
|
|
71
|
+
function useWorkspacePicker(runtimeCtx) {
|
|
72
|
+
const [busy, setBusy] = useState(false)
|
|
73
|
+
const [error, setError] = useState(null)
|
|
74
|
+
const pick = useCallback(async () => {
|
|
75
|
+
if (busy) return null
|
|
76
|
+
const picker = directoryPickerOf(runtimeCtx)
|
|
77
|
+
if (picker === null) {
|
|
78
|
+
setError('目录选择器不可用:无法新建工作区')
|
|
79
|
+
return null
|
|
80
|
+
}
|
|
81
|
+
setBusy(true)
|
|
82
|
+
setError(null)
|
|
83
|
+
try {
|
|
84
|
+
const picked = await picker.pick()
|
|
85
|
+
if (typeof picked !== 'string' || picked.length === 0) return null
|
|
86
|
+
// 幂等:目录已经是工作区时,Host 直接返回那一个。
|
|
87
|
+
const workspaces = serviceOf(runtimeCtx, 'workspaces')
|
|
88
|
+
if (typeof workspaces?.create === 'function') {
|
|
89
|
+
try {
|
|
90
|
+
await workspaces.create({ path: picked })
|
|
91
|
+
} catch (cause) {
|
|
92
|
+
throw new Error('新建工作区失败:' + (cause instanceof Error ? cause.message : String(cause)))
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return picked
|
|
96
|
+
} catch (cause) {
|
|
97
|
+
setError(cause instanceof Error ? cause.message : String(cause))
|
|
98
|
+
return null
|
|
99
|
+
} finally {
|
|
100
|
+
setBusy(false)
|
|
101
|
+
}
|
|
102
|
+
}, [runtimeCtx, busy])
|
|
103
|
+
return { pick, busy, error }
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* 比较两个路径是否指向同一位置。
|
|
108
|
+
*
|
|
109
|
+
* 宿主按平台口径比较;浏览器拿不到条件的比较键,所以在客户端也做一次,
|
|
110
|
+
* 用于把「刚选中的路径」映射回下拉里的已创建工作区。只归一化分隔符与末尾斜杠,
|
|
111
|
+
* Windows 盘符或 UNC 路径再折成小写——POSIX 路径保持大小写敏感。
|
|
112
|
+
* @param {string} left - 一个路径。
|
|
113
|
+
* @param {string} right - 另一个路径。
|
|
114
|
+
* @returns {boolean} 是否相同。
|
|
115
|
+
*/
|
|
116
|
+
function samePath(left, right) {
|
|
117
|
+
const normalize = (value) => String(value ?? '').replace(/[\\/]+/g, '/').replace(/\/+$/, '')
|
|
118
|
+
const a = normalize(left)
|
|
119
|
+
const b = normalize(right)
|
|
120
|
+
if (a.length === 0 || b.length === 0) return a === b
|
|
121
|
+
const windowsish = /^[a-zA-Z]:/.test(a) || a.startsWith('//')
|
|
122
|
+
return windowsish ? a.toLowerCase() === b.toLowerCase() : a === b
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* 工作区条件:一个下拉,选项是已创建工作区 + 「新建工作区…」。
|
|
127
|
+
*
|
|
128
|
+
* 当前路径不在下拉里时(刚选完、快照还没刷新,或路径来自旧状态)补一个当前项,
|
|
129
|
+
* 否则受控 select 会显示成别的项。选中「新建工作区…」立即回弹,不等异步结果。
|
|
130
|
+
* @param {string} label - 字段名。
|
|
131
|
+
* @param {string | null} value - 当前条件路径。
|
|
132
|
+
* @param {object[]} workspaces - 已创建工作区。
|
|
133
|
+
* @param {Function} onChange - 选了一个已创建工作区。
|
|
134
|
+
* @param {Function} onNew - 选了「新建工作区…」。
|
|
135
|
+
* @param {object} [opts] - `{ title, busy, error, newLabel, ariaLabel }`。
|
|
136
|
+
* @returns {object} React 节点。
|
|
137
|
+
*/
|
|
138
|
+
function workspaceField(label, value, workspaces, onChange, onNew, opts) {
|
|
139
|
+
const current = typeof value === 'string' ? value : ''
|
|
140
|
+
const entries = (workspaces ?? [])
|
|
141
|
+
.filter((workspace) => typeof workspace?.path === 'string' && workspace.path.length > 0)
|
|
142
|
+
.map((workspace) => ({
|
|
143
|
+
value: workspace.path,
|
|
144
|
+
// 没有独立标题时只写路径,不重复成「路径 · 路径」。
|
|
145
|
+
label: typeof workspace.title === 'string' && workspace.title.length > 0 && workspace.title !== workspace.path
|
|
146
|
+
? workspace.title + ' · ' + workspace.path
|
|
147
|
+
: workspace.path,
|
|
148
|
+
}))
|
|
149
|
+
const matched = entries.find((entry) => samePath(entry.value, current))
|
|
150
|
+
if (current.length > 0 && matched === undefined) {
|
|
151
|
+
entries.unshift({ value: current, label: '当前选择 · ' + current })
|
|
152
|
+
}
|
|
153
|
+
if (current.length === 0) {
|
|
154
|
+
entries.unshift({ value: '', label: '未选择工作区', disabled: true })
|
|
155
|
+
}
|
|
156
|
+
const selected = matched?.value ?? current
|
|
157
|
+
const canCreate = typeof onNew === 'function'
|
|
158
|
+
return h(
|
|
159
|
+
'label',
|
|
160
|
+
{ className: 'ptField', title: opts?.title },
|
|
161
|
+
h('span', { className: 'ptFieldLabel' }, label),
|
|
162
|
+
h(
|
|
163
|
+
'select',
|
|
164
|
+
{
|
|
165
|
+
className: 'ptSelect',
|
|
166
|
+
value: selected,
|
|
167
|
+
disabled: opts?.busy === true,
|
|
168
|
+
'aria-busy': opts?.busy === true ? 'true' : undefined,
|
|
169
|
+
'aria-label': opts?.ariaLabel ?? label,
|
|
170
|
+
onChange: (event) => {
|
|
171
|
+
const next = event.target.value
|
|
172
|
+
if (canCreate && next === NEW_WORKSPACE) {
|
|
173
|
+
// 「新建工作区…」不是可停留的选项:立刻回到当前项,结果由 onNew 决定。
|
|
174
|
+
event.target.value = selected
|
|
175
|
+
void onNew()
|
|
176
|
+
return
|
|
177
|
+
}
|
|
178
|
+
if (next === selected) return
|
|
179
|
+
onChange(next)
|
|
180
|
+
},
|
|
181
|
+
},
|
|
182
|
+
entries.map((entry) => h('option', {
|
|
183
|
+
key: entry.value,
|
|
184
|
+
value: entry.value,
|
|
185
|
+
disabled: entry.disabled === true,
|
|
186
|
+
}, entry.label)),
|
|
187
|
+
canCreate
|
|
188
|
+
? h('option', { key: NEW_WORKSPACE, value: NEW_WORKSPACE }, opts?.newLabel ?? '新建工作区…')
|
|
189
|
+
: null,
|
|
190
|
+
),
|
|
191
|
+
opts?.error
|
|
192
|
+
? h('span', {
|
|
193
|
+
className: 'ptError',
|
|
194
|
+
style: { fontSize: '11px', maxWidth: '240px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
|
|
195
|
+
title: opts.error,
|
|
196
|
+
}, opts.error)
|
|
197
|
+
: null,
|
|
198
|
+
)
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
return { workspaceField, samePath, useWorkspacePicker }
|
|
202
|
+
}
|
|
203
|
+
},
|
|
204
|
+
})
|
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 插件活动:从 session log 的 `tool/call` / `tool/result` 归约出工具级用量。
|
|
3
|
+
*
|
|
4
|
+
* 这里只做「工具名 → 调用数/错误数/耗时/最后使用/会话」的纯聚合,不判断
|
|
5
|
+
* 插件归属;归属由客户端用快照里的 `tools.attributed` 做连接,避免 host 为了
|
|
6
|
+
* 一份活动重新跑整份快照。
|
|
7
|
+
*
|
|
8
|
+
* 读取范围有意限制在最近 N 天、最多 M 个会话:活动是诊断视图,不是全量审计。
|
|
9
|
+
* 单个会话的结果按「最后事件序号」缓存,日志没变就不重复归约。
|
|
10
|
+
* @module dsh-plugin-console/host/activity
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { readSessionEvents } from './session-events.js'
|
|
14
|
+
|
|
15
|
+
/** 默认时间窗与扫描上限。 */
|
|
16
|
+
const DEFAULT_DAYS = 7
|
|
17
|
+
const DEFAULT_LIMIT = 20
|
|
18
|
+
const MAX_LIMIT = 50
|
|
19
|
+
|
|
20
|
+
/** 单个工具最多保留多少个耗时样本;p95 不需要全量。 */
|
|
21
|
+
const MAX_DURATIONS = 2000
|
|
22
|
+
|
|
23
|
+
/** 会话活动缓存上限。 */
|
|
24
|
+
const MAX_CACHE = 256
|
|
25
|
+
const CACHE = new Map()
|
|
26
|
+
|
|
27
|
+
/** 把任意输入收成范围内的整数。 */
|
|
28
|
+
function clampInt(value, min, max, fallback) {
|
|
29
|
+
const number = typeof value === 'number' ? value : Number(value)
|
|
30
|
+
if (!Number.isFinite(number)) return fallback
|
|
31
|
+
return Math.min(max, Math.max(min, Math.trunc(number)))
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** 最近秩百分位;空数组返回 null。 */
|
|
35
|
+
function percentile(values, fraction) {
|
|
36
|
+
if (!Array.isArray(values) || values.length === 0) return null
|
|
37
|
+
const sorted = [...values].sort((left, right) => left - right)
|
|
38
|
+
const index = Math.min(sorted.length - 1, Math.max(0, Math.ceil(fraction * sorted.length) - 1))
|
|
39
|
+
return sorted[index]
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** 事件序列的轻量指纹:活会话用 seq,冷会话用长度 + 末事件序号/时间。 */
|
|
43
|
+
function stampOf(events, captured) {
|
|
44
|
+
const last = events[events.length - 1]
|
|
45
|
+
if (captured.source === 'live' && typeof captured.agent?.session?.seq === 'number') {
|
|
46
|
+
return 'live:' + captured.agent.session.seq
|
|
47
|
+
}
|
|
48
|
+
return 'log:' + events.length + ':' + (last?.seq ?? '') + ':' + (last?.time ?? '')
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* 纯归约:把一段会话事件变成「工具名 → 计数 + 耗时样本」。
|
|
53
|
+
*
|
|
54
|
+
* 只处理已经配对的 `tool/result`;没有结果的调用计入 calls,但不计耗时。
|
|
55
|
+
* 同一个 callId 的重复结果只算一次。
|
|
56
|
+
* @param {Array<object>} events - 会话事件。
|
|
57
|
+
* @returns {Map<string, {calls: number, results: number, errors: number, durations: number[], lastUsed: number}>} 工具级结果。
|
|
58
|
+
*/
|
|
59
|
+
export function summarizeToolEvents(events) {
|
|
60
|
+
const pending = new Map()
|
|
61
|
+
const tools = new Map()
|
|
62
|
+
|
|
63
|
+
for (const event of Array.isArray(events) ? events : []) {
|
|
64
|
+
if (event?.type === 'tool/call') {
|
|
65
|
+
const data = event.data ?? {}
|
|
66
|
+
const name = typeof data.name === 'string' ? data.name : undefined
|
|
67
|
+
if (name === undefined) continue
|
|
68
|
+
const time = typeof event.time === 'number' ? event.time : undefined
|
|
69
|
+
const row = tools.get(name) ?? { calls: 0, results: 0, errors: 0, durations: [], lastUsed: 0 }
|
|
70
|
+
row.calls++
|
|
71
|
+
if (time !== undefined) row.lastUsed = Math.max(row.lastUsed, time)
|
|
72
|
+
tools.set(name, row)
|
|
73
|
+
if (typeof data.callId === 'string') pending.set(data.callId, { name, time })
|
|
74
|
+
continue
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
if (event?.type === 'tool/result') {
|
|
78
|
+
const data = event.data ?? {}
|
|
79
|
+
const callId = typeof data.toolCallId === 'string'
|
|
80
|
+
? data.toolCallId
|
|
81
|
+
: (typeof data.message?.toolCallId === 'string' ? data.message.toolCallId : undefined)
|
|
82
|
+
const call = callId === undefined ? undefined : pending.get(callId)
|
|
83
|
+
if (call === undefined) continue
|
|
84
|
+
pending.delete(callId)
|
|
85
|
+
const row = tools.get(call.name)
|
|
86
|
+
if (row === undefined) continue
|
|
87
|
+
row.results++
|
|
88
|
+
if (data.message?.isError === true || data.isError === true) row.errors++
|
|
89
|
+
const time = typeof event.time === 'number' ? event.time : undefined
|
|
90
|
+
if (time !== undefined) {
|
|
91
|
+
row.lastUsed = Math.max(row.lastUsed, time)
|
|
92
|
+
if (call.time !== undefined && row.durations.length < MAX_DURATIONS) {
|
|
93
|
+
row.durations.push(Math.max(0, time - call.time))
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
return tools
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** 把单个会话的结果并进总表。 */
|
|
103
|
+
function mergeRows(target, source, sessionId) {
|
|
104
|
+
for (const [name, row] of source) {
|
|
105
|
+
const merged = target.get(name) ?? {
|
|
106
|
+
calls: 0,
|
|
107
|
+
results: 0,
|
|
108
|
+
errors: 0,
|
|
109
|
+
durations: [],
|
|
110
|
+
lastUsed: 0,
|
|
111
|
+
sessions: new Set(),
|
|
112
|
+
}
|
|
113
|
+
merged.calls += row.calls
|
|
114
|
+
merged.results += row.results
|
|
115
|
+
merged.errors += row.errors
|
|
116
|
+
merged.lastUsed = Math.max(merged.lastUsed, row.lastUsed ?? 0)
|
|
117
|
+
merged.sessions.add(sessionId)
|
|
118
|
+
const room = MAX_DURATIONS - merged.durations.length
|
|
119
|
+
if (room > 0) merged.durations.push(...row.durations.slice(0, room))
|
|
120
|
+
target.set(name, merged)
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* 读取最近一段时间的工具活动。
|
|
126
|
+
* @param {object} ctx - host 插件上下文。
|
|
127
|
+
* @param {{days?: number | string, limit?: number | string}} [options] - 时间窗与会话上限。
|
|
128
|
+
* @returns {Promise<object>} 可直接序列化的活动摘要。
|
|
129
|
+
*/
|
|
130
|
+
export async function readActivity(ctx, options = {}) {
|
|
131
|
+
const days = clampInt(options.days, 1, 90, DEFAULT_DAYS)
|
|
132
|
+
const limit = clampInt(options.limit, 1, MAX_LIMIT, DEFAULT_LIMIT)
|
|
133
|
+
const cutoff = Date.now() - days * 24 * 60 * 60 * 1000
|
|
134
|
+
|
|
135
|
+
/** @type {Map<string, {id: string, createdAt: number, sizeBytes?: number, live: boolean}>} */
|
|
136
|
+
const records = new Map()
|
|
137
|
+
const persistence = ctx.get('sessionPersistence')
|
|
138
|
+
if (persistence !== undefined && typeof persistence.list === 'function') {
|
|
139
|
+
try {
|
|
140
|
+
for (const snapshot of await persistence.list()) {
|
|
141
|
+
const header = snapshot?.header
|
|
142
|
+
if (typeof header?.id !== 'string') continue
|
|
143
|
+
const createdAt = typeof header.createdAt === 'number' ? header.createdAt : undefined
|
|
144
|
+
records.set(header.id, {
|
|
145
|
+
id: header.id,
|
|
146
|
+
createdAt: createdAt ?? 0,
|
|
147
|
+
sizeBytes: typeof snapshot.sizeBytes === 'number' ? snapshot.sizeBytes : undefined,
|
|
148
|
+
live: false,
|
|
149
|
+
})
|
|
150
|
+
}
|
|
151
|
+
} catch {
|
|
152
|
+
// 读不到持久化时仍尝试活会话
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const sessions = ctx.get('sessions')
|
|
157
|
+
if (sessions !== undefined && typeof sessions.list === 'function') {
|
|
158
|
+
try {
|
|
159
|
+
for (const session of sessions.list()) {
|
|
160
|
+
if (typeof session?.id !== 'string') continue
|
|
161
|
+
const existing = records.get(session.id)
|
|
162
|
+
records.set(session.id, {
|
|
163
|
+
id: session.id,
|
|
164
|
+
createdAt: existing?.createdAt ?? Date.now(),
|
|
165
|
+
sizeBytes: existing?.sizeBytes,
|
|
166
|
+
live: true,
|
|
167
|
+
})
|
|
168
|
+
}
|
|
169
|
+
} catch {
|
|
170
|
+
// 活会话读失败不影响冷会话
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
if (records.size === 0) {
|
|
175
|
+
return {
|
|
176
|
+
available: false,
|
|
177
|
+
reason: '这个部署没有可读的会话持久化或活会话,无法归约工具活动',
|
|
178
|
+
windowDays: days,
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const ordered = [...records.values()]
|
|
183
|
+
.filter((record) => record.live || record.createdAt >= cutoff)
|
|
184
|
+
// 活会话没有 createdAt 时按「现在」参与排序,避免被 limit 排掉
|
|
185
|
+
.map((record) => ({ ...record, createdAt: record.createdAt || Date.now() }))
|
|
186
|
+
.sort((left, right) => right.createdAt - left.createdAt)
|
|
187
|
+
const selected = ordered.slice(0, limit)
|
|
188
|
+
|
|
189
|
+
const merged = new Map()
|
|
190
|
+
let scanned = 0
|
|
191
|
+
let skipped = 0
|
|
192
|
+
for (const record of selected) {
|
|
193
|
+
let captured
|
|
194
|
+
try {
|
|
195
|
+
captured = await readSessionEvents(ctx, record.id)
|
|
196
|
+
} catch {
|
|
197
|
+
skipped++
|
|
198
|
+
continue
|
|
199
|
+
}
|
|
200
|
+
if (captured === undefined) {
|
|
201
|
+
skipped++
|
|
202
|
+
continue
|
|
203
|
+
}
|
|
204
|
+
scanned++
|
|
205
|
+
const stamp = stampOf(captured.events, captured)
|
|
206
|
+
const cacheKey = record.id + '|' + stamp
|
|
207
|
+
let rows = CACHE.get(cacheKey)
|
|
208
|
+
if (rows === undefined) {
|
|
209
|
+
rows = summarizeToolEvents(captured.events)
|
|
210
|
+
CACHE.set(cacheKey, rows)
|
|
211
|
+
if (CACHE.size > MAX_CACHE) CACHE.delete(CACHE.keys().next().value)
|
|
212
|
+
}
|
|
213
|
+
mergeRows(merged, rows, record.id)
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
const tools = {}
|
|
217
|
+
let totalCalls = 0
|
|
218
|
+
let totalResults = 0
|
|
219
|
+
let totalErrors = 0
|
|
220
|
+
for (const [name, row] of merged) {
|
|
221
|
+
tools[name] = {
|
|
222
|
+
calls: row.calls,
|
|
223
|
+
results: row.results,
|
|
224
|
+
errors: row.errors,
|
|
225
|
+
errorRate: row.results > 0 ? row.errors / row.results : 0,
|
|
226
|
+
p50Ms: percentile(row.durations, 0.5),
|
|
227
|
+
p95Ms: percentile(row.durations, 0.95),
|
|
228
|
+
lastUsed: row.lastUsed > 0 ? row.lastUsed : undefined,
|
|
229
|
+
sessions: [...row.sessions],
|
|
230
|
+
}
|
|
231
|
+
totalCalls += row.calls
|
|
232
|
+
totalResults += row.results
|
|
233
|
+
totalErrors += row.errors
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
return {
|
|
237
|
+
available: true,
|
|
238
|
+
generatedAt: new Date().toISOString(),
|
|
239
|
+
windowDays: days,
|
|
240
|
+
limit,
|
|
241
|
+
sessionsScanned: scanned,
|
|
242
|
+
sessionsSkipped: skipped,
|
|
243
|
+
truncated: ordered.length > selected.length,
|
|
244
|
+
totals: {
|
|
245
|
+
calls: totalCalls,
|
|
246
|
+
results: totalResults,
|
|
247
|
+
errors: totalErrors,
|
|
248
|
+
tools: Object.keys(tools).length,
|
|
249
|
+
},
|
|
250
|
+
tools,
|
|
251
|
+
}
|
|
252
|
+
}
|