dsh-plugin-slim 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +95 -2
- package/client.js +524 -0
- package/cordis.patch.yml +6 -0
- package/icon.svg +8 -0
- package/lib/attribution.js +627 -0
- package/lib/checkup.js +338 -0
- package/lib/footprint.js +134 -0
- package/lib/host.js +846 -0
- package/lib/http.js +231 -0
- package/lib/index.js +153 -0
- package/lib/patch.js +797 -0
- package/lib/routes.js +493 -0
- package/lib/usage.js +116 -0
- package/package.json +73 -4
package/lib/checkup.js
ADDED
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure-ish report merger: entries + tools + usage + attribution -> one
|
|
3
|
+
* `Report` object shared verbatim by the four panel routes.
|
|
4
|
+
*
|
|
5
|
+
* Honesty rules enforced here (handoff spec §2.3 / §3.1):
|
|
6
|
+
* - footprint counts only always-loaded tools (`deferLoading !== true`); the
|
|
7
|
+
* summary totals deduplicate tools by name, per-plugin rows do not (a tool
|
|
8
|
+
* registered by two plugins is shown under both, the global account stays low);
|
|
9
|
+
* - usage unknown never becomes 0: when the usage summary is unknown every
|
|
10
|
+
* plugin/tool gets `used30d === null`, plugins are classified `heavy-unknown`
|
|
11
|
+
* (never `idle-heavy`) and every idle-heavy/reducible aggregate is 0;
|
|
12
|
+
* - the six plugin statuses and their sort order are exactly the contract:
|
|
13
|
+
* idle-heavy -> heavy-unknown -> active-heavy -> sleeping -> zero-burden ->
|
|
14
|
+
* protected (three first groups by alwaysLoadedChars desc, then name asc).
|
|
15
|
+
*
|
|
16
|
+
* @module dsh-plugin-slim/checkup
|
|
17
|
+
*/
|
|
18
|
+
import { attributeTools } from './attribution.js'
|
|
19
|
+
import { estimateToolFootprint, sumFootprints } from './footprint.js'
|
|
20
|
+
import { protectReasonFor } from './host.js'
|
|
21
|
+
|
|
22
|
+
/** Contract order for the six plugin statuses. */
|
|
23
|
+
const STATUS_ORDER = Object.freeze(['idle-heavy', 'heavy-unknown', 'active-heavy', 'sleeping', 'zero-burden', 'protected'])
|
|
24
|
+
|
|
25
|
+
/** Statuses ordered by burden first, then alphabetically by name. */
|
|
26
|
+
const BURDEN_STATUSES = new Set(['idle-heavy', 'heavy-unknown', 'active-heavy'])
|
|
27
|
+
|
|
28
|
+
/** Warning bounds for one report. */
|
|
29
|
+
const MAX_WARNINGS = 20
|
|
30
|
+
const MAX_WARNING_CHARS = 500
|
|
31
|
+
|
|
32
|
+
/** @param {unknown} value @returns {value is Record<string, unknown>} */
|
|
33
|
+
function isRecord(value) {
|
|
34
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** @param {unknown} value @returns {string} */
|
|
38
|
+
function textOf(value) {
|
|
39
|
+
return typeof value === 'string' ? value.trim() : ''
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** @param {unknown} value @returns {Date} */
|
|
43
|
+
function resolveNow(value) {
|
|
44
|
+
if (value instanceof Date && Number.isFinite(value.getTime())) return value
|
|
45
|
+
if (typeof value === 'number' && Number.isFinite(value)) return new Date(value)
|
|
46
|
+
if (typeof value === 'string' && value !== '') {
|
|
47
|
+
const time = Date.parse(value)
|
|
48
|
+
if (!Number.isNaN(time)) return new Date(time)
|
|
49
|
+
}
|
|
50
|
+
return new Date()
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Trim, bound and de-duplicate warnings keeping first-seen order. */
|
|
54
|
+
function finalizeWarnings(messages) {
|
|
55
|
+
const seen = new Set()
|
|
56
|
+
const out = []
|
|
57
|
+
for (const message of messages) {
|
|
58
|
+
if (typeof message !== 'string' || message === '') continue
|
|
59
|
+
const bounded = message.length <= MAX_WARNING_CHARS ? message : message.slice(0, MAX_WARNING_CHARS - 1) + '…'
|
|
60
|
+
if (seen.has(bounded)) continue
|
|
61
|
+
seen.add(bounded)
|
|
62
|
+
out.push(bounded)
|
|
63
|
+
if (out.length >= MAX_WARNINGS) break
|
|
64
|
+
}
|
|
65
|
+
return out
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Normalize the host entry rows into the report's plugin skeleton rows. */
|
|
69
|
+
function normalizeEntries(entries) {
|
|
70
|
+
const out = []
|
|
71
|
+
const seen = new Set()
|
|
72
|
+
for (const row of Array.isArray(entries) ? entries : []) {
|
|
73
|
+
if (!isRecord(row)) continue
|
|
74
|
+
const entryId = textOf(row.entryId) || textOf(row.id) || textOf(row.name)
|
|
75
|
+
if (entryId === '' || seen.has(entryId)) continue
|
|
76
|
+
seen.add(entryId)
|
|
77
|
+
out.push({
|
|
78
|
+
entryId,
|
|
79
|
+
name: textOf(row.name) || entryId,
|
|
80
|
+
version: typeof row.version === 'string' && row.version !== '' ? row.version : null,
|
|
81
|
+
description: typeof row.description === 'string' ? row.description : '',
|
|
82
|
+
enabled: row.enabled !== false && row.disabled !== true,
|
|
83
|
+
expressionManaged: row.expressionManaged === true,
|
|
84
|
+
source: typeof row.source === 'string' && row.source !== '' ? row.source : 'unknown',
|
|
85
|
+
unresolvedName: row.unresolvedName === true,
|
|
86
|
+
declaredProtected: row.protected === true,
|
|
87
|
+
declaredProtectReason: typeof row.protectReason === 'string' ? row.protectReason : null,
|
|
88
|
+
})
|
|
89
|
+
}
|
|
90
|
+
return out
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Normalize tool rows, keeping model-facing fields intact for footprint sizing. */
|
|
94
|
+
function normalizeTools(tools) {
|
|
95
|
+
const out = []
|
|
96
|
+
const seen = new Set()
|
|
97
|
+
for (const row of Array.isArray(tools) ? tools : []) {
|
|
98
|
+
if (!isRecord(row)) continue
|
|
99
|
+
const name = textOf(row.name)
|
|
100
|
+
if (name === '' || seen.has(name)) continue
|
|
101
|
+
seen.add(name)
|
|
102
|
+
const tool = { name, description: typeof row.description === 'string' ? row.description : '' }
|
|
103
|
+
if (row.parameters !== undefined && row.parameters !== null) tool.parameters = row.parameters
|
|
104
|
+
if (row.deferLoading === true) tool.deferLoading = true
|
|
105
|
+
if (typeof row.owner === 'string' && row.owner !== '') tool.owner = row.owner
|
|
106
|
+
out.push(tool)
|
|
107
|
+
}
|
|
108
|
+
return out
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Normalize the usage summary ({ byTool: Map | object, unknown }) defensively. */
|
|
112
|
+
function normalizeUsage(usage) {
|
|
113
|
+
if (!isRecord(usage)) return { byTool: new Map(), unknown: true }
|
|
114
|
+
const byTool = usage.byTool instanceof Map ? usage.byTool : isRecord(usage.byTool) ? usage.byTool : new Map()
|
|
115
|
+
return { byTool, unknown: usage.unknown === true }
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Per-tool usage facts. Unknown usage is null - never 0 (honesty red line).
|
|
120
|
+
* @returns {{ count: number | null, lastUsedAt: string | null }}
|
|
121
|
+
*/
|
|
122
|
+
function usageFor(usage, name) {
|
|
123
|
+
if (usage.unknown === true) return { count: null, lastUsedAt: null }
|
|
124
|
+
const entry = usage.byTool instanceof Map ? usage.byTool.get(name) : isRecord(usage.byTool) ? usage.byTool[name] : undefined
|
|
125
|
+
if (!isRecord(entry)) return { count: 0, lastUsedAt: null }
|
|
126
|
+
const count = typeof entry.count === 'number' && Number.isFinite(entry.count) && entry.count >= 0 ? entry.count : 0
|
|
127
|
+
const lastUsedAt = typeof entry.lastUsedAt === 'string' && entry.lastUsedAt !== '' ? entry.lastUsedAt : null
|
|
128
|
+
return { count, lastUsedAt }
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Latest ISO timestamp of two candidates (null-safe). */
|
|
132
|
+
function latestTimestamp(left, right) {
|
|
133
|
+
if (left === null) return right
|
|
134
|
+
if (right === null) return left
|
|
135
|
+
return left >= right ? left : right
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** Classify one plugin into the contract's six statuses. */
|
|
139
|
+
function classifyStatus(plugin) {
|
|
140
|
+
if (plugin.protected === true) return 'protected'
|
|
141
|
+
if (plugin.enabled !== true) return 'sleeping'
|
|
142
|
+
if (plugin.alwaysLoadedTools === 0) return 'zero-burden'
|
|
143
|
+
if (plugin.used30d === 0) return 'idle-heavy'
|
|
144
|
+
if (plugin.used30d === null) return 'heavy-unknown'
|
|
145
|
+
return 'active-heavy'
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Contract ordering: burden groups by chars desc, everything else by name. */
|
|
149
|
+
function sortPlugins(plugins) {
|
|
150
|
+
return plugins.sort((left, right) => {
|
|
151
|
+
const leftGroup = STATUS_ORDER.indexOf(left.status)
|
|
152
|
+
const rightGroup = STATUS_ORDER.indexOf(right.status)
|
|
153
|
+
if (leftGroup !== rightGroup) return leftGroup - rightGroup
|
|
154
|
+
if (BURDEN_STATUSES.has(left.status) && left.alwaysLoadedChars !== right.alwaysLoadedChars) {
|
|
155
|
+
return right.alwaysLoadedChars - left.alwaysLoadedChars
|
|
156
|
+
}
|
|
157
|
+
if (left.name < right.name) return -1
|
|
158
|
+
if (left.name > right.name) return 1
|
|
159
|
+
return 0
|
|
160
|
+
})
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Public report shape of the newest unrestored snapshot (null when none). */
|
|
164
|
+
function normalizeLatestSnapshot(snapshot) {
|
|
165
|
+
if (!isRecord(snapshot) || typeof snapshot.id !== 'string' || snapshot.id === '') return null
|
|
166
|
+
const changes = Array.isArray(snapshot.changes) ? snapshot.changes : []
|
|
167
|
+
return {
|
|
168
|
+
id: snapshot.id,
|
|
169
|
+
createdAt: typeof snapshot.createdAt === 'string' ? snapshot.createdAt : '',
|
|
170
|
+
count: changes.length,
|
|
171
|
+
summary: typeof snapshot.summary === 'string' ? snapshot.summary : '',
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** Build one per-plugin tool row (footprint + honest usage). */
|
|
176
|
+
function buildToolRow(tool, usage) {
|
|
177
|
+
const footprint = estimateToolFootprint(tool)
|
|
178
|
+
const usageRow = usageFor(usage, tool.name)
|
|
179
|
+
return {
|
|
180
|
+
name: tool.name,
|
|
181
|
+
description: typeof tool.description === 'string' ? tool.description : '',
|
|
182
|
+
chars: footprint.chars,
|
|
183
|
+
estimatedTokens: footprint.estimatedTokens,
|
|
184
|
+
deferred: footprint.deferred === true,
|
|
185
|
+
schemaMeasured: footprint.schemaMeasured === true,
|
|
186
|
+
used30d: usageRow.count,
|
|
187
|
+
lastUsedAt: usageRow.lastUsedAt,
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Build the full checkup Report shared by GET /report and every POST response.
|
|
193
|
+
*
|
|
194
|
+
* @param {{
|
|
195
|
+
* entries?: unknown,
|
|
196
|
+
* tools?: unknown,
|
|
197
|
+
* usage?: { byTool?: Map<string, object> | object, unknown?: boolean },
|
|
198
|
+
* patchPath?: string | null,
|
|
199
|
+
* patchWritable?: boolean,
|
|
200
|
+
* latestSnapshot?: unknown,
|
|
201
|
+
* warnings?: string[],
|
|
202
|
+
* now?: Date | number | string,
|
|
203
|
+
* profilePath?: string,
|
|
204
|
+
* attribution?: { byPlugin?: Map<string, object[]>, byTool?: Map<string, string[]>, warnings?: string[] },
|
|
205
|
+
* }} [input]
|
|
206
|
+
* @returns {Promise<object>}
|
|
207
|
+
*/
|
|
208
|
+
export async function buildCheckupReport(input = {}) {
|
|
209
|
+
const options = isRecord(input) ? input : {}
|
|
210
|
+
const nowDate = resolveNow(options.now)
|
|
211
|
+
const entries = normalizeEntries(options.entries)
|
|
212
|
+
const tools = normalizeTools(options.tools)
|
|
213
|
+
const usage = normalizeUsage(options.usage)
|
|
214
|
+
const inputWarnings = Array.isArray(options.warnings) ? options.warnings : []
|
|
215
|
+
|
|
216
|
+
let attribution
|
|
217
|
+
if (isRecord(options.attribution) && options.attribution.byPlugin instanceof Map) {
|
|
218
|
+
attribution = options.attribution
|
|
219
|
+
} else {
|
|
220
|
+
attribution = await attributeTools({ tools, plugins: entries, profilePath: options.profilePath })
|
|
221
|
+
}
|
|
222
|
+
const byPlugin = attribution.byPlugin instanceof Map ? attribution.byPlugin : new Map()
|
|
223
|
+
const byTool = attribution.byTool instanceof Map ? attribution.byTool : new Map()
|
|
224
|
+
|
|
225
|
+
// Global unique tool table: the honest denominator of the total account.
|
|
226
|
+
const globalTools = []
|
|
227
|
+
const globalSeen = new Set()
|
|
228
|
+
for (const tool of tools) {
|
|
229
|
+
if (globalSeen.has(tool.name)) continue
|
|
230
|
+
globalSeen.add(tool.name)
|
|
231
|
+
globalTools.push(buildToolRow(tool, usage))
|
|
232
|
+
}
|
|
233
|
+
const totals = sumFootprints(globalTools)
|
|
234
|
+
|
|
235
|
+
const plugins = entries.map((entry) => {
|
|
236
|
+
const attributed = byPlugin.get(entry.entryId) ?? []
|
|
237
|
+
const rows = []
|
|
238
|
+
const seenTools = new Set()
|
|
239
|
+
for (const row of Array.isArray(attributed) ? attributed : []) {
|
|
240
|
+
if (!isRecord(row) || typeof row.name !== 'string' || row.name === '') continue
|
|
241
|
+
if (seenTools.has(row.name)) continue
|
|
242
|
+
seenTools.add(row.name)
|
|
243
|
+
rows.push(buildToolRow(row, usage))
|
|
244
|
+
}
|
|
245
|
+
const alwaysLoaded = rows.filter((row) => row.deferred !== true)
|
|
246
|
+
let used30d = null
|
|
247
|
+
let lastUsedAt = null
|
|
248
|
+
if (rows.length > 0 && usage.unknown !== true) {
|
|
249
|
+
used30d = 0
|
|
250
|
+
for (const row of rows) {
|
|
251
|
+
if (typeof row.used30d === 'number') used30d += row.used30d
|
|
252
|
+
lastUsedAt = latestTimestamp(lastUsedAt, row.lastUsedAt)
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
const ownReason = protectReasonFor(entry)
|
|
256
|
+
const protectedRow = entry.declaredProtected === true || ownReason !== null
|
|
257
|
+
const plugin = {
|
|
258
|
+
entryId: entry.entryId,
|
|
259
|
+
name: entry.name,
|
|
260
|
+
version: entry.version,
|
|
261
|
+
description: entry.description,
|
|
262
|
+
enabled: entry.enabled,
|
|
263
|
+
protected: protectedRow,
|
|
264
|
+
protectReason: ownReason ?? entry.declaredProtectReason,
|
|
265
|
+
canToggle: protectedRow !== true && entry.expressionManaged !== true,
|
|
266
|
+
expressionManaged: entry.expressionManaged,
|
|
267
|
+
source: entry.source,
|
|
268
|
+
status: 'protected',
|
|
269
|
+
alwaysLoadedTools: alwaysLoaded.length,
|
|
270
|
+
deferredTools: rows.length - alwaysLoaded.length,
|
|
271
|
+
alwaysLoadedChars: alwaysLoaded.reduce((sum, row) => sum + row.chars, 0),
|
|
272
|
+
alwaysLoadedTokens: alwaysLoaded.reduce((sum, row) => sum + row.estimatedTokens, 0),
|
|
273
|
+
used30d,
|
|
274
|
+
lastUsedAt,
|
|
275
|
+
tools: rows,
|
|
276
|
+
}
|
|
277
|
+
plugin.status = classifyStatus(plugin)
|
|
278
|
+
return plugin
|
|
279
|
+
})
|
|
280
|
+
sortPlugins(plugins)
|
|
281
|
+
|
|
282
|
+
const idleHeavy = plugins.filter((plugin) => plugin.status === 'idle-heavy')
|
|
283
|
+
// Deduplicate by tool name: one tool attributed to two idle-heavy plugins must
|
|
284
|
+
// not be counted twice, otherwise reduciblePercent could exceed 100% while the
|
|
285
|
+
// always-loaded denominator is already globally deduplicated.
|
|
286
|
+
const idleToolNames = new Set()
|
|
287
|
+
for (const plugin of idleHeavy) {
|
|
288
|
+
for (const tool of plugin.tools) {
|
|
289
|
+
if (tool.deferred !== true) idleToolNames.add(tool.name)
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
const idleHeavyRows = globalTools.filter((tool) => tool.deferred !== true && idleToolNames.has(tool.name))
|
|
293
|
+
const idleHeavyTools = idleHeavyRows.length
|
|
294
|
+
const idleHeavyChars = idleHeavyRows.reduce((sum, tool) => sum + tool.chars, 0)
|
|
295
|
+
const idleHeavyTokens = idleHeavyRows.reduce((sum, tool) => sum + tool.estimatedTokens, 0)
|
|
296
|
+
const reduciblePercent = totals.alwaysLoadedChars > 0 ? Math.round((idleHeavyChars / totals.alwaysLoadedChars) * 100) : 0
|
|
297
|
+
|
|
298
|
+
const unattributedTools = globalTools.filter((tool) => !byTool.has(tool.name))
|
|
299
|
+
unattributedTools.sort((left, right) => {
|
|
300
|
+
if (left.chars !== right.chars) return right.chars - left.chars
|
|
301
|
+
if (left.name < right.name) return -1
|
|
302
|
+
if (left.name > right.name) return 1
|
|
303
|
+
return 0
|
|
304
|
+
})
|
|
305
|
+
|
|
306
|
+
const reportWarnings = [...inputWarnings]
|
|
307
|
+
if (Array.isArray(attribution.warnings)) reportWarnings.push(...attribution.warnings)
|
|
308
|
+
if (usage.unknown === true) {
|
|
309
|
+
reportWarnings.push('无法读取历史会话调用记录:用量按未知处理,不会把插件误判为吃灰')
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
return {
|
|
313
|
+
generatedAt: nowDate.toISOString(),
|
|
314
|
+
summary: {
|
|
315
|
+
totalPlugins: plugins.length,
|
|
316
|
+
manageablePlugins: plugins.filter((plugin) => plugin.protected !== true).length,
|
|
317
|
+
sleepingPlugins: plugins.filter((plugin) => plugin.status === 'sleeping').length,
|
|
318
|
+
protectedPlugins: plugins.filter((plugin) => plugin.protected === true).length,
|
|
319
|
+
alwaysLoadedTools: totals.alwaysLoadedTools,
|
|
320
|
+
deferredTools: totals.deferredTools,
|
|
321
|
+
alwaysLoadedChars: totals.alwaysLoadedChars,
|
|
322
|
+
alwaysLoadedTokens: totals.alwaysLoadedTokens,
|
|
323
|
+
idleHeavyPlugins: idleHeavy.length,
|
|
324
|
+
idleHeavyTools,
|
|
325
|
+
idleHeavyChars,
|
|
326
|
+
idleHeavyTokens,
|
|
327
|
+
reduciblePercent,
|
|
328
|
+
usageKnown: usage.unknown !== true,
|
|
329
|
+
patchPath: typeof options.patchPath === 'string' && options.patchPath !== '' ? options.patchPath : null,
|
|
330
|
+
patchWritable: options.patchWritable === true,
|
|
331
|
+
},
|
|
332
|
+
plugins,
|
|
333
|
+
unattributedTools,
|
|
334
|
+
latestSnapshot: normalizeLatestSnapshot(options.latestSnapshot),
|
|
335
|
+
warnings: finalizeWarnings(reportWarnings),
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
package/lib/footprint.js
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tool context footprint estimation (pure, zero I/O).
|
|
3
|
+
*
|
|
4
|
+
* Estimates the prompt-context weight of registered tools from their model-facing
|
|
5
|
+
* fields (`name`, `description`, `parameters`) and distinguishes always-loaded
|
|
6
|
+
* tools from deferred tools (`deferLoading === true`).
|
|
7
|
+
*
|
|
8
|
+
* @module dsh-plugin-slim/footprint
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/** Matches CJK Unified Ideographs, CJK punctuation, fullwidth forms and Kana/Hangul. */
|
|
12
|
+
const CJK_OR_FULLWIDTH = /[\u3000-\u303F\u3040-\u30FF\u3400-\u4DBF\u4E00-\u9FFF\uF900-\uFAFF\uFF00-\uFFEF]/g
|
|
13
|
+
|
|
14
|
+
/** @param {unknown} value @returns {boolean} */
|
|
15
|
+
function isRecord(value) {
|
|
16
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Deterministic token estimate for mixed Chinese/English JSON/prose strings.
|
|
21
|
+
* Not tied to any specific tokenizer; clearly presented in UI as an estimate.
|
|
22
|
+
* @param {unknown} text
|
|
23
|
+
* @returns {number}
|
|
24
|
+
*/
|
|
25
|
+
export function estimateTokensFromText(text) {
|
|
26
|
+
if (typeof text !== 'string' || text === '') return 0
|
|
27
|
+
const cjkMatches = text.match(CJK_OR_FULLWIDTH)
|
|
28
|
+
const cjkCount = cjkMatches === null ? 0 : cjkMatches.length
|
|
29
|
+
const otherCount = Math.max(0, text.length - cjkCount)
|
|
30
|
+
return Math.ceil(cjkCount * 0.7 + otherCount * 0.28)
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Safely serialize `{ name, description, parameters }` for character/token sizing.
|
|
35
|
+
* Circular references or BigInt values degrade to `{ name, description }` with
|
|
36
|
+
* `schemaMeasured: false` instead of throwing.
|
|
37
|
+
* @param {{ name?: unknown, description?: unknown, parameters?: unknown }} tool
|
|
38
|
+
* @returns {{ serialized: string, schemaMeasured: boolean }}
|
|
39
|
+
*/
|
|
40
|
+
function serializeToolFace(tool) {
|
|
41
|
+
const name = typeof tool?.name === 'string' ? tool.name : ''
|
|
42
|
+
const description = typeof tool?.description === 'string' ? tool.description : ''
|
|
43
|
+
const parameters = tool?.parameters
|
|
44
|
+
const hasParameters = parameters !== undefined && parameters !== null
|
|
45
|
+
|
|
46
|
+
if (hasParameters) {
|
|
47
|
+
try {
|
|
48
|
+
const serialized = JSON.stringify({ name, description, parameters })
|
|
49
|
+
return { serialized, schemaMeasured: true }
|
|
50
|
+
} catch {
|
|
51
|
+
// Fall back to name + description when parameters contain circular refs or BigInt.
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
return {
|
|
56
|
+
serialized: JSON.stringify({ name, description }),
|
|
57
|
+
schemaMeasured: !hasParameters,
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Estimate the per-turn definition footprint of a single tool.
|
|
63
|
+
* @param {unknown} tool
|
|
64
|
+
* @returns {{ chars: number, estimatedTokens: number, deferred: boolean, schemaMeasured: boolean }}
|
|
65
|
+
*/
|
|
66
|
+
export function estimateToolFootprint(tool) {
|
|
67
|
+
if (!isRecord(tool)) {
|
|
68
|
+
return { chars: 0, estimatedTokens: 0, deferred: false, schemaMeasured: false }
|
|
69
|
+
}
|
|
70
|
+
const { serialized, schemaMeasured } = serializeToolFace(tool)
|
|
71
|
+
return {
|
|
72
|
+
chars: serialized.length,
|
|
73
|
+
estimatedTokens: estimateTokensFromText(serialized),
|
|
74
|
+
deferred: tool.deferLoading === true,
|
|
75
|
+
schemaMeasured,
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Aggregate tool footprints, keeping always-loaded and deferred tools separate.
|
|
81
|
+
* Only `deferred === false` tools consume prompt context on every turn.
|
|
82
|
+
* @param {Array<{ chars?: number, estimatedTokens?: number, deferred?: boolean }>} footprints
|
|
83
|
+
* @returns {{
|
|
84
|
+
* alwaysLoadedTools: number,
|
|
85
|
+
* deferredTools: number,
|
|
86
|
+
* alwaysLoadedChars: number,
|
|
87
|
+
* alwaysLoadedTokens: number,
|
|
88
|
+
* deferredChars: number,
|
|
89
|
+
* deferredTokens: number,
|
|
90
|
+
* }}
|
|
91
|
+
*/
|
|
92
|
+
export function sumFootprints(footprints) {
|
|
93
|
+
let alwaysLoadedTools = 0
|
|
94
|
+
let deferredTools = 0
|
|
95
|
+
let alwaysLoadedChars = 0
|
|
96
|
+
let alwaysLoadedTokens = 0
|
|
97
|
+
let deferredChars = 0
|
|
98
|
+
let deferredTokens = 0
|
|
99
|
+
|
|
100
|
+
if (!Array.isArray(footprints)) {
|
|
101
|
+
return {
|
|
102
|
+
alwaysLoadedTools,
|
|
103
|
+
deferredTools,
|
|
104
|
+
alwaysLoadedChars,
|
|
105
|
+
alwaysLoadedTokens,
|
|
106
|
+
deferredChars,
|
|
107
|
+
deferredTokens,
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
for (const item of footprints) {
|
|
112
|
+
if (!isRecord(item)) continue
|
|
113
|
+
const chars = Number.isFinite(item.chars) && item.chars >= 0 ? item.chars : 0
|
|
114
|
+
const tokens = Number.isFinite(item.estimatedTokens) && item.estimatedTokens >= 0 ? item.estimatedTokens : 0
|
|
115
|
+
if (item.deferred === true) {
|
|
116
|
+
deferredTools += 1
|
|
117
|
+
deferredChars += chars
|
|
118
|
+
deferredTokens += tokens
|
|
119
|
+
} else {
|
|
120
|
+
alwaysLoadedTools += 1
|
|
121
|
+
alwaysLoadedChars += chars
|
|
122
|
+
alwaysLoadedTokens += tokens
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
return {
|
|
127
|
+
alwaysLoadedTools,
|
|
128
|
+
deferredTools,
|
|
129
|
+
alwaysLoadedChars,
|
|
130
|
+
alwaysLoadedTokens,
|
|
131
|
+
deferredChars,
|
|
132
|
+
deferredTokens,
|
|
133
|
+
}
|
|
134
|
+
}
|