dsh-context-compression-improved 0.2.3 → 0.2.5
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/.gitattributes +2 -1
- package/.githooks/pre-push +37 -0
- package/.github/workflows/ci.yml +39 -39
- package/CHANGELOG.ja.md +169 -39
- package/CHANGELOG.ko.md +167 -39
- package/CHANGELOG.md +333 -135
- package/CHANGELOG.zh.md +152 -39
- package/CONTRIBUTING.md +22 -22
- package/README.ja.md +85 -104
- package/README.ko.md +85 -103
- package/README.md +94 -112
- package/README.zh.md +85 -101
- package/THIRD_PARTY_NOTICES.md +14 -14
- package/docs/compat-0.1.5-report.md +77 -0
- package/docs/installation.ja.md +78 -76
- package/docs/installation.ko.md +78 -76
- package/docs/installation.md +103 -76
- package/docs/installation.zh.md +100 -76
- package/docs/repair-log.md +657 -582
- package/eslint.config.js +30 -30
- package/package.json +163 -142
- package/packages/selector/README.md +26 -31
- package/packages/selector/README.zh.md +24 -31
- package/packages/selector/THIRD_PARTY_NOTICES.md +32 -38
- package/packages/selector/cordis.patch.yml +27 -19
- package/packages/selector/dsh.plugin.json +2 -2
- package/packages/selector/lib/client.d.ts +320 -228
- package/packages/selector/lib/client.js +3254 -1462
- package/packages/selector/lib/config.js +1713 -842
- package/packages/selector/lib/index.d.ts +46 -38
- package/packages/selector/lib/index.js +1099 -645
- package/packages/selector/lib/invariant.js +70 -70
- package/packages/selector/lib/pruner.d.ts +904 -684
- package/packages/selector/lib/pruner.js +5800 -3807
- package/packages/selector/lib/style.css +88 -46
- package/packages/selector/lib/tail-trim.js +145 -136
- package/packages/selector/package.json +18 -19
- package/packages/selector/screenshots.json +3 -6
- package/packages/selector/src/client/CompressionProfileControls.tsx +293 -229
- package/packages/selector/src/client/CompressionProfileSelector.module.css +199 -170
- package/packages/selector/src/client/CompressionProfileSelector.tsx +85 -79
- package/packages/selector/src/client/EstimatorControls.tsx +277 -281
- package/packages/selector/src/client/decode.ts +57 -49
- package/packages/selector/src/client/index.ts +249 -111
- package/packages/selector/src/client/locales/de.ts +141 -0
- package/packages/selector/src/client/locales/es.ts +141 -0
- package/packages/selector/src/client/locales/fr.ts +141 -0
- package/packages/selector/src/client/locales/it.ts +141 -0
- package/packages/selector/src/client/locales/ja.ts +141 -0
- package/packages/selector/src/client/locales/ko.ts +141 -0
- package/packages/selector/src/client/locales/ru.ts +141 -0
- package/packages/selector/src/client/locales.ts +282 -198
- package/packages/selector/src/client/monitor-fab.ts +336 -0
- package/packages/selector/src/client/preset-options.ts +88 -70
- package/packages/selector/src/client/savings-card.tsx +150 -0
- package/packages/selector/src/client/settings-section.tsx +140 -126
- package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -210
- package/packages/selector/src/index.ts +671 -327
- package/packages/selector/src/invariant.ts +113 -113
- package/packages/selector/src/preset-overlay.ts +60 -1
- package/packages/selector/src/profiles.ts +431 -342
- package/packages/selector/src/pruner/content.ts +18 -5
- package/packages/selector/src/pruner/state.ts +57 -43
- package/packages/selector/src/pruner/types.ts +23 -5
- package/packages/selector/src/pruner.ts +2736 -2144
- package/packages/selector/src/runtime/adaptive-cost.ts +23 -12
- package/packages/selector/src/runtime/audit.ts +303 -215
- package/packages/selector/src/runtime/config.ts +756 -613
- package/packages/selector/src/runtime/measurement.ts +436 -403
- package/packages/selector/src/runtime/monitor.ts +235 -0
- package/packages/selector/src/runtime/reducers.ts +1115 -97
- package/packages/selector/src/runtime/retrieve.ts +479 -457
- package/packages/selector/src/runtime/savings.ts +337 -0
- package/packages/selector/src/runtime/session-events.ts +30 -17
- package/packages/selector/src/runtime/summary-command.ts +127 -0
- package/packages/selector/src/runtime/tail-trim.ts +166 -166
- package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -0
- package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -0
- package/packages/selector/src/runtime/tokenpilot/advisor.ts +419 -0
- package/packages/selector/src/runtime/tokenpilot/benefit.ts +200 -0
- package/packages/selector/src/runtime/tokenpilot/dedup.ts +1 -1
- package/packages/selector/src/runtime/tokenpilot/estimator.ts +151 -183
- package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -0
- package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -0
- package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -0
- package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -0
- 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 +303 -0
- package/packages/selector/src/runtime/toolclass.ts +103 -0
- package/packages/selector/src/runtime/types.ts +365 -309
- package/packages/selector/tests/advisor-report.host.spec.ts +223 -0
- package/packages/selector/tests/auto-compact.client.spec.tsx +214 -226
- package/packages/selector/tests/built/client-artifact.spec.ts +59 -51
- package/packages/selector/tests/code-skeleton.client.spec.ts +91 -88
- package/packages/selector/tests/custom-contract.client.spec.ts +205 -202
- package/packages/selector/tests/estimator-channel.client.spec.tsx +253 -247
- package/packages/selector/tests/estimator-route-registration.host.spec.ts +194 -176
- package/packages/selector/tests/host-preset-overlay.host.spec.ts +206 -204
- package/packages/selector/tests/monitor-fab.client.spec.ts +138 -0
- package/packages/selector/tests/preset-options-write.client.spec.ts +207 -181
- package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +201 -196
- package/packages/selector/tests/preset-overlay.host.spec.ts +246 -243
- package/packages/selector/tests/profiles.client.spec.tsx +436 -434
- package/packages/selector/tests/public/package-contract.client.spec.ts +78 -33
- package/packages/selector/tests/runtime/adaptive-cost.spec.ts +7 -7
- package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +232 -0
- package/packages/selector/tests/runtime/advisor-invariant.spec.ts +272 -0
- package/packages/selector/tests/runtime/advisor.spec.ts +226 -0
- package/packages/selector/tests/runtime/audit.spec.ts +275 -129
- 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/deprecated-preset-options.spec.ts +96 -0
- 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/intent-gate.spec.ts +62 -0
- package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -0
- package/packages/selector/tests/runtime/line-mapping.spec.ts +153 -0
- package/packages/selector/tests/runtime/monitor.spec.ts +301 -0
- package/packages/selector/tests/runtime/prose-reducers.spec.ts +133 -0
- package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2724 -2531
- package/packages/selector/tests/runtime/read-input-cap.spec.ts +33 -0
- package/packages/selector/tests/runtime/savings.spec.ts +120 -0
- package/packages/selector/tests/runtime/search-reducer.spec.ts +110 -0
- package/packages/selector/tests/runtime/session-events.spec.ts +27 -27
- package/packages/selector/tests/runtime/sidechannel.spec.ts +241 -0
- package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
- package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +159 -0
- package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +217 -0
- package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +79 -56
- package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +116 -100
- 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/settings-seat.client.spec.ts +130 -0
- package/packages/selector/tests/standing-generation.host.spec.ts +697 -631
- package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +253 -250
- package/pnpm-workspace.yaml +66 -19
- package/scripts/capture-profile-baseline.mjs +42 -0
- package/scripts/generate-tokenizer-fixtures.py +81 -81
- package/scripts/generate-vision-fixtures.py +208 -208
- package/scripts/{packed-components-smoke.ts → packed-components-smoke.mjs} +732 -713
- package/scripts/{packed-install-e2e.ts → packed-install-e2e.mjs} +1273 -1072
- package/scripts/toolclass-corpus-replay.mjs +281 -0
- package/scripts/{verify-release.ts → verify-release.mjs} +318 -300
- package/tests/TEST_INVENTORY.md +41 -42
- package/scripts/capture-profile-baseline.ts +0 -80
- package/tsconfig.scripts.json +0 -13
- /package/{packages/selector/assets/screenshots → docs/assets}/context-compression-selector-profiles.jpg +0 -0
- /package/{packages/selector/assets/screenshots → docs/assets}/context-compression-selector-settings.png +0 -0
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Turn-tail intent-summary growth gate (TokenPilot-inspired E2).
|
|
3
|
+
*
|
|
4
|
+
* Pure decision helper evaluated at the turn-boundary postflight: it decides
|
|
5
|
+
* whether this turn may spend a summary-writer LLM call and stage a fold for
|
|
6
|
+
* the next pressure round. The gate is deliberately conservative — every
|
|
7
|
+
* unresolved input (unknown context window, non-finite counters) fails closed
|
|
8
|
+
* toward "do not run", because a skipped fold is free while a wasted summary
|
|
9
|
+
* call is not. Content safety is unaffected either way: fail-open semantics
|
|
10
|
+
* live in the fold landing path, not here.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** Floor: the live surface must exceed this fraction of the context window. */
|
|
14
|
+
export const INTENT_GATE_FLOOR_FRACTION = 0.45
|
|
15
|
+
|
|
16
|
+
/** Growth: the live surface must have grown by more than this since the last landed fold. */
|
|
17
|
+
export const INTENT_GATE_GROWTH_TOKENS = 50_000
|
|
18
|
+
|
|
19
|
+
/** Session-scoped user override set through `/ctx-summary off|on`. */
|
|
20
|
+
export type SummaryOverride = 'on' | 'off' | undefined
|
|
21
|
+
|
|
22
|
+
export interface IntentGateInput {
|
|
23
|
+
/** Frozen `intentSummary.enabled` setting for the session. */
|
|
24
|
+
enabled: boolean
|
|
25
|
+
/** `/ctx-summary` override; `'off'` wins over everything, `'on'` never bypasses the numeric gates. */
|
|
26
|
+
override: SummaryOverride
|
|
27
|
+
/** Exact live-surface token estimate from the compaction view. */
|
|
28
|
+
liveTokens: number
|
|
29
|
+
/** Host context window in tokens; `undefined` fails the floor check. */
|
|
30
|
+
contextWindow: number | undefined
|
|
31
|
+
/** Live-surface tokens at the time the last fold landed (0 = never folded). */
|
|
32
|
+
baselineTokens: number
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface IntentGateSnapshot extends IntentGateInput {
|
|
36
|
+
readonly decision: boolean
|
|
37
|
+
readonly reason: 'disabled' | 'override-off' | 'no-window' | 'below-floor' | 'below-growth' | 'passed'
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function isUsableNumber(value: number): boolean {
|
|
41
|
+
return Number.isFinite(value) && value >= 0
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Evaluate the growth gate. Boundary-exact: equality never triggers. */
|
|
45
|
+
export function shouldRunIntentFold(input: IntentGateInput): boolean {
|
|
46
|
+
return evaluateIntentGate(input).decision === true
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Same evaluation with the reason attached, for audits and `/ctx-summary status`. */
|
|
50
|
+
export function evaluateIntentGate(input: IntentGateInput): IntentGateSnapshot {
|
|
51
|
+
const snapshot = (decision: boolean, reason: IntentGateSnapshot['reason']): IntentGateSnapshot => ({
|
|
52
|
+
...input,
|
|
53
|
+
decision,
|
|
54
|
+
reason,
|
|
55
|
+
})
|
|
56
|
+
if (!input.enabled) return snapshot(false, 'disabled')
|
|
57
|
+
if (input.override === 'off') return snapshot(false, 'override-off')
|
|
58
|
+
if (!isUsableNumber(input.liveTokens)) return snapshot(false, 'below-floor')
|
|
59
|
+
if (input.contextWindow === undefined || !isUsableNumber(input.contextWindow)) return snapshot(false, 'no-window')
|
|
60
|
+
if (!(input.liveTokens > input.contextWindow * INTENT_GATE_FLOOR_FRACTION)) return snapshot(false, 'below-floor')
|
|
61
|
+
if (!isUsableNumber(input.baselineTokens)) return snapshot(false, 'below-growth')
|
|
62
|
+
const growth = input.liveTokens - input.baselineTokens
|
|
63
|
+
if (!(growth > INTENT_GATE_GROWTH_TOKENS)) return snapshot(false, 'below-growth')
|
|
64
|
+
return snapshot(true, 'passed')
|
|
65
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Semantic-role input masking for the intent-summary writer (task_2.2).
|
|
3
|
+
*
|
|
4
|
+
* The intent summary records historical TASK semantics — for read-class tools
|
|
5
|
+
* the semantics are "read X", never the file body, so the body is masked to a
|
|
6
|
+
* one-line record before it can reach the summary prompt. Write-class results
|
|
7
|
+
* (edits) ARE task semantics and keep their skeleton + verbatim error lines.
|
|
8
|
+
*
|
|
9
|
+
* Classification REUSES `classifyToolSource()` (reducers.ts routes on the
|
|
10
|
+
* same classes): hand-rolling a name→role map here would regress its fixed
|
|
11
|
+
* misclassification edges (mcp→generic, web_search/memory_search not being
|
|
12
|
+
* content search, glob being path-listing, execute_sql not being shell).
|
|
13
|
+
* Only the write class is layered on top — `ToolClass` has no write member.
|
|
14
|
+
*/
|
|
15
|
+
import { classifyToolSource, type ToolClass } from '../toolclass.ts'
|
|
16
|
+
|
|
17
|
+
export type IntentRole = 'read-mask' | 'write-keep' | 'conservative'
|
|
18
|
+
|
|
19
|
+
/** Exact-token write layer, same tokenization discipline as toolclass. */
|
|
20
|
+
const WRITE_NAMES = new Set(['apply_patch', 'multi_edit', 'create_file', 'write_to_file', 'str_replace_editor'])
|
|
21
|
+
const WRITE_TOKENS = new Set(['write', 'edit', 'patch'])
|
|
22
|
+
|
|
23
|
+
function hasWriteToken(name: string): boolean {
|
|
24
|
+
const lowered = name.toLowerCase()
|
|
25
|
+
if (WRITE_NAMES.has(lowered)) return true
|
|
26
|
+
return lowered.split(/[-_/]+/).some(token => WRITE_TOKENS.has(token))
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Role for one candidate. The write layer is consulted first; everything
|
|
31
|
+
* else defers to the shared classifier. `shell`/`generic` stay conservative
|
|
32
|
+
* (skeleton + error lines, never a blind mask) — a bash result can be a
|
|
33
|
+
* mutation even when its name says nothing.
|
|
34
|
+
*/
|
|
35
|
+
export function classifyIntentRole(toolName: string, command: string, text?: string): IntentRole {
|
|
36
|
+
if (hasWriteToken(toolName)) return 'write-keep'
|
|
37
|
+
const toolClass: ToolClass = classifyToolSource(toolName, command, text)
|
|
38
|
+
if (toolClass === 'read' || toolClass === 'search' || toolClass === 'path-listing') return 'read-mask'
|
|
39
|
+
return 'conservative'
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** One candidate's slimmed face for the summary prompt. */
|
|
43
|
+
export interface MaskedCandidate {
|
|
44
|
+
readonly seq: number
|
|
45
|
+
readonly role: IntentRole
|
|
46
|
+
/** Read-mask single line; skeleton/error lines for keep roles. */
|
|
47
|
+
readonly record: string
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const ERROR_LINE_PATTERN = /\b(error|failed|failure|exception|panic|fatal|traceback|unreachable|denied)\b/i
|
|
51
|
+
const KEEP_HEAD_LINES = 40
|
|
52
|
+
const KEEP_HEAD_CHARS = 2_000
|
|
53
|
+
|
|
54
|
+
/** Verbatim error/warn lines kept out of the LLM's hands and into the intent block. */
|
|
55
|
+
export function extractErrorLines(text: string): string[] {
|
|
56
|
+
return text.split('\n').filter(line => ERROR_LINE_PATTERN.test(line)).slice(0, 10)
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Count lines and code points for the read-mask record tail. */
|
|
60
|
+
function scaleOf(text: string): { lines: number, chars: number } {
|
|
61
|
+
const lines = text.length === 0 ? 0 : text.split('\n').length
|
|
62
|
+
return { lines, chars: text.length }
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Build the prompt face for one candidate. Read-mask output contains NONE of
|
|
67
|
+
* the original body — only the tool name, the call's target argument, and
|
|
68
|
+
* the dropped scale — so a hostile body can never leak into the summary.
|
|
69
|
+
*/
|
|
70
|
+
export function maskCandidateForSummary(
|
|
71
|
+
seq: number,
|
|
72
|
+
toolName: string,
|
|
73
|
+
argumentsText: string,
|
|
74
|
+
text: string,
|
|
75
|
+
): MaskedCandidate {
|
|
76
|
+
const role = classifyIntentRole(toolName, extractCommand(argumentsText), text)
|
|
77
|
+
if (role === 'read-mask') {
|
|
78
|
+
const { lines, chars } = scaleOf(text)
|
|
79
|
+
return {
|
|
80
|
+
seq,
|
|
81
|
+
role,
|
|
82
|
+
record: `${toolName} ${extractTarget(argumentsText)} -> masked (${lines} lines / ${chars} chars)`,
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
const head = text.split('\n', KEEP_HEAD_LINES).join('\n').slice(0, KEEP_HEAD_CHARS)
|
|
86
|
+
const errorLines = extractErrorLines(text)
|
|
87
|
+
const errorBlock = errorLines.length > 0 ? `\nerror lines (verbatim):\n${errorLines.join('\n')}` : ''
|
|
88
|
+
return {
|
|
89
|
+
seq,
|
|
90
|
+
role,
|
|
91
|
+
record: `${toolName} (seq ${seq})\n${head}${errorBlock}`,
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Extract a short command head from a tool-call arguments JSON string. */
|
|
96
|
+
function extractCommand(argumentsText: string): string {
|
|
97
|
+
try {
|
|
98
|
+
const parsed: unknown = JSON.parse(argumentsText)
|
|
99
|
+
if (parsed !== null && typeof parsed === 'object') {
|
|
100
|
+
const command = (parsed as { command?: unknown }).command
|
|
101
|
+
if (typeof command === 'string') return command.slice(0, 200)
|
|
102
|
+
}
|
|
103
|
+
} catch {
|
|
104
|
+
// arguments are free-form for some tools; classification still works.
|
|
105
|
+
}
|
|
106
|
+
return ''
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Extract the most target-like string argument (path/query/url) for read-mask records. */
|
|
110
|
+
export function extractTarget(argumentsText: string): string {
|
|
111
|
+
try {
|
|
112
|
+
const parsed: unknown = JSON.parse(argumentsText)
|
|
113
|
+
if (parsed !== null && typeof parsed === 'object') {
|
|
114
|
+
const record = parsed as Record<string, unknown>
|
|
115
|
+
const target = [record.path, record.file_path, record.query, record.url, record.pattern, record.glob]
|
|
116
|
+
.find(candidate => typeof candidate === 'string' && candidate.trim().length > 0)
|
|
117
|
+
if (typeof target === 'string') return target.slice(0, 160)
|
|
118
|
+
const first = Object.values(record).find(value => typeof value === 'string')
|
|
119
|
+
if (typeof first === 'string') return first.slice(0, 160)
|
|
120
|
+
}
|
|
121
|
+
} catch {
|
|
122
|
+
// free-form arguments degrade to an unlabeled mask record
|
|
123
|
+
}
|
|
124
|
+
return '(unparsed target)'
|
|
125
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Deterministic fold-range selection for the turn-tail intent summary
|
|
3
|
+
* (task_2.1). The host — never the model — decides WHAT gets folded: the
|
|
4
|
+
* consumed increment outside the protected working set, oldest-first
|
|
5
|
+
* (tail-biased folding keeps the cached request prefix byte-stable).
|
|
6
|
+
*/
|
|
7
|
+
import type { SnapshotCandidate } from '../../pruner/types.ts'
|
|
8
|
+
|
|
9
|
+
/** Per-batch cap: one pass never folds more than this many candidates. */
|
|
10
|
+
export const INTENT_RANGE_MAX_CANDIDATES = 20
|
|
11
|
+
|
|
12
|
+
export interface IntentRangeInput {
|
|
13
|
+
/** Pressure candidates already filtered to safe/eligible faces by the caller. */
|
|
14
|
+
readonly candidates: readonly SnapshotCandidate[]
|
|
15
|
+
/** Protected working-set seqs (never foldable). */
|
|
16
|
+
readonly protectedSeqs: ReadonlySet<number>
|
|
17
|
+
/** Already-folded seqs (fold-once: never reconsidered). */
|
|
18
|
+
readonly foldedSeqs: ReadonlySet<number>
|
|
19
|
+
/** Per-batch cap so one pass cannot fold unboundedly. */
|
|
20
|
+
readonly maxCandidates: number
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Oldest-first selection of foldable candidates. Excludes the protected
|
|
25
|
+
* working set and already-folded seqs; caps the batch size.
|
|
26
|
+
*/
|
|
27
|
+
export function computeIntentRange(
|
|
28
|
+
input: IntentRangeInput,
|
|
29
|
+
): { readonly seqs: number[], readonly skippedProtected: number, readonly skippedFolded: number } {
|
|
30
|
+
const unprotected = input.candidates.filter(candidate => !input.protectedSeqs.has(candidate.seq))
|
|
31
|
+
const skippedProtected = input.candidates.length - unprotected.length
|
|
32
|
+
const eligible = unprotected.filter(candidate => !input.foldedSeqs.has(candidate.seq))
|
|
33
|
+
const skippedFolded = unprotected.length - eligible.length
|
|
34
|
+
// Oldest-first: seq ascending == oldest first in the append-only log.
|
|
35
|
+
const ordered = [...eligible].sort((a, b) => a.seq - b.seq)
|
|
36
|
+
return { seqs: ordered.slice(0, Math.max(0, input.maxCandidates)).map(candidate => candidate.seq), skippedProtected, skippedFolded }
|
|
37
|
+
}
|
|
@@ -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,303 @@
|
|
|
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
|
+
/**
|
|
53
|
+
* @param overrides - per-consumer overrides of the estimator-named options.
|
|
54
|
+
* The estimator itself never passes them (byte-identical behavior); the
|
|
55
|
+
* advisory advisor passes its own mode/timeout/output budget so both
|
|
56
|
+
* consumers share one transport without sharing one configuration.
|
|
57
|
+
*/
|
|
58
|
+
constructor(
|
|
59
|
+
private readonly ctx: Context,
|
|
60
|
+
private readonly options: PresetOptionsSettings,
|
|
61
|
+
private readonly overrides?: {
|
|
62
|
+
readonly mode?: '' | 'host' | 'direct'
|
|
63
|
+
readonly timeoutMs?: number
|
|
64
|
+
readonly maxTokens?: number
|
|
65
|
+
},
|
|
66
|
+
) {}
|
|
67
|
+
|
|
68
|
+
private get mode(): '' | 'host' | 'direct' {
|
|
69
|
+
return this.overrides?.mode ?? this.options.estimatorMode ?? ''
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
get enabled(): boolean {
|
|
73
|
+
return this.mode === 'host' || this.mode === 'direct'
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async ask(request: SideChannelRequest): Promise<string | undefined> {
|
|
77
|
+
const timeoutMs = this.overrides?.timeoutMs ?? this.options.estimatorTimeoutMs ?? 3_000
|
|
78
|
+
const timeout = AbortSignal.timeout(timeoutMs)
|
|
79
|
+
const signal = typeof AbortSignal.any === 'function' ? AbortSignal.any([request.signal, timeout]) : timeout
|
|
80
|
+
try {
|
|
81
|
+
if (this.mode === 'host') return await this.askHost(request.system, request.user, signal)
|
|
82
|
+
if (this.mode === 'direct') return await this.askDirect(request.system, request.user, signal)
|
|
83
|
+
return undefined
|
|
84
|
+
} catch {
|
|
85
|
+
return undefined
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Failure-open wrapper that also records one audit record per call. */
|
|
90
|
+
async askAudited(request: SideChannelRequest): Promise<{ text?: string, audit: SideChannelAudit }> {
|
|
91
|
+
const now = Date.now()
|
|
92
|
+
const text = await this.ask(request)
|
|
93
|
+
const audit: SideChannelAudit = {
|
|
94
|
+
ok: text !== undefined,
|
|
95
|
+
latencyMs: Date.now() - now,
|
|
96
|
+
...this.identity() !== undefined ? { channel: this.identity()! } : {},
|
|
97
|
+
...(text === undefined ? { reason: 'channel returned no content (timeout, non-2xx, parse failure, or reasoning ate the output-token budget)' } : {}),
|
|
98
|
+
}
|
|
99
|
+
return { ...(text === undefined ? {} : { text }), audit }
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
identity(): string | undefined {
|
|
103
|
+
if (this.mode === 'direct') {
|
|
104
|
+
return `direct:${this.options.estimatorModel ?? ''}`
|
|
105
|
+
}
|
|
106
|
+
if (this.mode === 'host') {
|
|
107
|
+
const route = this.resolveHostRoute()
|
|
108
|
+
return route === undefined ? 'host' : `host:${route.provider}/${route.model}`
|
|
109
|
+
}
|
|
110
|
+
return undefined
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Same host-route resolution as the estimator: explicit, then host default. */
|
|
114
|
+
private resolveHostRoute(): { provider: string, model: string } | undefined {
|
|
115
|
+
const provider = this.options.estimatorProvider ?? ''
|
|
116
|
+
const model = this.options.estimatorModel ?? ''
|
|
117
|
+
if (provider.length > 0 && model.length > 0) return { provider, model }
|
|
118
|
+
try {
|
|
119
|
+
const defaults = this.ctx.get('agentDefaultModel' as never) as
|
|
120
|
+
| { currentSelection?: () => { provider?: string, model?: string } | undefined }
|
|
121
|
+
| undefined
|
|
122
|
+
const selected = defaults?.currentSelection?.()
|
|
123
|
+
const selectedProvider = selected?.provider ?? ''
|
|
124
|
+
const selectedModel = selected?.model ?? ''
|
|
125
|
+
if (selectedProvider.length > 0 && selectedModel.length > 0) {
|
|
126
|
+
return {
|
|
127
|
+
provider: provider.length > 0 ? provider : selectedProvider,
|
|
128
|
+
model: model.length > 0 ? model : selectedModel,
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
} catch {
|
|
132
|
+
// optional service; absence must not throw
|
|
133
|
+
}
|
|
134
|
+
return undefined
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
private async askHost(system: string, user: string, signal: AbortSignal): Promise<string | undefined> {
|
|
138
|
+
let llm: HostLlmLike | undefined
|
|
139
|
+
try {
|
|
140
|
+
llm = this.ctx.get('llm' as never) as HostLlmLike | undefined
|
|
141
|
+
} catch {
|
|
142
|
+
return undefined
|
|
143
|
+
}
|
|
144
|
+
if (llm?.stream === undefined) return undefined
|
|
145
|
+
const route = this.resolveHostRoute()
|
|
146
|
+
if (route === undefined) return undefined
|
|
147
|
+
let text = ''
|
|
148
|
+
const stream = llm.stream({
|
|
149
|
+
provider: route.provider,
|
|
150
|
+
model: route.model,
|
|
151
|
+
messages: [{ role: 'user', content: [{ type: 'text', text: user }] }],
|
|
152
|
+
system,
|
|
153
|
+
temperature: 0,
|
|
154
|
+
reasoningEffort: 'off',
|
|
155
|
+
maxTokens: this.overrides?.maxTokens ?? 256,
|
|
156
|
+
signal,
|
|
157
|
+
})
|
|
158
|
+
for await (const chunk of stream) {
|
|
159
|
+
// reasoningEffort 'off' is a request, not a guarantee: if reasoning still
|
|
160
|
+
// eats the 256-token budget, `content` stays empty and the caller falls
|
|
161
|
+
// back to the mechanical fold (text.trim() check below).
|
|
162
|
+
if (chunk.type === 'text-delta' && typeof chunk.text === 'string') {
|
|
163
|
+
text += chunk.text
|
|
164
|
+
} else if (chunk.type === 'finish' && chunk.text === undefined) {
|
|
165
|
+
break
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
return text.trim().length > 0 ? text : undefined
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
private async askDirect(system: string, user: string, signal: AbortSignal): Promise<string | undefined> {
|
|
172
|
+
const baseUrl = this.options.estimatorBaseUrl
|
|
173
|
+
if (baseUrl === undefined || baseUrl.length === 0) return undefined
|
|
174
|
+
const headers: Record<string, string> = { 'content-type': 'application/json' }
|
|
175
|
+
if (this.options.estimatorApiKey !== undefined && this.options.estimatorApiKey.length > 0) {
|
|
176
|
+
headers.authorization = `Bearer ${this.options.estimatorApiKey}`
|
|
177
|
+
}
|
|
178
|
+
const model = this.options.estimatorModel ?? ''
|
|
179
|
+
if (model.length === 0) return undefined
|
|
180
|
+
const response = await fetch(`${baseUrl.replace(/\/+$/, '')}/chat/completions`, {
|
|
181
|
+
method: 'POST',
|
|
182
|
+
headers,
|
|
183
|
+
body: JSON.stringify({
|
|
184
|
+
model,
|
|
185
|
+
messages: [
|
|
186
|
+
{ role: 'system', content: system },
|
|
187
|
+
{ role: 'user', content: user },
|
|
188
|
+
],
|
|
189
|
+
temperature: 0,
|
|
190
|
+
max_tokens: this.overrides?.maxTokens ?? 256,
|
|
191
|
+
}),
|
|
192
|
+
signal,
|
|
193
|
+
})
|
|
194
|
+
if (!response.ok) return undefined
|
|
195
|
+
const payload = (await response.json()) as {
|
|
196
|
+
choices?: { message?: { content?: string } }[]
|
|
197
|
+
}
|
|
198
|
+
const text = payload.choices?.[0]?.message?.content
|
|
199
|
+
return typeof text === 'string' && text.trim().length > 0 ? text : undefined
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* Rank-then-cut (TS4): ONE call sorts and filters. The prompt carries the
|
|
205
|
+
* query, the main LLM's reasoning summary (the intent lives there — AD11),
|
|
206
|
+
* and per-node summaries with identifier + count + ONE content sample.
|
|
207
|
+
*/
|
|
208
|
+
export function buildRankSystemPrompt(kind: 'search' | 'document'): string {
|
|
209
|
+
const what = kind === 'search' ? 'files' : 'document sections'
|
|
210
|
+
return [
|
|
211
|
+
'You rank session artifacts by relevance to an agent query.',
|
|
212
|
+
`You are given numbered ${what} with a short sample each.`,
|
|
213
|
+
`Answer with ONLY the identifiers of the ${what} that matter, most relevant first,`,
|
|
214
|
+
'as a comma-separated list. Omit identifiers you consider irrelevant.',
|
|
215
|
+
'Never invent identifiers; never add commentary.',
|
|
216
|
+
].join(' ')
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
export function parseRanking(text: string | undefined, validIds: ReadonlySet<string>): string[] | undefined {
|
|
220
|
+
if (text === undefined || text.trim().length === 0) return undefined
|
|
221
|
+
const ranked: string[] = []
|
|
222
|
+
const seen = new Set<string>()
|
|
223
|
+
for (const token of text.split(/[\s,;]+/)) {
|
|
224
|
+
const id = token.replace(/[^\w./:#-]/gu, '')
|
|
225
|
+
if (id.length === 0 || !validIds.has(id) || seen.has(id)) continue
|
|
226
|
+
seen.add(id)
|
|
227
|
+
ranked.push(id)
|
|
228
|
+
}
|
|
229
|
+
return ranked.length > 0 ? ranked : undefined
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** Nodes mentioned by the LM keep their rank; the rest are appended in order (SC-existence). */
|
|
233
|
+
export function mergeRanking<T extends { readonly id: string }>(nodes: readonly T[], ranking: readonly string[] | undefined): readonly T[] {
|
|
234
|
+
if (ranking === undefined) return nodes
|
|
235
|
+
const byId = new Map(nodes.map(node => [node.id, node]))
|
|
236
|
+
const ordered: T[] = []
|
|
237
|
+
for (const id of ranking) {
|
|
238
|
+
const node = byId.get(id)
|
|
239
|
+
if (node !== undefined) ordered.push(node)
|
|
240
|
+
}
|
|
241
|
+
for (const node of nodes) {
|
|
242
|
+
if (!ordered.includes(node)) ordered.push(node)
|
|
243
|
+
}
|
|
244
|
+
return ordered
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** Cost gate (R-10): call only when something must be dropped and there is more than one node. */
|
|
248
|
+
export function sideChannelGate(fitsBudget: boolean, nodeCount: number): boolean {
|
|
249
|
+
return !fitsBudget && nodeCount > 1
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** One node face offered to the rank prompt: id + count/mass + ONE content sample. */
|
|
253
|
+
export interface RankedNode { readonly id: string, readonly detail: string, readonly sample: string }
|
|
254
|
+
|
|
255
|
+
export function buildRankUserPrompt(
|
|
256
|
+
nodes: readonly RankedNode[],
|
|
257
|
+
query: string,
|
|
258
|
+
reasoningSummary: string | undefined,
|
|
259
|
+
): string {
|
|
260
|
+
const lines = [
|
|
261
|
+
...(query.trim().length > 0 ? [`query: ${query.trim().slice(0, 300)}`] : []),
|
|
262
|
+
...(reasoningSummary !== undefined && reasoningSummary.trim().length > 0
|
|
263
|
+
? [`reasoning: ${reasoningSummary.trim().slice(0, 300)}`] : []),
|
|
264
|
+
...nodes.map(node => `${node.id} | ${node.detail} | ${node.sample.replace(/\s+/gu, ' ')}`),
|
|
265
|
+
]
|
|
266
|
+
return lines.join('\n')
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
export interface RankOutcome {
|
|
270
|
+
/** Ranked ids the LM returned; `undefined` on any failure (fail-open). */
|
|
271
|
+
readonly ranking?: readonly string[]
|
|
272
|
+
readonly audit: SideChannelAudit
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* S1 orchestrator: gate → ONE channel call → parse → merge. Every failure
|
|
277
|
+
* path (gate closed, channel undefined, garbage answer) resolves with
|
|
278
|
+
* `ranking: undefined`, which the mechanical fold reproduces byte-for-byte.
|
|
279
|
+
*/
|
|
280
|
+
export async function rankNodes(
|
|
281
|
+
nodes: readonly RankedNode[],
|
|
282
|
+
validIds: ReadonlySet<string>,
|
|
283
|
+
query: string,
|
|
284
|
+
reasoningSummary: string | undefined,
|
|
285
|
+
channel: Pick<SideChannel, 'ask' | 'askAudited' | 'identity'>,
|
|
286
|
+
signal: AbortSignal,
|
|
287
|
+
): Promise<RankOutcome> {
|
|
288
|
+
if (nodes.length <= 1 || query.trim().length === 0) {
|
|
289
|
+
return { audit: { ok: false, latencyMs: 0, reason: 'gate closed: single node or empty query' } }
|
|
290
|
+
}
|
|
291
|
+
const { text, audit } = await channel.askAudited({
|
|
292
|
+
system: buildRankSystemPrompt('search'),
|
|
293
|
+
user: buildRankUserPrompt(nodes, query, reasoningSummary),
|
|
294
|
+
signal,
|
|
295
|
+
})
|
|
296
|
+
const ranking = parseRanking(text, validIds)
|
|
297
|
+
return {
|
|
298
|
+
...(ranking === undefined ? {} : { ranking }),
|
|
299
|
+
audit: ranking === undefined
|
|
300
|
+
? { ...audit, ok: false, reason: 'unparseable or empty ranking; falling back to the mechanical fold' }
|
|
301
|
+
: audit,
|
|
302
|
+
}
|
|
303
|
+
}
|