dsh-context-compression-improved 0.9.7 → 0.9.8

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.
Files changed (126) hide show
  1. package/.gitattributes +2 -2
  2. package/.githooks/pre-push +37 -37
  3. package/CHANGELOG.md +4 -0
  4. package/CONTRIBUTING.md +22 -22
  5. package/LICENSE +21 -21
  6. package/README.de.md +3 -3
  7. package/README.es.md +3 -3
  8. package/README.fr.md +3 -3
  9. package/README.it.md +3 -3
  10. package/README.ja.md +3 -3
  11. package/README.ko.md +3 -3
  12. package/README.md +3 -3
  13. package/README.ru.md +3 -3
  14. package/README.zh.md +3 -3
  15. package/SECURITY.md +18 -18
  16. package/THIRD_PARTY_NOTICES.md +14 -14
  17. package/docs/compat-0.1.5-report.md +77 -77
  18. package/docs/installation.de.md +2 -2
  19. package/docs/installation.es.md +2 -2
  20. package/docs/installation.fr.md +2 -2
  21. package/docs/installation.it.md +2 -2
  22. package/docs/installation.ja.md +2 -2
  23. package/docs/installation.ko.md +2 -2
  24. package/docs/installation.md +2 -2
  25. package/docs/installation.ru.md +2 -2
  26. package/docs/installation.zh.md +2 -2
  27. package/docs/repair-log.md +657 -657
  28. package/package.json +6 -6
  29. package/packages/selector/LICENSE +21 -21
  30. package/packages/selector/README.md +26 -26
  31. package/packages/selector/README.zh.md +24 -24
  32. package/packages/selector/THIRD_PARTY_NOTICES.md +32 -32
  33. package/packages/selector/cordis.patch.yml +27 -27
  34. package/packages/selector/docs/history-tool-call-working-set-spec.md +112 -112
  35. package/packages/selector/docs/native-tool-result-selector-spec.md +34 -34
  36. package/packages/selector/docs/subagent-cache-reuse-spec.md +46 -46
  37. package/packages/selector/dsh.plugin.json +2 -2
  38. package/packages/selector/lib/style.css +53 -53
  39. package/packages/selector/package.json +21 -21
  40. package/packages/selector/screenshots.json +3 -3
  41. package/packages/selector/src/client/CustomPolicyEditor.tsx +216 -216
  42. package/packages/selector/src/client/EstimatorControls.tsx +277 -277
  43. package/packages/selector/src/client/preset-options.ts +88 -88
  44. package/packages/selector/src/client/scope-face.ts +24 -24
  45. package/packages/selector/src/css-modules.d.ts +6 -6
  46. package/packages/selector/src/estimator-catalog.ts +104 -104
  47. package/packages/selector/src/invariant.ts +113 -113
  48. package/packages/selector/src/pruner/tuning.ts +23 -23
  49. package/packages/selector/src/pruner/types.ts +78 -78
  50. package/packages/selector/src/runtime/adaptive-cost.ts +205 -205
  51. package/packages/selector/src/runtime/audit.ts +303 -303
  52. package/packages/selector/src/runtime/custom-policy.ts +278 -278
  53. package/packages/selector/src/runtime/deepseek-official-pricing.ts +298 -298
  54. package/packages/selector/src/runtime/deepseek-v4-vision-tokens.ts +254 -254
  55. package/packages/selector/src/runtime/session-events.ts +30 -30
  56. package/packages/selector/src/runtime/token-count.ts +72 -72
  57. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -233
  58. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -204
  59. package/packages/selector/src/runtime/tokenpilot/advisor.ts +419 -419
  60. package/packages/selector/src/runtime/tokenpilot/benefit.ts +200 -200
  61. package/packages/selector/src/runtime/tokenpilot/dedup.ts +81 -81
  62. package/packages/selector/src/runtime/tokenpilot/estimator.ts +151 -151
  63. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -53
  64. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -65
  65. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -125
  66. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -37
  67. package/packages/selector/src/runtime/tokenpilot/read-state.ts +98 -98
  68. package/packages/selector/src/runtime/toolclass.ts +103 -103
  69. package/packages/selector/src/runtime/value.ts +48 -48
  70. package/packages/selector/tests/advisor-report.host.spec.ts +223 -223
  71. package/packages/selector/tests/cache-prefix-audit.spec.ts +123 -123
  72. package/packages/selector/tests/estimator-catalog.spec.ts +70 -70
  73. package/packages/selector/tests/helpers/legacy-namespace.ts +35 -35
  74. package/packages/selector/tests/helpers/legacy-settings/index.ts +15 -15
  75. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.d.ts +41 -41
  76. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.js +647 -647
  77. package/packages/selector/tests/helpers/legacy-settings/legacy/redact.js +78 -78
  78. package/packages/selector/tests/helpers/legacy-settings/legacy/util-values.js +234 -234
  79. package/packages/selector/tests/preset-overlay.host.spec.ts +246 -246
  80. package/packages/selector/tests/public/package-contract.client.spec.ts +4 -4
  81. package/packages/selector/tests/runtime/adaptive-cost.spec.ts +167 -167
  82. package/packages/selector/tests/runtime/advisor-invariant.spec.ts +272 -272
  83. package/packages/selector/tests/runtime/advisor.spec.ts +226 -226
  84. package/packages/selector/tests/runtime/char-basis.spec.ts +30 -30
  85. package/packages/selector/tests/runtime/code-skeleton.spec.ts +152 -152
  86. package/packages/selector/tests/runtime/deepseek-official-pricing.spec.ts +186 -186
  87. package/packages/selector/tests/runtime/deepseek-v4-vision-tokens.spec.ts +122 -122
  88. package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +96 -96
  89. package/packages/selector/tests/runtime/fixtures/profile-baseline.json +273 -273
  90. package/packages/selector/tests/runtime/fixtures/tokenizer-golden.json +106 -106
  91. package/packages/selector/tests/runtime/fixtures/vision-golden.json +459 -459
  92. package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +74 -74
  93. package/packages/selector/tests/runtime/html-reducer.spec.ts +212 -212
  94. package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -62
  95. package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -156
  96. package/packages/selector/tests/runtime/line-mapping.spec.ts +153 -153
  97. package/packages/selector/tests/runtime/prose-reducers.spec.ts +133 -133
  98. package/packages/selector/tests/runtime/read-input-cap.spec.ts +33 -33
  99. package/packages/selector/tests/runtime/search-reducer.spec.ts +110 -110
  100. package/packages/selector/tests/runtime/session-events.spec.ts +27 -27
  101. package/packages/selector/tests/runtime/sidechannel.spec.ts +241 -241
  102. package/packages/selector/tests/runtime/summary-command.spec.ts +154 -154
  103. package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +159 -159
  104. package/packages/selector/tests/runtime/tokenizer-golden.spec.ts +53 -53
  105. package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +217 -217
  106. package/packages/selector/tests/runtime/tokenpilot/dedup.spec.ts +52 -52
  107. package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +79 -79
  108. package/packages/selector/tests/runtime/tokenpilot/locator.spec.ts +76 -76
  109. package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +82 -82
  110. package/packages/selector/tests/runtime/toolclass.spec.ts +156 -156
  111. package/packages/selector/tests/runtime/value.spec.ts +23 -23
  112. package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +269 -269
  113. package/packages/selector/tests/support/cache-prefix-audit.ts +105 -105
  114. package/packages/selector/tests/support/mock-adapter.ts +37 -37
  115. package/packages/selector/tests/support/ui-primitives.tsx +34 -34
  116. package/packages/selector/tsconfig.json +11 -11
  117. package/packages/selector/tsdown.client.config.ts +102 -102
  118. package/packages/selector/tsdown.config.ts +20 -20
  119. package/scripts/capture-profile-baseline.mjs +42 -42
  120. package/scripts/generate-tokenizer-fixtures.py +81 -81
  121. package/scripts/generate-vision-fixtures.py +208 -208
  122. package/scripts/hosts.mjs +2 -1
  123. package/scripts/toolclass-corpus-replay.mjs +281 -281
  124. package/tsconfig.base.json +18 -18
  125. package/tsconfig.json +7 -7
  126. package/vitest.built.config.ts +9 -9
