dsh-context-compression-improved 0.2.3 → 0.2.4
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/.github/workflows/ci.yml +39 -39
- package/CHANGELOG.md +137 -135
- package/README.md +112 -112
- package/package.json +142 -142
- package/packages/selector/README.md +31 -31
- package/packages/selector/README.zh.md +31 -31
- package/packages/selector/dsh.plugin.json +16 -16
- package/packages/selector/lib/client.d.ts +228 -228
- package/packages/selector/lib/client.js +1462 -1462
- package/packages/selector/lib/config.js +856 -842
- package/packages/selector/lib/index.d.ts +37 -37
- package/packages/selector/lib/index.js +693 -645
- package/packages/selector/lib/invariant.js +70 -70
- package/packages/selector/lib/pruner.d.ts +728 -683
- package/packages/selector/lib/pruner.js +4765 -3807
- package/packages/selector/lib/style.css +46 -46
- package/packages/selector/lib/tail-trim.js +136 -136
- package/packages/selector/package.json +9 -1
- package/packages/selector/src/client/index.ts +111 -111
- package/packages/selector/src/preset-overlay.ts +60 -1
- package/packages/selector/src/pruner/content.ts +18 -5
- package/packages/selector/src/pruner/types.ts +23 -5
- package/packages/selector/src/pruner.ts +164 -154
- package/packages/selector/src/runtime/adaptive-cost.ts +23 -12
- package/packages/selector/src/runtime/audit.ts +18 -2
- package/packages/selector/src/runtime/config.ts +30 -1
- package/packages/selector/src/runtime/measurement.ts +31 -2
- package/packages/selector/src/runtime/reducers.ts +1115 -97
- package/packages/selector/src/runtime/tokenpilot/dedup.ts +1 -1
- package/packages/selector/src/runtime/tokenpilot/locator.ts +1 -1
- package/packages/selector/src/runtime/tokenpilot/read-state.ts +23 -2
- package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +275 -0
- package/packages/selector/src/runtime/toolclass.ts +103 -0
- package/packages/selector/src/runtime/types.ts +16 -0
- package/packages/selector/tests/preset-overlay.host.spec.ts +256 -243
- package/packages/selector/tests/runtime/adaptive-cost.spec.ts +7 -7
- package/packages/selector/tests/runtime/audit.spec.ts +44 -1
- package/packages/selector/tests/runtime/char-basis.spec.ts +30 -0
- package/packages/selector/tests/runtime/code-skeleton.spec.ts +14 -3
- package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +74 -0
- package/packages/selector/tests/runtime/html-reducer.spec.ts +212 -0
- package/packages/selector/tests/runtime/line-mapping.spec.ts +153 -0
- package/packages/selector/tests/runtime/prose-reducers.spec.ts +133 -0
- package/packages/selector/tests/runtime/public/public-runtime.spec.ts +198 -27
- package/packages/selector/tests/runtime/read-input-cap.spec.ts +33 -0
- package/packages/selector/tests/runtime/search-reducer.spec.ts +110 -0
- package/packages/selector/tests/runtime/sidechannel.spec.ts +241 -0
- package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +159 -0
- package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +24 -0
- package/packages/selector/tests/runtime/toolclass.spec.ts +156 -0
- package/packages/selector/tests/standing-generation.host.spec.ts +642 -631
- package/scripts/toolclass-corpus-replay.mjs +273 -0
|
@@ -76,6 +76,6 @@ export function dedupePlaceholder(entry: DedupeTableEntry, originalChars: number
|
|
|
76
76
|
return [
|
|
77
77
|
`[... identical to the earlier ${entry.toolName} result; first seen at ${entry.sourceRef};`,
|
|
78
78
|
`original_chars=${String(originalChars)};`,
|
|
79
|
-
'
|
|
79
|
+
'retrieve with context_compression_retrieve({"ref":"' + entry.sourceRef + '","start_line":1}) if the omitted evidence is necessary.]',
|
|
80
80
|
].join(' ')
|
|
81
81
|
}
|
|
@@ -118,7 +118,7 @@ export function buildLocatorBlock(
|
|
|
118
118
|
`- seq range: ${String(shadowedRange.start)}-${String(shadowedRange.end)}`,
|
|
119
119
|
...[...spillFiles].map(path => `- spill file: ${path}`),
|
|
120
120
|
...[...touchedFiles].map(path => `- file touched: ${path}`),
|
|
121
|
-
'(Use `read <spill file>` or `context_compression_retrieve` with a `session://` source to restore exact text.)',
|
|
121
|
+
'(Use `read <spill file>` or `context_compression_retrieve` with a `session://` source — pass start_line/max_lines to window the text — to restore exact text.)',
|
|
122
122
|
]
|
|
123
123
|
return {
|
|
124
124
|
text: lines.join('\n'),
|
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
* aggregate placeholder instead of the ordinary historical placeholder.
|
|
9
9
|
*/
|
|
10
10
|
import type { SessionEvent } from '@deepseek-ai/dsh-session'
|
|
11
|
+
import { looksLikeDocument } from '../reducers.ts'
|
|
11
12
|
|
|
12
13
|
/** Write-style tool names whose success supersedes earlier reads. */
|
|
13
14
|
const WRITE_TOOLS = /(?:^|[-_])?(?:write|edit|apply_patch|file_write|file_edit|str_replace|replace|multiedit)(?:$|[-_])/i
|
|
@@ -53,13 +54,18 @@ export function isSupersededRead(
|
|
|
53
54
|
/** Error/warning/info line classifiers used by the omission summary. */
|
|
54
55
|
const ERROR_LINE = /\b(error|failed|failure|fatal|exception|traceback|cannot|unable|denied)\b/i
|
|
55
56
|
const WARN_LINE = /\b(warn|warning|deprecated)\b/i
|
|
57
|
+
const SECTION_HEADING = /^#{1,3}\s+(.{1,80})/
|
|
56
58
|
|
|
57
59
|
/**
|
|
58
|
-
* Cluster one omitted line-count into
|
|
59
|
-
*
|
|
60
|
+
* Cluster one omitted line-count into a summary appended to a placeholder
|
|
61
|
+
* marker, giving the model meta-knowledge about what was dropped. Document
|
|
62
|
+
* content (R8) swaps the error/warn/info census for a section-heading list —
|
|
63
|
+
* `0 error, 0 warn, N info` carries no information about a dropped document,
|
|
64
|
+
* while its heading list does.
|
|
60
65
|
*/
|
|
61
66
|
export function clusterOmittedLines(text: string, omittedLines: number): string | undefined {
|
|
62
67
|
if (omittedLines <= 0) return undefined
|
|
68
|
+
if (looksLikeDocument(text)) return documentCensus(text, omittedLines)
|
|
63
69
|
let errors = 0
|
|
64
70
|
let warns = 0
|
|
65
71
|
let infos = 0
|
|
@@ -75,3 +81,18 @@ export function clusterOmittedLines(text: string, omittedLines: number): string
|
|
|
75
81
|
if (parts.length === 0) return undefined
|
|
76
82
|
return `${String(omittedLines)} lines omitted (${parts.join(', ')})`
|
|
77
83
|
}
|
|
84
|
+
|
|
85
|
+
/** Bounded section-heading list for an omitted document (R8 census). */
|
|
86
|
+
function documentCensus(text: string, omittedLines: number): string {
|
|
87
|
+
const titles: string[] = []
|
|
88
|
+
for (const line of text.split('\n')) {
|
|
89
|
+
const match = SECTION_HEADING.exec(line)
|
|
90
|
+
if (match === null) continue
|
|
91
|
+
titles.push(match[1]!.trim())
|
|
92
|
+
if (titles.length >= 8) break
|
|
93
|
+
}
|
|
94
|
+
if (titles.length === 0) return `${String(omittedLines)} lines omitted (document content)`
|
|
95
|
+
let summary = titles.join(' · ')
|
|
96
|
+
if (summary.length > 240) summary = `${summary.slice(0, 240)}…`
|
|
97
|
+
return `${String(omittedLines)} lines omitted (sections: ${summary})`
|
|
98
|
+
}
|
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* TokenPilot-inspired side channel (Phases 10–13).
|
|
3
|
+
*
|
|
4
|
+
* The S1 relevance filters (S1a search nodes, S1b document sections) ride the
|
|
5
|
+
* SAME transports the estimator uses — `host` (the Harness `llm` service) or
|
|
6
|
+
* `direct` (OpenAI-compatible HTTP) — with `maxTokens: 256`,
|
|
7
|
+
* `temperature: 0`, `reasoningEffort: 'off'`. No second provider/model
|
|
8
|
+
* configuration surface exists; failures are fail-open (`undefined`, never a
|
|
9
|
+
* throw) and the mechanical fold is always the fallback.
|
|
10
|
+
*
|
|
11
|
+
* Layer rules: the side channel only changes SELECTION and ORDER; it never
|
|
12
|
+
* rewrites content and never removes a node's existence (L1 locators and
|
|
13
|
+
* section headings always survive). Every call is cost-gated: if everything
|
|
14
|
+
* fits the budget the channel is not called at all.
|
|
15
|
+
*/
|
|
16
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
17
|
+
import type { PresetOptionsSettings } from '../types.ts'
|
|
18
|
+
|
|
19
|
+
/** The minimal face of the Harness `llm` service this module consumes. */
|
|
20
|
+
export interface HostLlmLike {
|
|
21
|
+
stream(request: {
|
|
22
|
+
provider: string
|
|
23
|
+
model: string
|
|
24
|
+
messages: readonly { readonly role: 'user', readonly content: readonly { readonly type: 'text', readonly text: string }[] }[]
|
|
25
|
+
system?: string
|
|
26
|
+
temperature?: number
|
|
27
|
+
reasoningEffort?: string
|
|
28
|
+
maxTokens?: number
|
|
29
|
+
signal?: AbortSignal
|
|
30
|
+
}): AsyncIterable<{ readonly type: string, readonly text?: string }>
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Audit record of one side-channel call (Phase 13). All fields optional-safe. */
|
|
34
|
+
export interface SideChannelAudit {
|
|
35
|
+
readonly ok: boolean
|
|
36
|
+
readonly latencyMs: number
|
|
37
|
+
/** host|direct plus the resolved provider/model identity. */
|
|
38
|
+
readonly channel?: string
|
|
39
|
+
/** L2 coverage: content shown N of node content total M. */
|
|
40
|
+
readonly coverage?: { readonly shown: number, readonly total: number }
|
|
41
|
+
readonly reason?: string
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface SideChannelRequest {
|
|
45
|
+
readonly system: string
|
|
46
|
+
readonly user: string
|
|
47
|
+
readonly signal: AbortSignal
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** One bound side channel. `ask` resolves `undefined` on ANY failure. */
|
|
51
|
+
export class SideChannel {
|
|
52
|
+
constructor(
|
|
53
|
+
private readonly ctx: Context,
|
|
54
|
+
private readonly options: PresetOptionsSettings,
|
|
55
|
+
) {}
|
|
56
|
+
|
|
57
|
+
get enabled(): boolean {
|
|
58
|
+
return this.options.estimatorMode === 'host' || this.options.estimatorMode === 'direct'
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async ask(request: SideChannelRequest): Promise<string | undefined> {
|
|
62
|
+
const timeoutMs = this.options.estimatorTimeoutMs ?? 3_000
|
|
63
|
+
const timeout = AbortSignal.timeout(timeoutMs)
|
|
64
|
+
const signal = typeof AbortSignal.any === 'function' ? AbortSignal.any([request.signal, timeout]) : timeout
|
|
65
|
+
try {
|
|
66
|
+
if (this.options.estimatorMode === 'host') return await this.askHost(request.system, request.user, signal)
|
|
67
|
+
if (this.options.estimatorMode === 'direct') return await this.askDirect(request.system, request.user, signal)
|
|
68
|
+
return undefined
|
|
69
|
+
} catch {
|
|
70
|
+
return undefined
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Failure-open wrapper that also records one audit record per call. */
|
|
75
|
+
async askAudited(request: SideChannelRequest): Promise<{ text?: string, audit: SideChannelAudit }> {
|
|
76
|
+
const now = Date.now()
|
|
77
|
+
const text = await this.ask(request)
|
|
78
|
+
const audit: SideChannelAudit = {
|
|
79
|
+
ok: text !== undefined,
|
|
80
|
+
latencyMs: Date.now() - now,
|
|
81
|
+
...this.identity() !== undefined ? { channel: this.identity()! } : {},
|
|
82
|
+
...(text === undefined ? { reason: 'channel returned no content (timeout, non-2xx, parse failure, or reasoning ate the 256-token budget)' } : {}),
|
|
83
|
+
}
|
|
84
|
+
return { ...(text === undefined ? {} : { text }), audit }
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
identity(): string | undefined {
|
|
88
|
+
if (this.options.estimatorMode === 'direct') {
|
|
89
|
+
return `direct:${this.options.estimatorModel ?? ''}`
|
|
90
|
+
}
|
|
91
|
+
if (this.options.estimatorMode === 'host') {
|
|
92
|
+
const route = this.resolveHostRoute()
|
|
93
|
+
return route === undefined ? 'host' : `host:${route.provider}/${route.model}`
|
|
94
|
+
}
|
|
95
|
+
return undefined
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Host-route resolution matching this version line's estimator semantics:
|
|
100
|
+
* an explicitly configured provider/model pair, nothing else.
|
|
101
|
+
*/
|
|
102
|
+
private resolveHostRoute(): { provider: string, model: string } | undefined {
|
|
103
|
+
const provider = this.options.estimatorProvider ?? ''
|
|
104
|
+
const model = this.options.estimatorModel ?? ''
|
|
105
|
+
if (provider.length > 0 && model.length > 0) return { provider, model }
|
|
106
|
+
return undefined
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
private async askHost(system: string, user: string, signal: AbortSignal): Promise<string | undefined> {
|
|
110
|
+
let llm: HostLlmLike | undefined
|
|
111
|
+
try {
|
|
112
|
+
llm = this.ctx.get('llm' as never) as HostLlmLike | undefined
|
|
113
|
+
} catch {
|
|
114
|
+
return undefined
|
|
115
|
+
}
|
|
116
|
+
if (llm?.stream === undefined) return undefined
|
|
117
|
+
const route = this.resolveHostRoute()
|
|
118
|
+
if (route === undefined) return undefined
|
|
119
|
+
let text = ''
|
|
120
|
+
const stream = llm.stream({
|
|
121
|
+
provider: route.provider,
|
|
122
|
+
model: route.model,
|
|
123
|
+
messages: [{ role: 'user', content: [{ type: 'text', text: user }] }],
|
|
124
|
+
system,
|
|
125
|
+
temperature: 0,
|
|
126
|
+
reasoningEffort: 'off',
|
|
127
|
+
maxTokens: 256,
|
|
128
|
+
signal,
|
|
129
|
+
})
|
|
130
|
+
for await (const chunk of stream) {
|
|
131
|
+
// reasoningEffort 'off' is a request, not a guarantee: if reasoning still
|
|
132
|
+
// eats the 256-token budget, `content` stays empty and the caller falls
|
|
133
|
+
// back to the mechanical fold (text.trim() check below).
|
|
134
|
+
if (chunk.type === 'text-delta' && typeof chunk.text === 'string') {
|
|
135
|
+
text += chunk.text
|
|
136
|
+
} else if (chunk.type === 'finish' && chunk.text === undefined) {
|
|
137
|
+
break
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
return text.trim().length > 0 ? text : undefined
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
private async askDirect(system: string, user: string, signal: AbortSignal): Promise<string | undefined> {
|
|
144
|
+
const baseUrl = this.options.estimatorBaseUrl
|
|
145
|
+
if (baseUrl === undefined || baseUrl.length === 0) return undefined
|
|
146
|
+
const headers: Record<string, string> = { 'content-type': 'application/json' }
|
|
147
|
+
if (this.options.estimatorApiKey !== undefined && this.options.estimatorApiKey.length > 0) {
|
|
148
|
+
headers.authorization = `Bearer ${this.options.estimatorApiKey}`
|
|
149
|
+
}
|
|
150
|
+
const model = this.options.estimatorModel ?? ''
|
|
151
|
+
if (model.length === 0) return undefined
|
|
152
|
+
const response = await fetch(`${baseUrl.replace(/\/+$/, '')}/chat/completions`, {
|
|
153
|
+
method: 'POST',
|
|
154
|
+
headers,
|
|
155
|
+
body: JSON.stringify({
|
|
156
|
+
model,
|
|
157
|
+
messages: [
|
|
158
|
+
{ role: 'system', content: system },
|
|
159
|
+
{ role: 'user', content: user },
|
|
160
|
+
],
|
|
161
|
+
temperature: 0,
|
|
162
|
+
max_tokens: 256,
|
|
163
|
+
}),
|
|
164
|
+
signal,
|
|
165
|
+
})
|
|
166
|
+
if (!response.ok) return undefined
|
|
167
|
+
const payload = (await response.json()) as {
|
|
168
|
+
choices?: { message?: { content?: string } }[]
|
|
169
|
+
}
|
|
170
|
+
const text = payload.choices?.[0]?.message?.content
|
|
171
|
+
return typeof text === 'string' && text.trim().length > 0 ? text : undefined
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Rank-then-cut (TS4): ONE call sorts and filters. The prompt carries the
|
|
177
|
+
* query, the main LLM's reasoning summary (the intent lives there — AD11),
|
|
178
|
+
* and per-node summaries with identifier + count + ONE content sample.
|
|
179
|
+
*/
|
|
180
|
+
export function buildRankSystemPrompt(kind: 'search' | 'document'): string {
|
|
181
|
+
const what = kind === 'search' ? 'files' : 'document sections'
|
|
182
|
+
return [
|
|
183
|
+
'You rank session artifacts by relevance to an agent query.',
|
|
184
|
+
`You are given numbered ${what} with a short sample each.`,
|
|
185
|
+
`Answer with ONLY the identifiers of the ${what} that matter, most relevant first,`,
|
|
186
|
+
'as a comma-separated list. Omit identifiers you consider irrelevant.',
|
|
187
|
+
'Never invent identifiers; never add commentary.',
|
|
188
|
+
].join(' ')
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
export function parseRanking(text: string | undefined, validIds: ReadonlySet<string>): string[] | undefined {
|
|
192
|
+
if (text === undefined || text.trim().length === 0) return undefined
|
|
193
|
+
const ranked: string[] = []
|
|
194
|
+
const seen = new Set<string>()
|
|
195
|
+
for (const token of text.split(/[\s,;]+/)) {
|
|
196
|
+
const id = token.replace(/[^\w./:#-]/gu, '')
|
|
197
|
+
if (id.length === 0 || !validIds.has(id) || seen.has(id)) continue
|
|
198
|
+
seen.add(id)
|
|
199
|
+
ranked.push(id)
|
|
200
|
+
}
|
|
201
|
+
return ranked.length > 0 ? ranked : undefined
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** Nodes mentioned by the LM keep their rank; the rest are appended in order (SC-existence). */
|
|
205
|
+
export function mergeRanking<T extends { readonly id: string }>(nodes: readonly T[], ranking: readonly string[] | undefined): readonly T[] {
|
|
206
|
+
if (ranking === undefined) return nodes
|
|
207
|
+
const byId = new Map(nodes.map(node => [node.id, node]))
|
|
208
|
+
const ordered: T[] = []
|
|
209
|
+
for (const id of ranking) {
|
|
210
|
+
const node = byId.get(id)
|
|
211
|
+
if (node !== undefined) ordered.push(node)
|
|
212
|
+
}
|
|
213
|
+
for (const node of nodes) {
|
|
214
|
+
if (!ordered.includes(node)) ordered.push(node)
|
|
215
|
+
}
|
|
216
|
+
return ordered
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** Cost gate (R-10): call only when something must be dropped and there is more than one node. */
|
|
220
|
+
export function sideChannelGate(fitsBudget: boolean, nodeCount: number): boolean {
|
|
221
|
+
return !fitsBudget && nodeCount > 1
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** One node face offered to the rank prompt: id + count/mass + ONE content sample. */
|
|
225
|
+
export interface RankedNode { readonly id: string, readonly detail: string, readonly sample: string }
|
|
226
|
+
|
|
227
|
+
export function buildRankUserPrompt(
|
|
228
|
+
nodes: readonly RankedNode[],
|
|
229
|
+
query: string,
|
|
230
|
+
reasoningSummary: string | undefined,
|
|
231
|
+
): string {
|
|
232
|
+
const lines = [
|
|
233
|
+
...(query.trim().length > 0 ? [`query: ${query.trim().slice(0, 300)}`] : []),
|
|
234
|
+
...(reasoningSummary !== undefined && reasoningSummary.trim().length > 0
|
|
235
|
+
? [`reasoning: ${reasoningSummary.trim().slice(0, 300)}`] : []),
|
|
236
|
+
...nodes.map(node => `${node.id} | ${node.detail} | ${node.sample.replace(/\s+/gu, ' ')}`),
|
|
237
|
+
]
|
|
238
|
+
return lines.join('\n')
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
export interface RankOutcome {
|
|
242
|
+
/** Ranked ids the LM returned; `undefined` on any failure (fail-open). */
|
|
243
|
+
readonly ranking?: readonly string[]
|
|
244
|
+
readonly audit: SideChannelAudit
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* S1 orchestrator: gate → ONE channel call → parse → merge. Every failure
|
|
249
|
+
* path (gate closed, channel undefined, garbage answer) resolves with
|
|
250
|
+
* `ranking: undefined`, which the mechanical fold reproduces byte-for-byte.
|
|
251
|
+
*/
|
|
252
|
+
export async function rankNodes(
|
|
253
|
+
nodes: readonly RankedNode[],
|
|
254
|
+
validIds: ReadonlySet<string>,
|
|
255
|
+
query: string,
|
|
256
|
+
reasoningSummary: string | undefined,
|
|
257
|
+
channel: Pick<SideChannel, 'ask' | 'askAudited' | 'identity'>,
|
|
258
|
+
signal: AbortSignal,
|
|
259
|
+
): Promise<RankOutcome> {
|
|
260
|
+
if (nodes.length <= 1 || query.trim().length === 0) {
|
|
261
|
+
return { audit: { ok: false, latencyMs: 0, reason: 'gate closed: single node or empty query' } }
|
|
262
|
+
}
|
|
263
|
+
const { text, audit } = await channel.askAudited({
|
|
264
|
+
system: buildRankSystemPrompt('search'),
|
|
265
|
+
user: buildRankUserPrompt(nodes, query, reasoningSummary),
|
|
266
|
+
signal,
|
|
267
|
+
})
|
|
268
|
+
const ranking = parseRanking(text, validIds)
|
|
269
|
+
return {
|
|
270
|
+
...(ranking === undefined ? {} : { ranking }),
|
|
271
|
+
audit: ranking === undefined
|
|
272
|
+
? { ...audit, ok: false, reason: 'unparseable or empty ranking; falling back to the mechanical fold' }
|
|
273
|
+
: audit,
|
|
274
|
+
}
|
|
275
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tool-source classification (R1/R2), narrowed to FOUR classes (tasks v2 G4):
|
|
3
|
+
* `read` / `shell` / `search` / `path-listing`, everything else `generic`.
|
|
4
|
+
*
|
|
5
|
+
* Form routing beats identity routing — most tools' results land through
|
|
6
|
+
* `read`/`cat` — so this layer exists to keep the OBSERVED misroutes out of
|
|
7
|
+
* the wrong reducers, not to add per-identity behavior:
|
|
8
|
+
* - `web_search` / `memory_search` are not content-search (findings §0)
|
|
9
|
+
* - `glob` is path listing, not search
|
|
10
|
+
* - `execute_sql` is not shell; `research` is not search (substring era bugs)
|
|
11
|
+
* - MCP output has no predictable identity (`mcp` token → generic, C8)
|
|
12
|
+
*
|
|
13
|
+
* Judgment order (C15): name whitelist → command hit → content fallback, and
|
|
14
|
+
* a hit at any earlier stage is never overridden by a later one.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
export type ToolClass = 'read' | 'shell' | 'search' | 'path-listing' | 'generic'
|
|
18
|
+
|
|
19
|
+
/** task_11 (AD3): exact-token matching, no substring hits. */
|
|
20
|
+
const TOKEN_SEPARATOR = /[-_/]+/
|
|
21
|
+
|
|
22
|
+
/** Multi-token names that must match as a whole word, not as a token. */
|
|
23
|
+
const READ_NAMES = new Set(['open_file'])
|
|
24
|
+
const READ_TOKENS = new Set(['read', 'cat', 'view'])
|
|
25
|
+
const SHELL_TOKENS = new Set(['shell', 'bash', 'pwsh', 'powershell', 'terminal', 'exec', 'command'])
|
|
26
|
+
const SEARCH_TOKENS = new Set(['grep', 'rg', 'ripgrep'])
|
|
27
|
+
const PATH_LISTING_TOKENS = new Set(['glob', 'tree', 'ls', 'fd', 'find'])
|
|
28
|
+
|
|
29
|
+
const SEARCH_COMMAND_PATTERN = /(?:^|\s)(?:rg|grep|ripgrep)\s/
|
|
30
|
+
const PATH_COMMAND_PATTERN = /(?:^|\s)(?:find|fd|ls|tree)\s/
|
|
31
|
+
|
|
32
|
+
/** grep-style hit line: `path:line[:column][: content]`. */
|
|
33
|
+
const PATH_LINE_CONTENT_PATTERN = /^(.*?):(\d+)(?::\d+)?(?::|\s+-\s+)(.*)$/
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Classify a tool result's source.
|
|
37
|
+
* @param name - raw tool name (case-insensitive).
|
|
38
|
+
* @param command - extracted command argument, '' when absent.
|
|
39
|
+
* @param text - result text; enables the C13/C14 content fallback for names
|
|
40
|
+
* that no whitelist (and no command hit) claims.
|
|
41
|
+
* @returns the tool source class.
|
|
42
|
+
*/
|
|
43
|
+
export function classifyToolSource(name: string, command: string, text?: string): ToolClass {
|
|
44
|
+
const lowered = name.toLowerCase()
|
|
45
|
+
const tokens = lowered.split(TOKEN_SEPARATOR).filter(token => token !== '')
|
|
46
|
+
// C8: an `mcp` token means the output identity is arbitrary — generic first,
|
|
47
|
+
// before any content heuristic gets a vote.
|
|
48
|
+
if (tokens.includes('mcp')) return 'generic'
|
|
49
|
+
const byName = classifyByName(lowered, tokens)
|
|
50
|
+
if (byName !== 'generic') return byName
|
|
51
|
+
const byCommand = classifyByCommand(command)
|
|
52
|
+
if (byCommand !== 'generic') return byCommand
|
|
53
|
+
return text === undefined ? 'generic' : classifyByContent(text)
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function classifyByName(lowered: string, tokens: readonly string[]): ToolClass {
|
|
57
|
+
if (READ_NAMES.has(lowered) || tokens.some(token => READ_TOKENS.has(token))) return 'read'
|
|
58
|
+
if (tokens.some(token => SHELL_TOKENS.has(token))) return 'shell'
|
|
59
|
+
if (tokens.some(token => SEARCH_TOKENS.has(token))) return 'search'
|
|
60
|
+
if (tokens.some(token => PATH_LISTING_TOKENS.has(token))) return 'path-listing'
|
|
61
|
+
return 'generic'
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function classifyByCommand(command: string): ToolClass {
|
|
65
|
+
if (command === '') return 'generic'
|
|
66
|
+
if (SEARCH_COMMAND_PATTERN.test(command)) return 'search'
|
|
67
|
+
if (PATH_COMMAND_PATTERN.test(command)) return 'path-listing'
|
|
68
|
+
return 'generic'
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** A path-shaped hit locator needs a path-looking prefix, not just `:digits`. */
|
|
72
|
+
function looksLikeFilePath(prefix: string): boolean {
|
|
73
|
+
if (prefix.includes('://')) return false
|
|
74
|
+
return prefix.includes('/') || prefix.includes('\\') || /\.[A-Za-z0-9]{1,8}$/.test(prefix)
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** A bare path: no whitespace, no URL scheme, with a separator or an extension. */
|
|
78
|
+
function isPurePathLine(line: string): boolean {
|
|
79
|
+
if (/\s/.test(line) || line.includes('://')) return false
|
|
80
|
+
return line.includes('/') || line.includes('\\') || /\.[A-Za-z0-9]{1,8}$/.test(line)
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Content fallback (C13/C14) for unknown names: one path-plausible
|
|
85
|
+
* `path:line:content` line reads as grep output; a body of ≥80% pure paths
|
|
86
|
+
* reads as a directory listing. Both require file-path evidence so prose
|
|
87
|
+
* (`Note: 2024 - ...`) and URLs (`https://host:8080 - ...`) stay generic.
|
|
88
|
+
*/
|
|
89
|
+
function classifyByContent(text: string): ToolClass {
|
|
90
|
+
let nonEmpty = 0
|
|
91
|
+
let purePaths = 0
|
|
92
|
+
let pathLineHits = 0
|
|
93
|
+
for (const line of text.split('\n')) {
|
|
94
|
+
if (line.trim() === '') continue
|
|
95
|
+
nonEmpty += 1
|
|
96
|
+
const match = PATH_LINE_CONTENT_PATTERN.exec(line)
|
|
97
|
+
if (match !== null && looksLikeFilePath(match[1] ?? '')) pathLineHits += 1
|
|
98
|
+
if (isPurePathLine(line)) purePaths += 1
|
|
99
|
+
}
|
|
100
|
+
if (pathLineHits >= 1) return 'search'
|
|
101
|
+
if (nonEmpty >= 4 && purePaths / nonEmpty >= 0.8) return 'path-listing'
|
|
102
|
+
return 'generic'
|
|
103
|
+
}
|
|
@@ -182,6 +182,14 @@ export interface ToolResultPruneConfig {
|
|
|
182
182
|
historyKeepRecentTokens?: number
|
|
183
183
|
/** Minimum reclaim required before historical aging is worth a cache break. Profile default when omitted. */
|
|
184
184
|
historyMinReclaimTokens?: number
|
|
185
|
+
/**
|
|
186
|
+
* Read-class input cap in characters. Invariant (startup-asserted in
|
|
187
|
+
* `resolvePolicy`): when set it must exceed `freshTriggerTokens × 4.0` —
|
|
188
|
+
* the conservative chars/token upper bound — otherwise the cap sits below
|
|
189
|
+
* the fresh trigger and silently silences the fresh path for every read
|
|
190
|
+
* result. Unset profiles (host cap 50k–59.5k chars observed) stay untouched.
|
|
191
|
+
*/
|
|
192
|
+
readInputCapChars?: number
|
|
185
193
|
/**
|
|
186
194
|
* Auto Compact threshold percent frozen into this deployment by the preset
|
|
187
195
|
* overlay generation (50–90 integer). When present it supersedes the live
|
|
@@ -211,6 +219,12 @@ export interface CompressionPolicy {
|
|
|
211
219
|
readonly historyKeepRecentToolCalls: number
|
|
212
220
|
readonly historyKeepRecentTokens: number
|
|
213
221
|
readonly historyMinReclaimTokens: number
|
|
222
|
+
/**
|
|
223
|
+
* Read-class input cap in characters when configured; absent otherwise.
|
|
224
|
+
* Startup-asserted to exceed `freshTriggerTokens × 4.0` so it can never
|
|
225
|
+
* silently silence the fresh path (G2 invariant).
|
|
226
|
+
*/
|
|
227
|
+
readonly readInputCapChars?: number
|
|
214
228
|
/**
|
|
215
229
|
* Auto Compact token watermark `A = floor(C × a)` when the standard-profile
|
|
216
230
|
* History linkage resolved for this Session; absent for Custom, Off, Native,
|
|
@@ -250,6 +264,8 @@ export interface ResolvedConfig {
|
|
|
250
264
|
readonly historyKeepRecentToolCalls?: number
|
|
251
265
|
readonly historyKeepRecentTokens?: number
|
|
252
266
|
readonly historyMinReclaimTokens?: number
|
|
267
|
+
/** Read-class input cap in characters when configured; absent otherwise. */
|
|
268
|
+
readonly readInputCapChars?: number
|
|
253
269
|
/**
|
|
254
270
|
* Auto Compact threshold percent frozen into this deployment by the preset
|
|
255
271
|
* overlay generation (50-90 integer). Supersedes the live Host setting.
|