dsh-agent-router 1.9.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.en.md +304 -0
- package/README.md +304 -0
- package/client.js +3061 -0
- package/cordis.patch.yml +20 -0
- package/docs/ARCHITECTURE_DIAGNOSIS_AND_PLAN.md +414 -0
- package/docs/DETAIL.ja.md +1 -0
- package/docs/DETAIL.md +1 -0
- package/docs/DETAIL.zh.md +1 -0
- package/docs/IMPLEMENTATION_PLAN.md +99 -0
- package/docs/ITERATION_PLAN_2026-11.md +377 -0
- package/docs/RELEASE.md +133 -0
- package/docs/RELEASE_CHECKLIST.md +88 -0
- package/docs/preview.svg +69 -0
- package/docs/preview.zh.svg +63 -0
- package/icon.svg +16 -0
- package/index.js +24 -0
- package/lib/classifier.js +405 -0
- package/lib/cli/discover.js +187 -0
- package/lib/cli/invoke.js +294 -0
- package/lib/cli/parsers.js +234 -0
- package/lib/cli/shared.js +145 -0
- package/lib/cli-runners.js +39 -0
- package/lib/config-limits.js +67 -0
- package/lib/config-normalize.js +147 -0
- package/lib/config-presets.js +89 -0
- package/lib/config-schema.js +347 -0
- package/lib/defaults.js +117 -0
- package/lib/diagnose-fallback.js +96 -0
- package/lib/error-classify.js +160 -0
- package/lib/eval-routing.js +96 -0
- package/lib/guardrails.js +70 -0
- package/lib/integrations.js +173 -0
- package/lib/job-runner.js +287 -0
- package/lib/ledger.js +360 -0
- package/lib/legacy-config.js +34 -0
- package/lib/model-capabilities.js +135 -0
- package/lib/model-score.js +65 -0
- package/lib/plugin.js +184 -0
- package/lib/profile-mount.js +524 -0
- package/lib/route-edit.js +82 -0
- package/lib/router/candidates.js +194 -0
- package/lib/router/catalog.js +121 -0
- package/lib/router/cli-select.js +84 -0
- package/lib/router/config-manager.js +122 -0
- package/lib/router/doctor.js +159 -0
- package/lib/router/local-models.js +126 -0
- package/lib/router/policy.js +61 -0
- package/lib/router/rpc.js +263 -0
- package/lib/router/system-prompt.js +29 -0
- package/lib/router/tools.js +1028 -0
- package/lib/router/util.js +99 -0
- package/lib/rpc-contract.js +46 -0
- package/lib/sessions.js +59 -0
- package/lib/task-queue.js +201 -0
- package/lib/tier-presets.js +595 -0
- package/lib/typert.host.js +79 -0
- package/lib/update-check.js +205 -0
- package/lib/worktree-lock.js +86 -0
- package/lib/worktree.js +268 -0
- package/locale/en.json +7 -0
- package/locale/ja.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +136 -0
- package/scripts/profile-maintenance.mjs +287 -0
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure error classification for routed executions.
|
|
3
|
+
*
|
|
4
|
+
* A single tier can contain DSH subagents and several local CLIs, each with its
|
|
5
|
+
* own error vocabulary. Instead of treating every failure as retryable, map the
|
|
6
|
+
* message to a small set of categories that drive cooldown, failover, and tier
|
|
7
|
+
* escalation decisions.
|
|
8
|
+
*
|
|
9
|
+
* @module dsh-agent-router/lib/error-classify
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
export const ERROR_CATEGORIES = Object.freeze([
|
|
13
|
+
'cancelled',
|
|
14
|
+
'auth',
|
|
15
|
+
'invalid_request',
|
|
16
|
+
'context_overflow',
|
|
17
|
+
'rate_limit',
|
|
18
|
+
'timeout',
|
|
19
|
+
'network',
|
|
20
|
+
'model_unavailable',
|
|
21
|
+
'unknown',
|
|
22
|
+
])
|
|
23
|
+
|
|
24
|
+
const RULES = [
|
|
25
|
+
{
|
|
26
|
+
category: 'cancelled',
|
|
27
|
+
retryable: false,
|
|
28
|
+
cooldown: false,
|
|
29
|
+
escalate: false,
|
|
30
|
+
pattern: /cancel(?:l)?ed|abort(?:ed)?|interrupt|SIGINT|SIGTERM|user (?:rejected|denied|stopped)|operation was cancelled|context canceled/i,
|
|
31
|
+
},
|
|
32
|
+
{
|
|
33
|
+
category: 'auth',
|
|
34
|
+
retryable: false,
|
|
35
|
+
cooldown: false,
|
|
36
|
+
escalate: false,
|
|
37
|
+
pattern: /\b401\b|\b403\b|unauthori[sz]ed|forbidden|invalid api key|api key (?:is )?(?:missing|invalid)|authentication|not logged in|login required|permission denied|no credentials|missing credentials/i,
|
|
38
|
+
},
|
|
39
|
+
{
|
|
40
|
+
category: 'invalid_request',
|
|
41
|
+
retryable: false,
|
|
42
|
+
cooldown: false,
|
|
43
|
+
escalate: false,
|
|
44
|
+
pattern: /\b400\b|\b422\b|invalid[_ ]?(?:request|argument|parameter|value)|bad request|unknown (?:model|option|flag|argument)|unrecognized (?:option|argument)|validation (?:error|failed)|unsupported (?:option|argument|parameter)/i,
|
|
45
|
+
},
|
|
46
|
+
{
|
|
47
|
+
category: 'context_overflow',
|
|
48
|
+
retryable: true,
|
|
49
|
+
cooldown: false,
|
|
50
|
+
escalate: true,
|
|
51
|
+
pattern: /context (?:length|window)|maximum context|too many tokens|token limit|prompt is too long|exceeds? .*context|input is too long/i,
|
|
52
|
+
},
|
|
53
|
+
{
|
|
54
|
+
category: 'rate_limit',
|
|
55
|
+
retryable: true,
|
|
56
|
+
cooldown: true,
|
|
57
|
+
escalate: true,
|
|
58
|
+
pattern: /\b429\b|rate limit|too many requests|quota exceeded|overloaded|capacity/i,
|
|
59
|
+
},
|
|
60
|
+
{
|
|
61
|
+
category: 'timeout',
|
|
62
|
+
retryable: true,
|
|
63
|
+
cooldown: true,
|
|
64
|
+
escalate: true,
|
|
65
|
+
pattern: /timed out|timeout|ETIMEDOUT/i,
|
|
66
|
+
},
|
|
67
|
+
{
|
|
68
|
+
category: 'model_unavailable',
|
|
69
|
+
retryable: true,
|
|
70
|
+
cooldown: true,
|
|
71
|
+
escalate: true,
|
|
72
|
+
pattern: /model .*(?:not found|unavailable|does not exist|not supported)|no such model|unsupported model|decommissioned/i,
|
|
73
|
+
},
|
|
74
|
+
{
|
|
75
|
+
category: 'network',
|
|
76
|
+
retryable: true,
|
|
77
|
+
cooldown: true,
|
|
78
|
+
escalate: true,
|
|
79
|
+
pattern: /ECONNRESET|ENOTFOUND|EAI_AGAIN|ECONNREFUSED|EPIPE|network|socket hang up|fetch failed|\b50[0234]\b|service unavailable|bad gateway|gateway timeout|internal server error|connection (?:reset|refused|closed)/i,
|
|
80
|
+
},
|
|
81
|
+
]
|
|
82
|
+
|
|
83
|
+
const HINTS = {
|
|
84
|
+
cancelled: 'The run was cancelled; no retry or escalation is needed.',
|
|
85
|
+
auth: 'Check provider credentials or CLI login before dispatching again.',
|
|
86
|
+
invalid_request: 'Fix the request arguments or model id; retrying with the same input will not help.',
|
|
87
|
+
context_overflow: 'Use a longer-context model or a local CLI for this task.',
|
|
88
|
+
rate_limit: 'The provider is rate limited; the route is cooling down before retry.',
|
|
89
|
+
timeout: 'The run timed out; the route is cooling down before retry.',
|
|
90
|
+
network: 'A transient network/proxy error occurred; the route is cooling down before retry.',
|
|
91
|
+
model_unavailable: 'The selected model is unavailable; another candidate will be tried.',
|
|
92
|
+
unknown: 'Unclassified failure; the route is cooling down conservatively.',
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const DEFAULTS = {
|
|
96
|
+
unknown: { retryable: true, cooldown: true, escalate: true },
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* @param {unknown} input Error object, message, or CLI result payload.
|
|
101
|
+
* @returns {{
|
|
102
|
+
* category: string,
|
|
103
|
+
* retryable: boolean,
|
|
104
|
+
* cooldown: boolean,
|
|
105
|
+
* escalate: boolean,
|
|
106
|
+
* userHint: string,
|
|
107
|
+
* message: string,
|
|
108
|
+
* }}
|
|
109
|
+
*/
|
|
110
|
+
export function classifyError(input) {
|
|
111
|
+
const message = describeError(input)
|
|
112
|
+
for (const rule of RULES) {
|
|
113
|
+
if (rule.pattern.test(message)) {
|
|
114
|
+
return {
|
|
115
|
+
category: rule.category,
|
|
116
|
+
retryable: rule.retryable,
|
|
117
|
+
cooldown: rule.cooldown,
|
|
118
|
+
escalate: rule.escalate,
|
|
119
|
+
userHint: HINTS[rule.category],
|
|
120
|
+
message,
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
const fallback = DEFAULTS.unknown
|
|
125
|
+
return {
|
|
126
|
+
category: 'unknown',
|
|
127
|
+
retryable: fallback.retryable,
|
|
128
|
+
cooldown: fallback.cooldown,
|
|
129
|
+
escalate: fallback.escalate,
|
|
130
|
+
userHint: HINTS.unknown,
|
|
131
|
+
message,
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Escalate a tier only when at least one failure was not explicitly
|
|
137
|
+
* non-escalatable (auth / bad request / cancellation).
|
|
138
|
+
* @param {Array<{ escalate?: boolean }>} attempts
|
|
139
|
+
*/
|
|
140
|
+
export function shouldEscalateAfter(attempts) {
|
|
141
|
+
if (!Array.isArray(attempts) || attempts.length === 0) return true
|
|
142
|
+
return attempts.some(attempt => attempt?.escalate !== false)
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function describeError(input) {
|
|
146
|
+
if (input === null || input === undefined) return ''
|
|
147
|
+
if (typeof input === 'string') return input
|
|
148
|
+
if (input instanceof Error) return input.message || String(input)
|
|
149
|
+
if (typeof input === 'object') {
|
|
150
|
+
const parts = [input.error, input.message, input.stderrTail]
|
|
151
|
+
.filter(part => typeof part === 'string' && part.trim())
|
|
152
|
+
if (parts.length > 0) return parts.join(' | ')
|
|
153
|
+
try {
|
|
154
|
+
return JSON.stringify(input)
|
|
155
|
+
} catch {
|
|
156
|
+
return String(input)
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
return String(input)
|
|
160
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Offline routing evaluation over the local run ledger.
|
|
3
|
+
*
|
|
4
|
+
* Produces reproducible aggregates (success, latency, escalation, feedback) per
|
|
5
|
+
* tier and backend. No prompt or output bodies are included.
|
|
6
|
+
*
|
|
7
|
+
* @module dsh-agent-router/lib/eval-routing
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
function average(values) {
|
|
11
|
+
const nums = values.filter(value => typeof value === 'number' && Number.isFinite(value))
|
|
12
|
+
if (nums.length === 0) return null
|
|
13
|
+
return Number((nums.reduce((sum, value) => sum + value, 0) / nums.length).toFixed(2))
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function rate(part, total) {
|
|
17
|
+
return total > 0 ? Number((part / total).toFixed(4)) : null
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function emptyBucket() {
|
|
21
|
+
return { total: 0, succeeded: 0, failed: 0, escalated: 0, durations: [], ratings: [] }
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function finalize(bucket) {
|
|
25
|
+
const { durations, ratings, ...rest } = bucket
|
|
26
|
+
return {
|
|
27
|
+
...rest,
|
|
28
|
+
successRate: rate(bucket.succeeded, bucket.total),
|
|
29
|
+
avgDurationMs: average(durations),
|
|
30
|
+
avgRating: average(ratings),
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* @param {Array<Record<string, any>>} runs
|
|
36
|
+
* @param {{ limit?: number }} [opts]
|
|
37
|
+
*/
|
|
38
|
+
export function buildEvalReport(runs = [], { limit = 200 } = {}) {
|
|
39
|
+
const slice = Array.isArray(runs) ? runs.slice(0, Math.max(1, limit)) : []
|
|
40
|
+
const overall = emptyBucket()
|
|
41
|
+
const byTier = {}
|
|
42
|
+
const byBackend = {}
|
|
43
|
+
|
|
44
|
+
for (const run of slice) {
|
|
45
|
+
if (!run || typeof run !== 'object') continue
|
|
46
|
+
const tier = run.tier || 'unknown'
|
|
47
|
+
const backend = run.backend || 'unknown'
|
|
48
|
+
const tierBucket = byTier[tier] || (byTier[tier] = emptyBucket())
|
|
49
|
+
const backendBucket = byBackend[backend] || (byBackend[backend] = emptyBucket())
|
|
50
|
+
const buckets = [overall, tierBucket, backendBucket]
|
|
51
|
+
const rating = Number(run.quality?.rating)
|
|
52
|
+
|
|
53
|
+
for (const bucket of buckets) {
|
|
54
|
+
bucket.total += 1
|
|
55
|
+
if (run.status === 'completed') bucket.succeeded += 1
|
|
56
|
+
else if (run.status === 'failed' || run.status === 'cancelled') bucket.failed += 1
|
|
57
|
+
if (run.escalatedFrom) bucket.escalated += 1
|
|
58
|
+
if (typeof run.durationMs === 'number') bucket.durations.push(run.durationMs)
|
|
59
|
+
if (Number.isFinite(rating) && rating > 0) bucket.ratings.push(rating)
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
return {
|
|
64
|
+
generatedAt: new Date().toISOString(),
|
|
65
|
+
sampleSize: slice.length,
|
|
66
|
+
...finalize(overall),
|
|
67
|
+
escalationRate: rate(overall.escalated, overall.total),
|
|
68
|
+
byTier: Object.fromEntries(Object.entries(byTier).map(([key, bucket]) => [key, finalize(bucket)])),
|
|
69
|
+
byBackend: Object.fromEntries(Object.entries(byBackend).map(([key, bucket]) => [key, finalize(bucket)])),
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Render a compact CSV suitable for pasting into a spreadsheet.
|
|
75
|
+
* @param {ReturnType<typeof buildEvalReport>} report
|
|
76
|
+
*/
|
|
77
|
+
export function evalReportToCsv(report) {
|
|
78
|
+
const lines = ['scope,key,total,succeeded,failed,escalated,success_rate,avg_duration_ms,avg_rating']
|
|
79
|
+
lines.push([
|
|
80
|
+
'overall', 'all', report.total, report.succeeded, report.failed, report.escalated,
|
|
81
|
+
report.successRate ?? '', report.avgDurationMs ?? '', report.avgRating ?? '',
|
|
82
|
+
].join(','))
|
|
83
|
+
for (const [tier, bucket] of Object.entries(report.byTier || {})) {
|
|
84
|
+
lines.push([
|
|
85
|
+
'tier', tier, bucket.total, bucket.succeeded, bucket.failed, bucket.escalated,
|
|
86
|
+
bucket.successRate ?? '', bucket.avgDurationMs ?? '', bucket.avgRating ?? '',
|
|
87
|
+
].join(','))
|
|
88
|
+
}
|
|
89
|
+
for (const [backend, bucket] of Object.entries(report.byBackend || {})) {
|
|
90
|
+
lines.push([
|
|
91
|
+
'backend', backend, bucket.total, bucket.succeeded, bucket.failed, bucket.escalated,
|
|
92
|
+
bucket.successRate ?? '', bucket.avgDurationMs ?? '', bucket.avgRating ?? '',
|
|
93
|
+
].join(','))
|
|
94
|
+
}
|
|
95
|
+
return lines.join('\n')
|
|
96
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Safety guardrails shared by tool execution, ledger writes, and worktree ops:
|
|
3
|
+
* secret redaction and path containment.
|
|
4
|
+
* @module dsh-agent-router/lib/guardrails
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { relative, resolve, sep } from 'node:path'
|
|
8
|
+
|
|
9
|
+
const SECRET_PATTERNS = [
|
|
10
|
+
/\bsk-[A-Za-z0-9_-]{8,}\b/g,
|
|
11
|
+
/\bgh[pousr]_[A-Za-z0-9]{8,}\b/g,
|
|
12
|
+
/\bAKIA[0-9A-Z]{16}\b/g,
|
|
13
|
+
/\bxox[baprs]-[A-Za-z0-9-]{8,}\b/g,
|
|
14
|
+
/(Bearer\s+)[A-Za-z0-9._~+/=-]{8,}/gi,
|
|
15
|
+
/((?:api[_-]?key|token|secret|password)\s*[:=]\s*["']?)[^\s"',}]{6,}/gi,
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Redact known credential shapes from a single string.
|
|
20
|
+
* @param {string} text
|
|
21
|
+
*/
|
|
22
|
+
export function redactText(text) {
|
|
23
|
+
if (typeof text !== 'string' || !text) return text
|
|
24
|
+
let out = text
|
|
25
|
+
for (const pattern of SECRET_PATTERNS) {
|
|
26
|
+
out = out.replace(pattern, (match, prefix) => `${prefix || ''}[redacted]`)
|
|
27
|
+
}
|
|
28
|
+
return out
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Recursively redact strings in plain objects/arrays.
|
|
33
|
+
* @param {any} value
|
|
34
|
+
*/
|
|
35
|
+
export function redactSecrets(value) {
|
|
36
|
+
if (typeof value === 'string') return redactText(value)
|
|
37
|
+
if (Array.isArray(value)) return value.map(item => redactSecrets(item))
|
|
38
|
+
if (value && typeof value === 'object') {
|
|
39
|
+
const out = {}
|
|
40
|
+
for (const [key, item] of Object.entries(value)) out[key] = redactSecrets(item)
|
|
41
|
+
return out
|
|
42
|
+
}
|
|
43
|
+
return value
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Whether `target` resolves inside `root` (including `root` itself).
|
|
48
|
+
* @param {string} root
|
|
49
|
+
* @param {string} target
|
|
50
|
+
*/
|
|
51
|
+
export function isPathWithin(root, target) {
|
|
52
|
+
if (!root || !target) return false
|
|
53
|
+
const base = resolve(root)
|
|
54
|
+
const resolved = resolve(target)
|
|
55
|
+
const rel = relative(base, resolved)
|
|
56
|
+
return rel === '' || (rel !== '..' && !rel.startsWith(`..${sep}`) && !rel.startsWith('..'))
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Throw when a path escapes its allowed root.
|
|
61
|
+
* @param {string} root
|
|
62
|
+
* @param {string} target
|
|
63
|
+
* @param {string} [label]
|
|
64
|
+
*/
|
|
65
|
+
export function assertPathWithin(root, target, label = 'path') {
|
|
66
|
+
if (!isPathWithin(root, target)) {
|
|
67
|
+
throw new Error(`${label} "${target}" is outside the allowed root "${root}"`)
|
|
68
|
+
}
|
|
69
|
+
return resolve(target)
|
|
70
|
+
}
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Optional runtime integrations with `dsh-cost-meter` and `dsh-context` / session telemetry.
|
|
3
|
+
* Strictly feature-detected and fail-safe: works identically when neither sibling plugin is installed.
|
|
4
|
+
* @module dsh-agent-router/lib/integrations
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Determine whether current Beijing time (UTC+8) falls inside configured peak windows.
|
|
9
|
+
* @param {Array<{start:number,end:number}>} windows
|
|
10
|
+
* @param {string[]} [holidays]
|
|
11
|
+
* @param {number} [nowMs]
|
|
12
|
+
*/
|
|
13
|
+
export function isPeakWindowNow(windows, holidays = [], nowMs = Date.now()) {
|
|
14
|
+
if (!Array.isArray(windows) || windows.length === 0) return false
|
|
15
|
+
// Convert to UTC+8 clock
|
|
16
|
+
const bj = new Date(nowMs + 8 * 3600_000)
|
|
17
|
+
const day = bj.getUTCDay() // 0=Sun, 6=Sat
|
|
18
|
+
if (day === 0 || day === 6) return false
|
|
19
|
+
const dateKey = bj.toISOString().slice(0, 10)
|
|
20
|
+
if (Array.isArray(holidays) && holidays.includes(dateKey)) return false
|
|
21
|
+
const mins = bj.getUTCHours() * 60 + bj.getUTCMinutes()
|
|
22
|
+
const hour = bj.getUTCHours()
|
|
23
|
+
return windows.some((w) => {
|
|
24
|
+
const start = Number(w?.start)
|
|
25
|
+
const end = Number(w?.end)
|
|
26
|
+
if (!Number.isFinite(start) || !Number.isFinite(end)) return false
|
|
27
|
+
// dsh-cost-meter stores either hours (e.g. 9..12 or 8.5..16.5) or minutes (>= 24)
|
|
28
|
+
if (start <= 24 && end <= 24) {
|
|
29
|
+
return hour >= start && hour < end
|
|
30
|
+
}
|
|
31
|
+
return mins >= start && mins < end
|
|
32
|
+
})
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Read budget, today/month spend, and peak status from `dsh-cost-meter` if installed.
|
|
37
|
+
* Uses `getLocalState()` so it never blocks on slow remote balance/quota HTTP calls.
|
|
38
|
+
* @param {any} ctx
|
|
39
|
+
*/
|
|
40
|
+
export async function readCostMeterSnapshot(ctx) {
|
|
41
|
+
const costMeter = ctx?.get?.('costMeter')
|
|
42
|
+
if (!costMeter) return { available: false }
|
|
43
|
+
try {
|
|
44
|
+
const fn = typeof costMeter.getLocalState === 'function'
|
|
45
|
+
? () => costMeter.getLocalState()
|
|
46
|
+
: (typeof costMeter.getState === 'function' ? () => costMeter.getState() : null)
|
|
47
|
+
if (!fn) return { available: false }
|
|
48
|
+
|
|
49
|
+
const state = await Promise.race([
|
|
50
|
+
fn(),
|
|
51
|
+
new Promise((_, reject) => setTimeout(() => reject(new Error('costMeter timeout')), 1500)),
|
|
52
|
+
])
|
|
53
|
+
if (!state || typeof state !== 'object') return { available: false }
|
|
54
|
+
|
|
55
|
+
const cfg = state.config || {}
|
|
56
|
+
const budgetCfg = cfg.budget || {}
|
|
57
|
+
const amount = Number(budgetCfg.amount ?? 0)
|
|
58
|
+
const used = Number(state.budgetUsed ?? 0)
|
|
59
|
+
const enabled = budgetCfg.enabled === true && amount > 0
|
|
60
|
+
const ratio = enabled ? used / amount : 0
|
|
61
|
+
const isPeak = cfg.peakEnabled === true
|
|
62
|
+
? isPeakWindowNow(cfg.peakWindows, cfg.peakHolidays)
|
|
63
|
+
: false
|
|
64
|
+
|
|
65
|
+
return {
|
|
66
|
+
available: true,
|
|
67
|
+
currency: cfg.currency || 'USD',
|
|
68
|
+
symbol: cfg.symbol || '$',
|
|
69
|
+
todayCost: Number(state.today?.cost ?? 0),
|
|
70
|
+
monthCost: Number(state.month?.cost ?? 0),
|
|
71
|
+
budget: {
|
|
72
|
+
enabled,
|
|
73
|
+
period: budgetCfg.period || 'month',
|
|
74
|
+
amount,
|
|
75
|
+
used,
|
|
76
|
+
ratio,
|
|
77
|
+
nearLimit: enabled && ratio >= 0.85 && ratio < 1,
|
|
78
|
+
exhausted: enabled && ratio >= 1,
|
|
79
|
+
},
|
|
80
|
+
peak: {
|
|
81
|
+
enabled: cfg.peakEnabled === true,
|
|
82
|
+
isPeak,
|
|
83
|
+
},
|
|
84
|
+
}
|
|
85
|
+
} catch {
|
|
86
|
+
return { available: false }
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Estimate current caller context pressure from its latest session usage event.
|
|
92
|
+
* Matches `dsh-context`'s billed-token accounting (`inputTokens + cacheReadTokens + cacheWriteTokens`).
|
|
93
|
+
* @param {any} agent
|
|
94
|
+
* @param {any} ctx
|
|
95
|
+
*/
|
|
96
|
+
export async function readContextPressure(agent, ctx) {
|
|
97
|
+
if (!agent?.session) return { available: false }
|
|
98
|
+
try {
|
|
99
|
+
// Prefer DSH's own tokenMeter replay service when mounted
|
|
100
|
+
const tokenMeter = ctx?.get?.('tokenMeter')
|
|
101
|
+
if (tokenMeter && typeof tokenMeter.contextPressure === 'function') {
|
|
102
|
+
try {
|
|
103
|
+
const p = tokenMeter.contextPressure(agent.session)
|
|
104
|
+
const usedTokens = Number(p?.pressureTokens ?? 0)
|
|
105
|
+
const contextWindow = Number(p?.contextWindow ?? 0)
|
|
106
|
+
if (usedTokens > 0) {
|
|
107
|
+
const ratio = contextWindow > 0 ? usedTokens / contextWindow : null
|
|
108
|
+
return {
|
|
109
|
+
available: true,
|
|
110
|
+
usedTokens,
|
|
111
|
+
contextWindow: contextWindow || null,
|
|
112
|
+
ratio,
|
|
113
|
+
high: ratio !== null && ratio >= 0.65,
|
|
114
|
+
critical: ratio !== null && ratio >= 0.82,
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
} catch {}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const events = agent.session.snapshotEvents?.()
|
|
121
|
+
if (!Array.isArray(events)) return { available: false }
|
|
122
|
+
let latestUsage = null
|
|
123
|
+
for (let i = events.length - 1; i >= 0; i--) {
|
|
124
|
+
const ev = events[i]
|
|
125
|
+
if (ev?.type === 'assistant/message' && ev.data?.usage) {
|
|
126
|
+
latestUsage = ev.data.usage
|
|
127
|
+
break
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
if (!latestUsage) return { available: false }
|
|
131
|
+
|
|
132
|
+
const usedTokens = Number(latestUsage.inputTokens ?? 0)
|
|
133
|
+
+ Number(latestUsage.cacheReadTokens ?? 0)
|
|
134
|
+
+ Number(latestUsage.cacheWriteTokens ?? 0)
|
|
135
|
+
+ Number(latestUsage.outputTokens ?? 0)
|
|
136
|
+
|
|
137
|
+
const liveHeader = agent?.session?.requestHeader?.()?.config
|
|
138
|
+
let contextWindow = Number(agent?.model?.contextWindow ?? agent?.session?.header?.contextWindow ?? 0)
|
|
139
|
+
if (!contextWindow) {
|
|
140
|
+
const opts = liveHeader || agent?.agentOptions || agent?.options || agent?.session?.header?.agentOptions
|
|
141
|
+
const llm = ctx?.get?.('llm')
|
|
142
|
+
if (opts?.provider && opts?.model && typeof llm?.resolveModelInfo === 'function') {
|
|
143
|
+
try {
|
|
144
|
+
const info = await llm.resolveModelInfo(opts.provider, opts.model)
|
|
145
|
+
contextWindow = Number(info?.contextWindow ?? info?.context?.contextWindow ?? 0)
|
|
146
|
+
} catch {}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const ratio = contextWindow > 0 ? usedTokens / contextWindow : null
|
|
151
|
+
return {
|
|
152
|
+
available: true,
|
|
153
|
+
usedTokens,
|
|
154
|
+
contextWindow: contextWindow || null,
|
|
155
|
+
ratio,
|
|
156
|
+
high: ratio !== null && ratio >= 0.65,
|
|
157
|
+
critical: ratio !== null && ratio >= 0.82,
|
|
158
|
+
}
|
|
159
|
+
} catch {
|
|
160
|
+
return { available: false }
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Determine whether a candidate route uses DeepSeek official/DeepSeek-family API pricing.
|
|
166
|
+
* @param {{ kind?: string, provider?: string, model?: string }} candidate
|
|
167
|
+
*/
|
|
168
|
+
export function isDeepSeekFamilyRoute(candidate) {
|
|
169
|
+
if (!candidate || candidate.kind !== 'dsh') return false
|
|
170
|
+
const p = String(candidate.provider || '').toLowerCase()
|
|
171
|
+
const m = String(candidate.model || '').toLowerCase()
|
|
172
|
+
return p.includes('deepseek') || m.includes('deepseek')
|
|
173
|
+
}
|