@@ -1,125 +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
- }
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
+ }
@@ -1,37 +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
- }
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
+ }
@@ -1,98 +1,98 @@
1
- /**
2
- * TokenPilot-inspired R2/R3: read-state semantics and clustered omission
3
- * markers.
4
- *
5
- * A read result is `superseded` when a later write-style tool call mutated the
6
- * same file: its full text can no longer match the file the model would read
7
- * again, so aggressive aging is safe. Superseded reads may compress to a small
8
- * aggregate placeholder instead of the ordinary historical placeholder.
9
- */
10
- import type { SessionEvent } from '@deepseek-ai/dsh-session'
11
- import { looksLikeDocument } from '../reducers.ts'
12
-
13
- /** Write-style tool names whose success supersedes earlier reads. */
14
- const WRITE_TOOLS = /(?:^|[-_])?(?:write|edit|apply_patch|file_write|file_edit|str_replace|replace|multiedit)(?:$|[-_])/i
15
- const PATH_KEYS = ['path', 'file_path'] as const
16
-
17
- /** Parse one path out of a tool-call arguments JSON blob. */
18
- export function toolCallPath(argumentsText: string): string | undefined {
19
- let parsed: unknown
20
- try {
21
- parsed = JSON.parse(argumentsText)
22
- } catch {
23
- return undefined
24
- }
25
- if (typeof parsed !== 'object' || parsed === null) return undefined
26
- const record = parsed as Record<string, unknown>
27
- for (const key of PATH_KEYS) {
28
- const value = record[key]
29
- if (typeof value === 'string' && value.length > 0) return value
30
- }
31
- return undefined
32
- }
33
-
34
- /**
35
- * Decide whether an oversized read result was superseded by a later mutation
36
- * of the same file. `readPath` is the read call's target path; events after
37
- * `readSeq` are scanned for a write-style call on it.
38
- */
39
- export function isSupersededRead(
40
- events: readonly SessionEvent[],
41
- readSeq: number,
42
- readPath: string | undefined,
43
- ): boolean {
44
- if (readPath === undefined) return false
45
- for (let seq = readSeq + 1; seq < events.length; seq += 1) {
46
- const event = events[seq]
47
- if (event?.type !== 'tool/call') continue
48
- if (!WRITE_TOOLS.test(event.data.name)) continue
49
- if (toolCallPath(event.data.arguments) === readPath) return true
50
- }
51
- return false
52
- }
53
-
54
- /** Error/warning/info line classifiers used by the omission summary. */
55
- const ERROR_LINE = /\b(error|failed|failure|fatal|exception|traceback|cannot|unable|denied)\b/i
56
- const WARN_LINE = /\b(warn|warning|deprecated)\b/i
57
- const SECTION_HEADING = /^#{1,3}\s+(.{1,80})/
58
-
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.
65
- */
66
- export function clusterOmittedLines(text: string, omittedLines: number): string | undefined {
67
- if (omittedLines <= 0) return undefined
68
- if (looksLikeDocument(text)) return documentCensus(text, omittedLines)
69
- let errors = 0
70
- let warns = 0
71
- let infos = 0
72
- for (const line of text.split('\n')) {
73
- if (ERROR_LINE.test(line)) errors += 1
74
- else if (WARN_LINE.test(line)) warns += 1
75
- else infos += 1
76
- }
77
- const parts: string[] = []
78
- if (errors > 0) parts.push(`${String(errors)} error`)
79
- if (warns > 0) parts.push(`${String(warns)} warn`)
80
- if (infos > 0) parts.push(`${String(infos)} info`)
81
- if (parts.length === 0) return undefined
82
- return `${String(omittedLines)} lines omitted (${parts.join(', ')})`
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
- }
1
+ /**
2
+ * TokenPilot-inspired R2/R3: read-state semantics and clustered omission
3
+ * markers.
4
+ *
5
+ * A read result is `superseded` when a later write-style tool call mutated the
6
+ * same file: its full text can no longer match the file the model would read
7
+ * again, so aggressive aging is safe. Superseded reads may compress to a small
8
+ * aggregate placeholder instead of the ordinary historical placeholder.
9
+ */
10
+ import type { SessionEvent } from '@deepseek-ai/dsh-session'
11
+ import { looksLikeDocument } from '../reducers.ts'
12
+
13
+ /** Write-style tool names whose success supersedes earlier reads. */
14
+ const WRITE_TOOLS = /(?:^|[-_])?(?:write|edit|apply_patch|file_write|file_edit|str_replace|replace|multiedit)(?:$|[-_])/i
15
+ const PATH_KEYS = ['path', 'file_path'] as const
16
+
17
+ /** Parse one path out of a tool-call arguments JSON blob. */
18
+ export function toolCallPath(argumentsText: string): string | undefined {
19
+ let parsed: unknown
20
+ try {
21
+ parsed = JSON.parse(argumentsText)
22
+ } catch {
23
+ return undefined
24
+ }
25
+ if (typeof parsed !== 'object' || parsed === null) return undefined
26
+ const record = parsed as Record<string, unknown>
27
+ for (const key of PATH_KEYS) {
28
+ const value = record[key]
29
+ if (typeof value === 'string' && value.length > 0) return value
30
+ }
31
+ return undefined
32
+ }
33
+
34
+ /**
35
+ * Decide whether an oversized read result was superseded by a later mutation
36
+ * of the same file. `readPath` is the read call's target path; events after
37
+ * `readSeq` are scanned for a write-style call on it.
38
+ */
39
+ export function isSupersededRead(
40
+ events: readonly SessionEvent[],
41
+ readSeq: number,
42
+ readPath: string | undefined,
43
+ ): boolean {
44
+ if (readPath === undefined) return false
45
+ for (let seq = readSeq + 1; seq < events.length; seq += 1) {
46
+ const event = events[seq]
47
+ if (event?.type !== 'tool/call') continue
48
+ if (!WRITE_TOOLS.test(event.data.name)) continue
49
+ if (toolCallPath(event.data.arguments) === readPath) return true
50
+ }
51
+ return false
52
+ }
53
+
54
+ /** Error/warning/info line classifiers used by the omission summary. */
55
+ const ERROR_LINE = /\b(error|failed|failure|fatal|exception|traceback|cannot|unable|denied)\b/i
56
+ const WARN_LINE = /\b(warn|warning|deprecated)\b/i
57
+ const SECTION_HEADING = /^#{1,3}\s+(.{1,80})/
58
+
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.
65
+ */
66
+ export function clusterOmittedLines(text: string, omittedLines: number): string | undefined {
67
+ if (omittedLines <= 0) return undefined
68
+ if (looksLikeDocument(text)) return documentCensus(text, omittedLines)
69
+ let errors = 0
70
+ let warns = 0
71
+ let infos = 0
72
+ for (const line of text.split('\n')) {
73
+ if (ERROR_LINE.test(line)) errors += 1
74
+ else if (WARN_LINE.test(line)) warns += 1
75
+ else infos += 1
76
+ }
77
+ const parts: string[] = []
78
+ if (errors > 0) parts.push(`${String(errors)} error`)
79
+ if (warns > 0) parts.push(`${String(warns)} warn`)
80
+ if (infos > 0) parts.push(`${String(infos)} info`)
81
+ if (parts.length === 0) return undefined
82
+ return `${String(omittedLines)} lines omitted (${parts.join(', ')})`
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
+ }