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
package/lib/core/errors.js
CHANGED
|
@@ -50,11 +50,24 @@ export const notReady = (message, options) => new ApiError('not_ready', message,
|
|
|
50
50
|
/** @param {string} message @param {object} [options] @returns {ApiError} */
|
|
51
51
|
export const unprocessable = (message, options) => new ApiError('unprocessable', message, options)
|
|
52
52
|
|
|
53
|
+
/**
|
|
54
|
+
* An internal failure's message can name host paths or file names. The hint is
|
|
55
|
+
* shown to the page, so paths and token-like strings are redacted first.
|
|
56
|
+
* @param {string} message
|
|
57
|
+
* @returns {string}
|
|
58
|
+
*/
|
|
59
|
+
function sanitizeHint(message) {
|
|
60
|
+
return message
|
|
61
|
+
.replace(/\b(?:\/[\w.@+-]+){2,}\/?/g, '[path]')
|
|
62
|
+
.replace(/\b[A-Za-z0-9_-]{24,}\b/g, '[redacted]')
|
|
63
|
+
.slice(0, 200)
|
|
64
|
+
}
|
|
65
|
+
|
|
53
66
|
/** @param {unknown} error @returns {ApiError} */
|
|
54
67
|
export function toApiError(error) {
|
|
55
68
|
if (error instanceof ApiError) return error
|
|
56
69
|
const message = error instanceof Error && error.message.length > 0 ? error.message : 'internal error'
|
|
57
|
-
return new ApiError('internal', '内部错误', { hint: message
|
|
70
|
+
return new ApiError('internal', '内部错误', { hint: sanitizeHint(message), cause: error })
|
|
58
71
|
}
|
|
59
72
|
|
|
60
73
|
/** @param {number} status @returns {string} */
|
package/lib/core/http.js
CHANGED
|
@@ -104,6 +104,15 @@ function fallbackRejection(request) {
|
|
|
104
104
|
const loopback =
|
|
105
105
|
address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1' || address.startsWith('127.')
|
|
106
106
|
if (!loopback) return 403
|
|
107
|
+
// DNS rebinding: a page on evil.example keeps its own Host and Origin while
|
|
108
|
+
// the address now points at loopback, so the Host must name this machine.
|
|
109
|
+
const hostHeader = String(request.headers.host ?? '')
|
|
110
|
+
if (hostHeader.length > 0) {
|
|
111
|
+
const hostname = hostHeader.replace(/:[0-9]+$/, '').replace(/^\[|\]$/g, '').toLowerCase()
|
|
112
|
+
const loopbackHost =
|
|
113
|
+
hostname === 'localhost' || hostname.endsWith('.localhost') || hostname === '::1' || hostname === '127.0.0.1' || hostname.startsWith('127.')
|
|
114
|
+
if (!loopbackHost) return 403
|
|
115
|
+
}
|
|
107
116
|
const site = String(request.headers['sec-fetch-site'] ?? '').toLowerCase()
|
|
108
117
|
if (site === 'cross-site') return 403
|
|
109
118
|
const origin = request.headers.origin
|
|
@@ -127,6 +136,7 @@ function fallbackRejection(request) {
|
|
|
127
136
|
* getConnection?: () => { requestRejection?: (request: unknown) => 401 | 403 | undefined } | undefined,
|
|
128
137
|
* dispatch: (method: string, params: Record<string, unknown>, context: object) => Promise<unknown>,
|
|
129
138
|
* health: () => unknown,
|
|
139
|
+
* onRejected?: (info: { path: string, method: string, status: 401 | 403, address: string }) => void,
|
|
130
140
|
* }} options
|
|
131
141
|
*/
|
|
132
142
|
export function createHttp(options) {
|
|
@@ -166,6 +176,18 @@ export function createHttp(options) {
|
|
|
166
176
|
|
|
167
177
|
const rejection = rejectionOf(request)
|
|
168
178
|
if (rejection !== undefined) {
|
|
179
|
+
// A refusal is security-relevant state: record it so a repeated probe
|
|
180
|
+
// leaves a trail even though nothing was executed.
|
|
181
|
+
try {
|
|
182
|
+
options.onRejected?.({
|
|
183
|
+
path,
|
|
184
|
+
method,
|
|
185
|
+
status: rejection,
|
|
186
|
+
address: String(request.socket?.remoteAddress ?? ''),
|
|
187
|
+
})
|
|
188
|
+
} catch {
|
|
189
|
+
/* auditing must never turn a refusal into an error */
|
|
190
|
+
}
|
|
169
191
|
sendText(response, rejection, rejection === 401 ? 'unauthorized' : 'forbidden')
|
|
170
192
|
return
|
|
171
193
|
}
|
package/lib/core/index.js
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
import os from 'node:os'
|
|
7
7
|
import path from 'node:path'
|
|
8
8
|
import { createCaps } from './caps.js'
|
|
9
|
-
import { createPathFence } from './paths.js'
|
|
9
|
+
import { createPathFence, isInside as isInsidePath } from './paths.js'
|
|
10
10
|
import { createStore } from './store.js'
|
|
11
11
|
import * as errors from './errors.js'
|
|
12
12
|
import * as util from './util.js'
|
|
@@ -23,8 +23,40 @@ const DEFAULTS = Object.freeze({
|
|
|
23
23
|
usageReplaySessions: 200,
|
|
24
24
|
usageReplayDays: 30,
|
|
25
25
|
aiAnalysisEnabled: false,
|
|
26
|
+
// null keeps each module's own default; a number applies to every cached
|
|
27
|
+
// module, an object tunes one module id at a time.
|
|
28
|
+
cacheTtlMs: null,
|
|
26
29
|
})
|
|
27
30
|
|
|
31
|
+
/** Cache lifetimes are keyed by module id; anything else is a typo. */
|
|
32
|
+
const CACHE_TTL_KEYS = new Set(['tools', 'diagnostics', 'diagnosticsSummary', 'recovery'])
|
|
33
|
+
/** One hour. A longer lifetime would let a page show stale host state for a day. */
|
|
34
|
+
const CACHE_TTL_MAX_MS = 3_600_000
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Accept `null` (module defaults), a number (all modules), or an object keyed by
|
|
38
|
+
* module id. Ranges are validated here so the cache never clamps a typo silently.
|
|
39
|
+
* @param {unknown} value
|
|
40
|
+
* @returns {void}
|
|
41
|
+
*/
|
|
42
|
+
function validateCacheTtl(value) {
|
|
43
|
+
if (value === null) return
|
|
44
|
+
const valid = (candidate) => typeof candidate === 'number' && Number.isInteger(candidate) && candidate >= 0 && candidate <= CACHE_TTL_MAX_MS
|
|
45
|
+
if (typeof value === 'number') {
|
|
46
|
+
if (!valid(value)) throw new Error(`agent-control-center: config.cacheTtlMs must be an integer in [0, ${CACHE_TTL_MAX_MS}]`)
|
|
47
|
+
return
|
|
48
|
+
}
|
|
49
|
+
if (typeof value !== 'object' || Array.isArray(value)) {
|
|
50
|
+
throw new Error('agent-control-center: config.cacheTtlMs must be null, a number, or an object keyed by module id')
|
|
51
|
+
}
|
|
52
|
+
for (const [key, entry] of Object.entries(/** @type {Record<string, unknown>} */ (value))) {
|
|
53
|
+
if (!CACHE_TTL_KEYS.has(key)) {
|
|
54
|
+
throw new Error(`agent-control-center: config.cacheTtlMs.${key} is not a cached module (${[...CACHE_TTL_KEYS].join(', ')})`)
|
|
55
|
+
}
|
|
56
|
+
if (!valid(entry)) throw new Error(`agent-control-center: config.cacheTtlMs.${key} must be an integer in [0, ${CACHE_TTL_MAX_MS}]`)
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
28
60
|
/**
|
|
29
61
|
* Validate the row config. Misconfiguration fails loud at load
|
|
30
62
|
* (AGENTS.md: no silent defaults for deployment choices).
|
|
@@ -60,6 +92,7 @@ export function normalizeConfig(raw) {
|
|
|
60
92
|
int('usageRetentionDays', 7, 730)
|
|
61
93
|
int('usageReplaySessions', 1, 2000)
|
|
62
94
|
int('usageReplayDays', 1, 365)
|
|
95
|
+
validateCacheTtl(config.cacheTtlMs)
|
|
63
96
|
if (!config.enabled) return config
|
|
64
97
|
|
|
65
98
|
const dshHome = process.env.DSH_HOME ?? path.join(os.homedir(), '.dsh')
|
|
@@ -93,7 +126,25 @@ export function createCore(options) {
|
|
|
93
126
|
readRoots.push(process.env.DSH_INSTALL_DIR)
|
|
94
127
|
}
|
|
95
128
|
const writeRoots = [config.dshHome, process.cwd()]
|
|
96
|
-
|
|
129
|
+
// `$DSH_HOME` is a read root because the user-global AGENTS.md lives there.
|
|
130
|
+
// The rest of that directory holds credentials, provider keys, profiles and
|
|
131
|
+
// durable session storage, so the fence refuses those even if a future
|
|
132
|
+
// caller asks for them by path.
|
|
133
|
+
const denySensitive = (absolute) => {
|
|
134
|
+
if (!isInsidePath(config.dshHome, absolute)) return null
|
|
135
|
+
const relative = path.relative(config.dshHome, absolute)
|
|
136
|
+
/** @type {string} */
|
|
137
|
+
const top = relative.split(path.sep)[0]
|
|
138
|
+
if (top === 'AGENTS.md' || top === 'CLAUDE.md' || top === 'AGENTS.local.md' || top === 'CLAUDE.local.md') return null
|
|
139
|
+
if (top === 'llm.env' || top === '.npmrc' || top === '.credentials.yaml' || top.startsWith('.credentials') || top.startsWith('.workbuddy')) {
|
|
140
|
+
return '该路径属于宿主凭据/密钥,插件不读取也不写入'
|
|
141
|
+
}
|
|
142
|
+
if (top === 'profiles' || top === 'storages' || top === 'skills' || top === '.git') {
|
|
143
|
+
return '该目录属于宿主内部数据,插件不读取也不写入'
|
|
144
|
+
}
|
|
145
|
+
return null
|
|
146
|
+
}
|
|
147
|
+
const paths = createPathFence({ readRoots, writeRoots, log: log.warn, deny: denySensitive })
|
|
97
148
|
const caps = createCaps({ ctx, log: log.warn })
|
|
98
149
|
return {
|
|
99
150
|
ctx,
|
package/lib/core/paths.js
CHANGED
|
@@ -49,6 +49,7 @@ async function realpathLenient(absolute) {
|
|
|
49
49
|
* readRoots?: readonly string[],
|
|
50
50
|
* writeRoots?: readonly string[],
|
|
51
51
|
* log?: (message: string) => void,
|
|
52
|
+
* deny?: (absolute: string) => string | null,
|
|
52
53
|
* }} options
|
|
53
54
|
* @returns {{
|
|
54
55
|
* resolveRead(candidate: string, options?: { cwd?: string }): Promise<{ absolute: string, root: string }>,
|
|
@@ -60,6 +61,7 @@ async function realpathLenient(absolute) {
|
|
|
60
61
|
export function createPathFence(options) {
|
|
61
62
|
const readRoots = (options.readRoots ?? []).filter((root) => typeof root === 'string' && path.isAbsolute(root))
|
|
62
63
|
const writeRoots = (options.writeRoots ?? []).filter((root) => typeof root === 'string' && path.isAbsolute(root))
|
|
64
|
+
const deny = typeof options.deny === 'function' ? options.deny : () => null
|
|
63
65
|
|
|
64
66
|
/**
|
|
65
67
|
* Widen the fence with one directory discovered from trusted host state (for
|
|
@@ -87,6 +89,8 @@ export function createPathFence(options) {
|
|
|
87
89
|
if (candidate.includes('\0')) throw forbidden('路径包含非法字符')
|
|
88
90
|
const absolute = path.isAbsolute(candidate) ? candidate : path.resolve(resolveOptions.cwd ?? process.cwd(), candidate)
|
|
89
91
|
const resolved = await realpathLenient(absolute)
|
|
92
|
+
const deniedRead = deny(resolved)
|
|
93
|
+
if (deniedRead !== null) throw forbidden(deniedRead)
|
|
90
94
|
const root = matchingRoot(readRoots, resolved)
|
|
91
95
|
if (root === undefined) throw forbidden('路径不在允许范围内')
|
|
92
96
|
return { absolute: resolved, root }
|
|
@@ -104,6 +108,8 @@ export function createPathFence(options) {
|
|
|
104
108
|
const absolute = path.isAbsolute(candidate) ? candidate : path.resolve(process.cwd(), candidate)
|
|
105
109
|
const resolved = await realpathLenient(absolute)
|
|
106
110
|
if (!allowList.has(resolved)) throw forbidden('该文件不在允许写入的清单内')
|
|
111
|
+
const deniedWrite = deny(resolved)
|
|
112
|
+
if (deniedWrite !== null) throw forbidden(deniedWrite)
|
|
107
113
|
if (matchingRoot(writeRoots, resolved) === undefined) throw forbidden('路径不在允许写入的根内')
|
|
108
114
|
return resolved
|
|
109
115
|
}
|
package/lib/core/registry.js
CHANGED
|
@@ -178,15 +178,31 @@ export function createRegistry(options) {
|
|
|
178
178
|
*/
|
|
179
179
|
refresh() {
|
|
180
180
|
for (const record of records) {
|
|
181
|
-
if (record.module === undefined
|
|
181
|
+
if (record.module === undefined) continue
|
|
182
|
+
// Re-probe: a module that reported BLOCKED at activation because a
|
|
183
|
+
// service was not mounted yet must recover once the service appears,
|
|
184
|
+
// and a probe that reads live state must not be frozen at boot.
|
|
185
|
+
let probe = record.probe ?? {}
|
|
186
|
+
// Only modules that already reported a probe get re-probed: an
|
|
187
|
+
// in-flight module has no trustworthy answer yet, so refresh derives a
|
|
188
|
+
// requires-only state for it instead of freezing a boot-time verdict.
|
|
189
|
+
if (record.probe !== undefined && typeof record.module.probe === 'function') {
|
|
190
|
+
try {
|
|
191
|
+
const next = record.module.probe()
|
|
192
|
+
if (next !== null && typeof next === 'object') probe = next
|
|
193
|
+
} catch (error) {
|
|
194
|
+
log(`module ${record.id} probe failed: ${String(error?.message ?? error)}`)
|
|
195
|
+
}
|
|
196
|
+
}
|
|
182
197
|
const missing = record.requires.filter((name) => !core.caps.get(name).present)
|
|
183
|
-
|
|
198
|
+
record.probe = probe
|
|
184
199
|
record.missing = missing
|
|
185
200
|
record.state = typeof probe.state === 'string' ? probe.state : missing.length === 0 ? 'FULL' : 'PARTIAL'
|
|
186
201
|
if (record.state === 'FULL' && missing.length > 0) record.state = 'PARTIAL'
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
}
|
|
202
|
+
const detail = typeof probe.detail === 'string' ? probe.detail : ''
|
|
203
|
+
if (detail.length > 0) record.detail = detail
|
|
204
|
+
else if (missing.length > 0) record.detail = `缺少能力:${missing.join(', ')}`
|
|
205
|
+
else if (record.detail === '' || record.detail.startsWith('缺少能力:')) record.detail = ''
|
|
190
206
|
}
|
|
191
207
|
return this.list()
|
|
192
208
|
},
|
package/lib/core/util.js
CHANGED
|
@@ -158,7 +158,10 @@ export function capList(items, limit) {
|
|
|
158
158
|
*/
|
|
159
159
|
export function redact(text, max = 200) {
|
|
160
160
|
return String(text ?? '')
|
|
161
|
-
.replace(/\b(sk|pk|ghp|gho|npm)_[A-Za-z0-9_-]{8,}/g, '[redacted]')
|
|
161
|
+
.replace(/\b(sk|pk|ghp|gho|npm|ghs|glpat|hf)[_-][A-Za-z0-9_-]{8,}/g, '[redacted]')
|
|
162
|
+
// Vendor keys with a hyphen separator (DeepSeek `sk-...`, Stripe-style
|
|
163
|
+
// prefixes) are the common case; the underscore form above cannot match.
|
|
164
|
+
.replace(/\b(sk|pk)-[A-Za-z0-9_-]{8,}/g, '[redacted]')
|
|
162
165
|
.replace(/\bBearer\s+[A-Za-z0-9._-]{8,}/gi, 'Bearer [redacted]')
|
|
163
166
|
.replace(/\b[A-Fa-f0-9]{32,}\b/g, '[redacted]')
|
|
164
167
|
.slice(0, max)
|
package/lib/modules/a-agents.js
CHANGED
|
@@ -864,25 +864,35 @@ export default function createModule(core) {
|
|
|
864
864
|
throw forbidden('路径不在允许范围内', { hint: String(error?.message ?? error).slice(0, 200) })
|
|
865
865
|
}
|
|
866
866
|
const directory = path.dirname(absoluteInput)
|
|
867
|
+
// A symlink named like an instruction file must not redirect the read or
|
|
868
|
+
// the write somewhere else: the resolved target has to keep the same file
|
|
869
|
+
// name and stay inside the same authorized directory.
|
|
870
|
+
const resolvedDirectory = path.dirname(resolvedPath)
|
|
871
|
+
if (path.basename(resolvedPath) !== fileName) {
|
|
872
|
+
throw forbidden('指令文件是符号链接,且指向另一个文件名', { hint: '只允许读取/编辑真实的指令文件,请改用实际文件路径' })
|
|
873
|
+
}
|
|
867
874
|
const globalHomes = [core.config.dshHome, agentsHome()]
|
|
868
875
|
for (const home of globalHomes) {
|
|
869
876
|
if (path.resolve(directory) === path.resolve(home) && fileName === USER_GLOBAL_FILE) {
|
|
877
|
+
if (path.resolve(resolvedDirectory) !== path.resolve(home)) {
|
|
878
|
+
throw forbidden('全局指令文件是符号链接,指向其它目录', { hint: '只允许真实文件' })
|
|
879
|
+
}
|
|
870
880
|
return {
|
|
871
|
-
absolute:
|
|
881
|
+
absolute: resolvedPath,
|
|
872
882
|
resolvedPath,
|
|
873
883
|
source: path.resolve(home) === path.resolve(core.config.dshHome) ? 'user-global' : 'agents-home',
|
|
874
|
-
directory,
|
|
884
|
+
directory: resolvedDirectory,
|
|
875
885
|
fileName,
|
|
876
886
|
}
|
|
877
887
|
}
|
|
878
888
|
}
|
|
879
889
|
// Widen first: a file at the project root is an ancestor of cwd, not inside it.
|
|
880
890
|
const chain = ancestorChain(rootProbe.root, cwd)
|
|
881
|
-
if (!chain.some((entry) => path.resolve(entry) === path.resolve(
|
|
891
|
+
if (!chain.some((entry) => path.resolve(entry) === path.resolve(resolvedDirectory))) {
|
|
882
892
|
throw forbidden('该文件不在当前工作目录的指令链上', { hint: '只允许编辑本项目根到会话工作目录之间的指令文件' })
|
|
883
893
|
}
|
|
884
894
|
const isLocal = config.localInstructionFileCandidates.includes(fileName)
|
|
885
|
-
return { absolute:
|
|
895
|
+
return { absolute: resolvedPath, resolvedPath, source: isLocal ? 'project-local' : 'project', directory: resolvedDirectory, fileName }
|
|
886
896
|
}
|
|
887
897
|
|
|
888
898
|
/* ---------------------------------------------------------------------- */
|
|
@@ -1334,6 +1344,95 @@ export default function createModule(core) {
|
|
|
1334
1344
|
* @param {unknown} params
|
|
1335
1345
|
* @returns {Promise<Record<string, any>>}
|
|
1336
1346
|
*/
|
|
1347
|
+
/**
|
|
1348
|
+
* Reassemble the model-facing instruction text from the files on the chain's
|
|
1349
|
+
* effective set, using the host's own frame, intro and budget decisions
|
|
1350
|
+
* (`dsh-agent-instructions/src/render.ts:255-330`). Read-only: nothing is
|
|
1351
|
+
* written, and `exact` states whether every chain stayed inside its budget
|
|
1352
|
+
* (the host then emits the same bytes from the same files).
|
|
1353
|
+
* @param {{ cwd?: string }} input
|
|
1354
|
+
* @returns {Promise<Record<string, any>>}
|
|
1355
|
+
*/
|
|
1356
|
+
async function renderMethod(input) {
|
|
1357
|
+
const resolved = await resolveCwd(input?.cwd)
|
|
1358
|
+
const chainData = await discover({ cwd: resolved.cwd, session: resolved.session })
|
|
1359
|
+
const maxBytes = chainData.config.maxBytes
|
|
1360
|
+
if (maxBytes === null || !(maxBytes > 0) || !Number.isFinite(maxBytes)) {
|
|
1361
|
+
return {
|
|
1362
|
+
available: false,
|
|
1363
|
+
reason: '未读到宿主的指令预算(maxBytes),无法判断哪些文件会进入模型',
|
|
1364
|
+
hint: '检查宿主 configEditor 的 agent-instructions 配置;只读项',
|
|
1365
|
+
cwd: chainData.cwd,
|
|
1366
|
+
projectRoot: chainData.projectRoot,
|
|
1367
|
+
budget: { maxBytes: null, source: chainData.config.maxBytesSource },
|
|
1368
|
+
}
|
|
1369
|
+
}
|
|
1370
|
+
/** @param {string} kind @returns {Array<{ displayPath: string, content: string }>} */
|
|
1371
|
+
const chainFiles = (kind) => chainData.items
|
|
1372
|
+
.filter((item) => item.readable && !item.tooLarge && !item.deduped
|
|
1373
|
+
&& (kind === 'global'
|
|
1374
|
+
? item.source === 'user-global' || item.source === 'agents-home'
|
|
1375
|
+
: item.source === 'project' || item.source === 'project-local'))
|
|
1376
|
+
.map((item) => ({ displayPath: item.displayPath, content: String(item.text ?? '') }))
|
|
1377
|
+
/**
|
|
1378
|
+
* Drop what the chain's budget omits and shorten what it truncates.
|
|
1379
|
+
* @param {Array<{ displayPath: string, content: string }>} files
|
|
1380
|
+
* @param {Record<string, any>} budget
|
|
1381
|
+
*/
|
|
1382
|
+
function applyBudget(files, budget) {
|
|
1383
|
+
const omitted = new Set(budget.omitted ?? [])
|
|
1384
|
+
const truncatedEntries = new Map((budget.truncated ?? []).map((entry) => [entry.displayPath, entry]))
|
|
1385
|
+
/** @type {Array<{ displayPath: string, content: string }>} */
|
|
1386
|
+
const kept = []
|
|
1387
|
+
for (const file of files) {
|
|
1388
|
+
if (omitted.has(file.displayPath)) continue
|
|
1389
|
+
const cut = truncatedEntries.get(file.displayPath)
|
|
1390
|
+
kept.push(cut === undefined ? file : { displayPath: file.displayPath, content: truncateUtf8(file.content, cut.includedBytes) })
|
|
1391
|
+
}
|
|
1392
|
+
return kept
|
|
1393
|
+
}
|
|
1394
|
+
const included = [
|
|
1395
|
+
...applyBudget(chainFiles('global'), chainData.chains.userGlobal),
|
|
1396
|
+
...applyBudget(chainFiles('project'), chainData.chains.project),
|
|
1397
|
+
]
|
|
1398
|
+
const omitted = [...(chainData.chains.userGlobal.omitted ?? []), ...(chainData.chains.project.omitted ?? [])]
|
|
1399
|
+
const truncated = [...(chainData.chains.userGlobal.truncated ?? []), ...(chainData.chains.project.truncated ?? [])]
|
|
1400
|
+
const exact = omitted.length === 0 && truncated.length === 0
|
|
1401
|
+
const intro = exact ? AGENT_INSTRUCTIONS_INTRO : COMPACT_AGENT_INSTRUCTIONS_INTRO
|
|
1402
|
+
const text = buildInstructionText(included, maxBytes, omitted, truncated, intro)
|
|
1403
|
+
return {
|
|
1404
|
+
available: true,
|
|
1405
|
+
mode: 'files',
|
|
1406
|
+
exact,
|
|
1407
|
+
cwd: chainData.cwd,
|
|
1408
|
+
projectRoot: chainData.projectRoot,
|
|
1409
|
+
text,
|
|
1410
|
+
bytes: byteLength(text),
|
|
1411
|
+
intro,
|
|
1412
|
+
budget: {
|
|
1413
|
+
maxBytes,
|
|
1414
|
+
source: chainData.config.maxBytesSource,
|
|
1415
|
+
userGlobal: {
|
|
1416
|
+
bytes: chainData.chains.userGlobal.bytes,
|
|
1417
|
+
renderedBytes: chainData.chains.userGlobal.renderedBytes,
|
|
1418
|
+
fits: chainData.chains.userGlobal.fits,
|
|
1419
|
+
},
|
|
1420
|
+
project: {
|
|
1421
|
+
bytes: chainData.chains.project.bytes,
|
|
1422
|
+
renderedBytes: chainData.chains.project.renderedBytes,
|
|
1423
|
+
fits: chainData.chains.project.fits,
|
|
1424
|
+
},
|
|
1425
|
+
},
|
|
1426
|
+
sections: included.map((file) => ({ displayPath: file.displayPath, bytes: byteLength(file.content) })),
|
|
1427
|
+
omitted,
|
|
1428
|
+
truncated,
|
|
1429
|
+
warnings: chainData.warnings ?? [],
|
|
1430
|
+
note: exact
|
|
1431
|
+
? '两条链都在预算内:文本由这些文件按宿主格式重新组合,宿主注入的字节应与此相同;会话精确视图可逐一比对。'
|
|
1432
|
+
: '存在省略或截断:这是按预算规则重组的近似文本,宿主实际注入可能有所不同;请以会话精确视图为准。',
|
|
1433
|
+
}
|
|
1434
|
+
}
|
|
1435
|
+
|
|
1337
1436
|
async function filesMethod(params) {
|
|
1338
1437
|
const p = util.paramsObject(params)
|
|
1339
1438
|
const requested = optionalStr(p, 'cwd', 4096)
|
|
@@ -1686,6 +1785,7 @@ export default function createModule(core) {
|
|
|
1686
1785
|
},
|
|
1687
1786
|
methods: {
|
|
1688
1787
|
'agents.files': async (params) => filesMethod(params),
|
|
1788
|
+
'agents.render': async (params) => renderMethod(util.paramsObject(params)),
|
|
1689
1789
|
'agents.list': async (params) => filesMethod(params),
|
|
1690
1790
|
'agents.read': async (params) => readMethod(params),
|
|
1691
1791
|
'agents.save': async (params, context) => saveMethod(params, context),
|
package/lib/modules/b-tools.js
CHANGED
|
@@ -20,6 +20,7 @@
|
|
|
20
20
|
*
|
|
21
21
|
* @module dsh-agent-control-center/modules/tools
|
|
22
22
|
*/
|
|
23
|
+
import { createCache, resolveCacheTtlMs, scheduleWarmup, withCacheMeta } from '../core/cache.js'
|
|
23
24
|
|
|
24
25
|
/** List descriptions are truncated; `tools.detail` carries the full text. */
|
|
25
26
|
const DESCRIPTION_LIMIT = 240
|
|
@@ -42,8 +43,42 @@ const DEFAULTS = Object.freeze({
|
|
|
42
43
|
|
|
43
44
|
const DAY_MS = 24 * 60 * 60 * 1000
|
|
44
45
|
|
|
46
|
+
/** Default lifetime for the inventory views; `config.cacheTtlMs` overrides it. */
|
|
47
|
+
const CACHE_TTL_MS = 30_000
|
|
48
|
+
/** One entry per parameter combination; bounded so a client cannot grow the map. */
|
|
49
|
+
const CACHE_MAX_ENTRIES = 24
|
|
50
|
+
/** Parameters warmed at activation, matching the first page load (days=7, presets on). */
|
|
51
|
+
const PREWARM_PARAMS = Object.freeze({ days: 7, includePresets: true })
|
|
52
|
+
|
|
45
53
|
export default function createModule(core) {
|
|
46
54
|
const { util } = core
|
|
55
|
+
// Inventory reads are the hottest Host path (registry views plus a bounded
|
|
56
|
+
// event scan per page load). One shared cache carries all three methods; keys
|
|
57
|
+
// include every parameter that changes the result, never the derived clock
|
|
58
|
+
// value, so repeated loads of one page hit.
|
|
59
|
+
const configuredTtlMs = resolveCacheTtlMs(core.config, 'tools', CACHE_TTL_MS)
|
|
60
|
+
const inventoryCache = createCache({
|
|
61
|
+
ttlMs: configuredTtlMs,
|
|
62
|
+
maxEntries: CACHE_MAX_ENTRIES,
|
|
63
|
+
label: 'tools:inventory',
|
|
64
|
+
})
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Resolve one inventory value through the cache. A degraded block
|
|
68
|
+
* (`available:false`) is a transient capability failure, so it is not stored:
|
|
69
|
+
* the next call retries instead of pinning the failure for the whole TTL.
|
|
70
|
+
* @param {string} key
|
|
71
|
+
* @param {boolean} refresh bypass the stored value but still join an in-flight scan
|
|
72
|
+
* @param {() => Promise<Record<string, any>>} compute
|
|
73
|
+
* @returns {Promise<Record<string, any>>}
|
|
74
|
+
*/
|
|
75
|
+
async function cached(key, refresh, compute) {
|
|
76
|
+
const resolved = await inventoryCache.resolve(key, compute, {
|
|
77
|
+
force: refresh,
|
|
78
|
+
shouldCache: (value) => value !== null && typeof value === 'object' && value.available === true,
|
|
79
|
+
})
|
|
80
|
+
return withCacheMeta(resolved)
|
|
81
|
+
}
|
|
47
82
|
|
|
48
83
|
/** Read a host service without assuming it exists (never throws). */
|
|
49
84
|
function service(name) {
|
|
@@ -774,7 +809,15 @@ export default function createModule(core) {
|
|
|
774
809
|
to = parsed
|
|
775
810
|
}
|
|
776
811
|
if (from > to) throw core.errors.badRequest('时间窗口为空:since 晚于 until')
|
|
777
|
-
|
|
812
|
+
// `sinceMs`/`untilMs` are the caller-supplied bounds only: a default window
|
|
813
|
+
// derived from `days` must not leak the wall clock into a cache key.
|
|
814
|
+
return {
|
|
815
|
+
from,
|
|
816
|
+
to,
|
|
817
|
+
days,
|
|
818
|
+
sinceMs: since === undefined || since === null ? null : from,
|
|
819
|
+
untilMs: until === undefined || until === null ? null : to,
|
|
820
|
+
}
|
|
778
821
|
}
|
|
779
822
|
|
|
780
823
|
/** @param {Record<string, unknown>} params */
|
|
@@ -789,27 +832,18 @@ export default function createModule(core) {
|
|
|
789
832
|
// Module
|
|
790
833
|
// -------------------------------------------------------------------------
|
|
791
834
|
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
return { state: 'PARTIAL', detail: '没有 sessionQuery:历史调用统计不可用(清单与三层状态仍可用)' }
|
|
805
|
-
}
|
|
806
|
-
return { state: 'FULL', detail: '' }
|
|
807
|
-
},
|
|
808
|
-
methods: {
|
|
809
|
-
/** Read-only inventory: registry views, three status layers, call counts. */
|
|
810
|
-
'tools.list': async (rawParams) => {
|
|
811
|
-
const params = util.paramsObject(rawParams)
|
|
812
|
-
const window = readWindow(params)
|
|
835
|
+
// -------------------------------------------------------------------------
|
|
836
|
+
// Methods and cache wiring
|
|
837
|
+
// -------------------------------------------------------------------------
|
|
838
|
+
|
|
839
|
+
/**
|
|
840
|
+
* Uncached implementations. Parameter validation stays here, so a rejected
|
|
841
|
+
* request throws before the cache lookup and can never store a value.
|
|
842
|
+
*/
|
|
843
|
+
const implementations = {
|
|
844
|
+
/** Read-only inventory: registry views, three status layers, call counts. */
|
|
845
|
+
'tools.list': async (params) => {
|
|
846
|
+
const window = readWindow(params)
|
|
813
847
|
const limit = util.numParam(params, 'limit', { min: 1, max: 500, fallback: DEFAULTS.limit })
|
|
814
848
|
const includeHistory = util.boolParam(params, 'includeHistory', true)
|
|
815
849
|
const includePresets = util.boolParam(params, 'includePresets', false)
|
|
@@ -876,8 +910,7 @@ export default function createModule(core) {
|
|
|
876
910
|
},
|
|
877
911
|
|
|
878
912
|
/** One tool: full schema, visibility basis, statistics, error distribution. */
|
|
879
|
-
'tools.detail': async (
|
|
880
|
-
const params = util.paramsObject(rawParams)
|
|
913
|
+
'tools.detail': async (params) => {
|
|
881
914
|
const name = util.strParam(params, 'name', { max: 200 })
|
|
882
915
|
const window = readWindow(params)
|
|
883
916
|
const includePresets = util.boolParam(params, 'includePresets', true)
|
|
@@ -1021,8 +1054,7 @@ export default function createModule(core) {
|
|
|
1021
1054
|
},
|
|
1022
1055
|
|
|
1023
1056
|
/** Compact totals for the overview page and the navigation badge. */
|
|
1024
|
-
'tools.summary': async (
|
|
1025
|
-
const params = util.paramsObject(rawParams)
|
|
1057
|
+
'tools.summary': async (params) => {
|
|
1026
1058
|
const days = util.numParam(params, 'days', { min: 1, max: 365, fallback: DEFAULTS.days })
|
|
1027
1059
|
const to = Date.now()
|
|
1028
1060
|
const from = to - days * DAY_MS
|
|
@@ -1066,6 +1098,117 @@ export default function createModule(core) {
|
|
|
1066
1098
|
probes: { executed: false },
|
|
1067
1099
|
}
|
|
1068
1100
|
},
|
|
1101
|
+
}
|
|
1102
|
+
|
|
1103
|
+
/**
|
|
1104
|
+
* Read one parameter with the same fallback the implementation applies. Raw
|
|
1105
|
+
* values are used on purpose: an invalid value makes the implementation
|
|
1106
|
+
* throw, and a throwing call is never cached, so a malformed request can only
|
|
1107
|
+
* cause a miss — never a wrong hit.
|
|
1108
|
+
* @param {unknown} value
|
|
1109
|
+
* @param {unknown} fallback
|
|
1110
|
+
* @returns {unknown}
|
|
1111
|
+
*/
|
|
1112
|
+
function paramOr(value, fallback) {
|
|
1113
|
+
return value === undefined || value === null ? fallback : value
|
|
1114
|
+
}
|
|
1115
|
+
|
|
1116
|
+
/**
|
|
1117
|
+
* Cache key for `tools.list`. Every parameter that changes the result is
|
|
1118
|
+
* included; the wall clock is not, so repeated loads of one window hit.
|
|
1119
|
+
* @param {Record<string, unknown>} params
|
|
1120
|
+
* @returns {string}
|
|
1121
|
+
*/
|
|
1122
|
+
function listCacheKey(params) {
|
|
1123
|
+
const agentId = paramOr(params.agentId, null)
|
|
1124
|
+
return JSON.stringify([
|
|
1125
|
+
'tools.list',
|
|
1126
|
+
paramOr(params.days, DEFAULTS.days),
|
|
1127
|
+
paramOr(params.since, null),
|
|
1128
|
+
paramOr(params.until, null),
|
|
1129
|
+
paramOr(params.limit, DEFAULTS.limit),
|
|
1130
|
+
paramOr(params.includeHistory, true),
|
|
1131
|
+
paramOr(params.includePresets, false),
|
|
1132
|
+
agentId === '' ? null : agentId,
|
|
1133
|
+
paramOr(params.maxSessions, DEFAULTS.maxSessions),
|
|
1134
|
+
paramOr(params.timeBudgetMs, DEFAULTS.timeBudgetMs),
|
|
1135
|
+
])
|
|
1136
|
+
}
|
|
1137
|
+
|
|
1138
|
+
/** @param {Record<string, unknown>} params @returns {string} */
|
|
1139
|
+
function detailCacheKey(params) {
|
|
1140
|
+
const agentId = paramOr(params.agentId, null)
|
|
1141
|
+
return JSON.stringify([
|
|
1142
|
+
'tools.detail',
|
|
1143
|
+
paramOr(params.name, ''),
|
|
1144
|
+
paramOr(params.days, DEFAULTS.days),
|
|
1145
|
+
paramOr(params.since, null),
|
|
1146
|
+
paramOr(params.until, null),
|
|
1147
|
+
paramOr(params.includePresets, true),
|
|
1148
|
+
agentId === '' ? null : agentId,
|
|
1149
|
+
paramOr(params.clusters, DEFAULTS.clusters),
|
|
1150
|
+
paramOr(params.samples, DEFAULTS.samples),
|
|
1151
|
+
paramOr(params.maxSessions, DEFAULTS.maxSessions),
|
|
1152
|
+
paramOr(params.timeBudgetMs, DEFAULTS.timeBudgetMs),
|
|
1153
|
+
])
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1156
|
+
/** @param {Record<string, unknown>} params @returns {string} */
|
|
1157
|
+
function summaryCacheKey(params) {
|
|
1158
|
+
return JSON.stringify(['tools.summary', paramOr(params.days, DEFAULTS.days)])
|
|
1159
|
+
}
|
|
1160
|
+
|
|
1161
|
+
/** @type {Record<string, (params: Record<string, unknown>) => string>} */
|
|
1162
|
+
const CACHE_KEY_BUILDERS = {
|
|
1163
|
+
'tools.list': listCacheKey,
|
|
1164
|
+
'tools.detail': detailCacheKey,
|
|
1165
|
+
'tools.summary': summaryCacheKey,
|
|
1166
|
+
}
|
|
1167
|
+
|
|
1168
|
+
/** Registry entry points: validate, then read through the cache. */
|
|
1169
|
+
const methods = {}
|
|
1170
|
+
for (const [name, implementation] of Object.entries(implementations)) {
|
|
1171
|
+
const keyBuilder = CACHE_KEY_BUILDERS[name]
|
|
1172
|
+
methods[name] = async (rawParams) => {
|
|
1173
|
+
const params = util.paramsObject(rawParams)
|
|
1174
|
+
if (keyBuilder === undefined) return implementation(params)
|
|
1175
|
+
const refresh = util.boolParam(params, 'refresh', false)
|
|
1176
|
+
return cached(keyBuilder(params), refresh, () => implementation(params))
|
|
1177
|
+
}
|
|
1178
|
+
}
|
|
1179
|
+
|
|
1180
|
+
return {
|
|
1181
|
+
id: 'tools',
|
|
1182
|
+
title: 'nav.tools',
|
|
1183
|
+
order: 20,
|
|
1184
|
+
requires: ['tools', 'sessionQuery'],
|
|
1185
|
+
/** Module defaults; a numeric `config.cacheTtlMs` overrides the lifetime. */
|
|
1186
|
+
cacheDefaults: Object.freeze({ cacheTtlMs: CACHE_TTL_MS, cacheMaxEntries: CACHE_MAX_ENTRIES }),
|
|
1187
|
+
/** Cache instance, exposed for the performance tests and operator probes. */
|
|
1188
|
+
caches: { inventory: inventoryCache },
|
|
1189
|
+
async init() {
|
|
1190
|
+
if (configuredTtlMs <= 0) return
|
|
1191
|
+
// Warm the first page load after activation. A failed warm-up only logs:
|
|
1192
|
+
// the cache stays cold and the first request computes.
|
|
1193
|
+
scheduleWarmup(() => methods['tools.list'](PREWARM_PARAMS).catch((error) => {
|
|
1194
|
+
try {
|
|
1195
|
+
core.log?.warn?.(`tools prewarm failed: ${util.redact(String(error?.message ?? error), 160)}`)
|
|
1196
|
+
} catch {
|
|
1197
|
+
// A logger failure must not turn into an unhandled rejection.
|
|
1198
|
+
}
|
|
1199
|
+
}))
|
|
1200
|
+
},
|
|
1201
|
+
probe: () => {
|
|
1202
|
+
const tools = service('tools')
|
|
1203
|
+
if (tools === undefined || typeof tools.definitions !== 'function') {
|
|
1204
|
+
return { state: 'BLOCKED', detail: '宿主未提供 tools 服务(definitions)' }
|
|
1205
|
+
}
|
|
1206
|
+
const query = service('sessionQuery')
|
|
1207
|
+
if (query === undefined || typeof query.listSessions !== 'function' || typeof query.readSession !== 'function') {
|
|
1208
|
+
return { state: 'PARTIAL', detail: '没有 sessionQuery:历史调用统计不可用(清单与三层状态仍可用)' }
|
|
1209
|
+
}
|
|
1210
|
+
return { state: 'FULL', detail: '' }
|
|
1069
1211
|
},
|
|
1212
|
+
methods,
|
|
1070
1213
|
}
|
|
1071
1214
|
}
|