@leing2021/super-pi 0.15.0 → 0.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -14,6 +14,8 @@ import { createPlanDiffTool } from "./tools/plan-diff"
|
|
|
14
14
|
import { createSessionHistoryTool } from "./tools/session-history"
|
|
15
15
|
import { createPatternExtractorTool } from "./tools/pattern-extractor"
|
|
16
16
|
import { filterBashOutput } from "./tools/bash-output-filter"
|
|
17
|
+
import { filterReadOutput } from "./tools/read-output-filter"
|
|
18
|
+
import { COMPACTION_FOCUS_INSTRUCTIONS } from "./tools/compaction-optimizer"
|
|
17
19
|
|
|
18
20
|
const artifactHelperParams = Type.Object({
|
|
19
21
|
repoRoot: Type.String({ description: "Repository root where workflow artifacts should be created" }),
|
|
@@ -543,6 +545,50 @@ export default function ceCoreExtension(pi: ExtensionAPI) {
|
|
|
543
545
|
},
|
|
544
546
|
}
|
|
545
547
|
})
|
|
548
|
+
|
|
549
|
+
// Read output smart filter — reduces context waste from large file reads
|
|
550
|
+
pi.on("tool_result", async (event, _ctx) => {
|
|
551
|
+
if (event.toolName !== "read") return undefined
|
|
552
|
+
|
|
553
|
+
// Extract path from input
|
|
554
|
+
const path = (event.input as any)?.path ?? ""
|
|
555
|
+
if (!path) return undefined
|
|
556
|
+
|
|
557
|
+
// Extract text content from tool result
|
|
558
|
+
const textBlocks = (event.content as Array<any>)?.filter((b: any) => b.type === "text") ?? []
|
|
559
|
+
if (textBlocks.length === 0) return undefined
|
|
560
|
+
|
|
561
|
+
const output = textBlocks.map((b: any) => b.text).join("")
|
|
562
|
+
const isImage = (event.content as Array<any>)?.some((b: any) => b.type === "image") ?? false
|
|
563
|
+
|
|
564
|
+
const result = filterReadOutput({
|
|
565
|
+
path,
|
|
566
|
+
output,
|
|
567
|
+
isError: event.isError ?? false,
|
|
568
|
+
isImage,
|
|
569
|
+
})
|
|
570
|
+
|
|
571
|
+
if (!result.filtered) return undefined
|
|
572
|
+
|
|
573
|
+
return {
|
|
574
|
+
content: [{ type: "text", text: result.output }],
|
|
575
|
+
details: {
|
|
576
|
+
...event.details,
|
|
577
|
+
readFilter: {
|
|
578
|
+
strategy: result.strategy,
|
|
579
|
+
originalBytes: result.originalBytes,
|
|
580
|
+
filteredBytes: result.filteredBytes,
|
|
581
|
+
},
|
|
582
|
+
},
|
|
583
|
+
}
|
|
584
|
+
})
|
|
585
|
+
|
|
586
|
+
// Compaction prompt optimizer — makes summaries more focused and useful
|
|
587
|
+
pi.on("session_before_compact", async (_event, _ctx) => {
|
|
588
|
+
return {
|
|
589
|
+
customInstructions: COMPACTION_FOCUS_INSTRUCTIONS,
|
|
590
|
+
}
|
|
591
|
+
})
|
|
546
592
|
}
|
|
547
593
|
|
|
548
594
|
|
|
@@ -567,3 +613,5 @@ export {
|
|
|
567
613
|
} from "./utils/artifact-paths"
|
|
568
614
|
export { normalizeSlug } from "./utils/name-utils"
|
|
569
615
|
export { filterBashOutput } from "./tools/bash-output-filter"
|
|
616
|
+
export { filterReadOutput } from "./tools/read-output-filter"
|
|
617
|
+
export { COMPACTION_FOCUS_INSTRUCTIONS, TURN_PREFIX_FOCUS_INSTRUCTIONS } from "./tools/compaction-optimizer"
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
// ============================================================================
|
|
2
|
+
// Compaction Prompt Optimizer
|
|
3
|
+
// ============================================================================
|
|
4
|
+
//
|
|
5
|
+
// Hooks into `session_before_compact` to inject custom instructions that make
|
|
6
|
+
// compaction summaries more focused and useful for coding agent context.
|
|
7
|
+
//
|
|
8
|
+
// This is a "prompt-only" optimization — it doesn't replace pi's compaction
|
|
9
|
+
// flow, just adds focus instructions to the summarization prompt.
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Custom instructions appended to compaction summarization prompts.
|
|
13
|
+
*
|
|
14
|
+
* Goals:
|
|
15
|
+
* 1. Preserve exact technical identifiers (paths, names, error messages)
|
|
16
|
+
* 2. Be terse on reasoning process, verbose on concrete state changes
|
|
17
|
+
* 3. Summarize file reads by purpose rather than including code snippets
|
|
18
|
+
* 4. Keep Critical Context section detailed for continuation
|
|
19
|
+
*/
|
|
20
|
+
export const COMPACTION_FOCUS_INSTRUCTIONS = `Additional focus for this summary:
|
|
21
|
+
|
|
22
|
+
1. Preserve EXACT file paths, function names, class names, variable names, and error messages — never paraphrase these
|
|
23
|
+
2. For each code change, note: file path, function/class, what changed, and why
|
|
24
|
+
3. Summarize file reads by their purpose (e.g., "read auth.ts to understand JWT middleware flow") rather than including code snippets
|
|
25
|
+
4. Be concise on the agent's reasoning process; be verbose on concrete state changes and decisions
|
|
26
|
+
5. Keep the "Critical Context" section detailed — this is what the agent needs to continue working
|
|
27
|
+
6. If any tests were run, summarize results by: file, pass/fail count, and specific failure messages
|
|
28
|
+
7. Note any blocked items and their exact error state`
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Additional instructions for turn-prefix summaries (split turns).
|
|
32
|
+
* These are more concise since the turn suffix is retained.
|
|
33
|
+
*/
|
|
34
|
+
export const TURN_PREFIX_FOCUS_INSTRUCTIONS = `Focus the turn-prefix summary on:
|
|
35
|
+
- What the user originally asked for
|
|
36
|
+
- Key decisions made in the prefix
|
|
37
|
+
- Exact file paths and identifiers needed to understand the retained suffix
|
|
38
|
+
Skip reasoning details — only keep actionable context.`
|
|
@@ -0,0 +1,506 @@
|
|
|
1
|
+
// ============================================================================
|
|
2
|
+
// Read Output Filter
|
|
3
|
+
// ============================================================================
|
|
4
|
+
//
|
|
5
|
+
// Filters `read` tool output at the source (via tool_result hook) to reduce
|
|
6
|
+
// context waste from large file reads. Symmetric with bash-output-filter.ts.
|
|
7
|
+
//
|
|
8
|
+
// Strategies:
|
|
9
|
+
// 1. Lock / generated files → extreme compression (summary only)
|
|
10
|
+
// 2. package.json → keep scripts + dep summary, drop full version lists
|
|
11
|
+
// 3. Large code files → keep signatures/structure, collapse bodies
|
|
12
|
+
// 4. Large markdown → keep headings + first paragraph per section
|
|
13
|
+
// 5. Generic → head/tail truncation for very large files
|
|
14
|
+
|
|
15
|
+
// ============================================================================
|
|
16
|
+
// Types
|
|
17
|
+
// ============================================================================
|
|
18
|
+
|
|
19
|
+
export interface ReadOutputFilterInput {
|
|
20
|
+
/** File path that was read */
|
|
21
|
+
path: string
|
|
22
|
+
/** The raw output text */
|
|
23
|
+
output: string
|
|
24
|
+
/** Whether the read resulted in an error */
|
|
25
|
+
isError?: boolean
|
|
26
|
+
/** Whether the file is an image (skip filtering) */
|
|
27
|
+
isImage?: boolean
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface ReadOutputFilterResult {
|
|
31
|
+
/** Filtered output text */
|
|
32
|
+
output: string
|
|
33
|
+
/** Whether filtering was applied */
|
|
34
|
+
filtered: boolean
|
|
35
|
+
/** Original size in bytes */
|
|
36
|
+
originalBytes: number
|
|
37
|
+
/** Filtered size in bytes */
|
|
38
|
+
filteredBytes: number
|
|
39
|
+
/** The filter strategy that was applied */
|
|
40
|
+
strategy: string
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// ============================================================================
|
|
44
|
+
// File Classification
|
|
45
|
+
// ============================================================================
|
|
46
|
+
|
|
47
|
+
type FileCategory =
|
|
48
|
+
| "lock-file"
|
|
49
|
+
| "generated-file"
|
|
50
|
+
| "minified-file"
|
|
51
|
+
| "package-json"
|
|
52
|
+
| "code"
|
|
53
|
+
| "markdown"
|
|
54
|
+
| "config"
|
|
55
|
+
| "unknown"
|
|
56
|
+
|
|
57
|
+
interface FilePattern {
|
|
58
|
+
test: (path: string) => boolean
|
|
59
|
+
category: FileCategory
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const FILE_PATTERNS: FilePattern[] = [
|
|
63
|
+
// Lock files — extreme compression
|
|
64
|
+
{ test: (p) => /(^|\/)(package-lock\.json|yarn\.lock|bun\.lock|pnpm-lock\.yaml|Gemfile\.lock|Podfile\.lock|composer\.lock|Cargo\.lock)$/.test(p), category: "lock-file" },
|
|
65
|
+
// Minified / bundle files
|
|
66
|
+
{ test: (p) => /\.(min\.js|min\.css|bundle\.js|chunk\.js|vendor\.js)$/i.test(p), category: "minified-file" },
|
|
67
|
+
// Generated files
|
|
68
|
+
{ test: (p) => /\.(generated\.\w+|auto\.\w+|pb\.ts)$/i.test(p) || /(?:^|\/)(generated|auto-generated|__generated__)\//i.test(p), category: "generated-file" },
|
|
69
|
+
// package.json — smart filter
|
|
70
|
+
{ test: (p) => /(^|\/)package\.json$/.test(p), category: "package-json" },
|
|
71
|
+
// Markdown
|
|
72
|
+
{ test: (p) => /\.(md|mdx)$/i.test(p), category: "markdown" },
|
|
73
|
+
// Config files (JSON/YAML/TOML without lock)
|
|
74
|
+
{ test: (p) => /\.(jsonc?|ya?ml|toml|ini|conf|rc)$/i.test(p) && !/lock/i.test(p), category: "config" },
|
|
75
|
+
// Code files
|
|
76
|
+
{ test: (p) => /\.(ts|tsx|js|jsx|py|rs|go|java|kt|rb|c|cpp|h|hpp|cs|swift|zig|scala|clj)$/i.test(p), category: "code" },
|
|
77
|
+
// Code files (alternate extensions)
|
|
78
|
+
{ test: (p) => /\.(vue|svelte|astro|sol|dart|lua|r|pl|pm|sh|bash|zsh|fish|ps1)$/i.test(p), category: "code" },
|
|
79
|
+
]
|
|
80
|
+
|
|
81
|
+
function classifyFile(path: string): FileCategory {
|
|
82
|
+
const normalized = path.replace(/\\/g, "/")
|
|
83
|
+
for (const pattern of FILE_PATTERNS) {
|
|
84
|
+
if (pattern.test(normalized)) return pattern.category
|
|
85
|
+
}
|
|
86
|
+
return "unknown"
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// ============================================================================
|
|
90
|
+
// Constants
|
|
91
|
+
// ============================================================================
|
|
92
|
+
|
|
93
|
+
/** Minimum output size (bytes) to trigger any filtering */
|
|
94
|
+
const MIN_FILTER_THRESHOLD = 2048 // 2KB
|
|
95
|
+
|
|
96
|
+
/** Maximum size for structural code compression trigger */
|
|
97
|
+
const CODE_COMPRESS_THRESHOLD = 8192 // 8KB
|
|
98
|
+
|
|
99
|
+
/** Maximum filtered output size (bytes) */
|
|
100
|
+
const MAX_FILTERED_SIZE = 30720 // 30KB
|
|
101
|
+
|
|
102
|
+
// ============================================================================
|
|
103
|
+
// Filter: Lock Files
|
|
104
|
+
// ============================================================================
|
|
105
|
+
|
|
106
|
+
function filterLockFile(output: string, path: string): string {
|
|
107
|
+
const bytes = Buffer.byteLength(output, "utf-8")
|
|
108
|
+
const lines = output.split("\n").length
|
|
109
|
+
|
|
110
|
+
// Try to extract name and lockfileVersion from JSON lock files
|
|
111
|
+
let summary = `Lock file: ${path.split("/").pop()}`
|
|
112
|
+
|
|
113
|
+
try {
|
|
114
|
+
const data = JSON.parse(output)
|
|
115
|
+
if (data.name) summary += `\nProject: ${data.name}`
|
|
116
|
+
if (data.lockfileVersion) summary += `\nLockfile version: ${data.lockfileVersion}`
|
|
117
|
+
if (data.packages) {
|
|
118
|
+
const pkgCount = Object.keys(data.packages).length
|
|
119
|
+
summary += `\nPackages: ${pkgCount}`
|
|
120
|
+
}
|
|
121
|
+
} catch {
|
|
122
|
+
// Not JSON (yarn.lock, etc.) — count lines
|
|
123
|
+
summary += `\nLines: ${lines}`
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
summary += `\nOriginal size: ${formatBytes(bytes)}`
|
|
127
|
+
return summary
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// ============================================================================
|
|
131
|
+
// Filter: Minified / Generated Files
|
|
132
|
+
// ============================================================================
|
|
133
|
+
|
|
134
|
+
function filterMinifiedFile(output: string, path: string): string {
|
|
135
|
+
const bytes = Buffer.byteLength(output, "utf-8")
|
|
136
|
+
const ext = path.split(".").pop() ?? ""
|
|
137
|
+
return [
|
|
138
|
+
`Minified ${ext} file: ${path.split("/").pop()}`,
|
|
139
|
+
`Size: ${formatBytes(bytes)} (${output.split("\n").length} lines)`,
|
|
140
|
+
`First 500 chars:`,
|
|
141
|
+
output.slice(0, 500),
|
|
142
|
+
"",
|
|
143
|
+
`[... ${formatBytes(bytes - 500)} omitted]`,
|
|
144
|
+
].join("\n")
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function filterGeneratedFile(output: string, path: string): string {
|
|
148
|
+
const bytes = Buffer.byteLength(output, "utf-8")
|
|
149
|
+
const lines = output.split("\n")
|
|
150
|
+
|
|
151
|
+
// Keep first 30 lines + last 10 lines + count
|
|
152
|
+
if (lines.length <= 50) return output
|
|
153
|
+
|
|
154
|
+
const head = lines.slice(0, 30)
|
|
155
|
+
const tail = lines.slice(-10)
|
|
156
|
+
const omitted = lines.length - 40
|
|
157
|
+
|
|
158
|
+
return [
|
|
159
|
+
...head,
|
|
160
|
+
"",
|
|
161
|
+
`[... ${omitted} lines omitted (generated file, ${formatBytes(bytes)})]`,
|
|
162
|
+
"",
|
|
163
|
+
...tail,
|
|
164
|
+
].join("\n")
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// ============================================================================
|
|
168
|
+
// Filter: package.json
|
|
169
|
+
// ============================================================================
|
|
170
|
+
|
|
171
|
+
function filterPackageJson(output: string): string {
|
|
172
|
+
try {
|
|
173
|
+
const pkg = JSON.parse(output)
|
|
174
|
+
const sections: string[] = []
|
|
175
|
+
|
|
176
|
+
sections.push(`Name: ${pkg.name ?? "unknown"}`)
|
|
177
|
+
if (pkg.version) sections.push(`Version: ${pkg.version}`)
|
|
178
|
+
if (pkg.description) sections.push(`Description: ${pkg.description}`)
|
|
179
|
+
|
|
180
|
+
if (pkg.scripts && Object.keys(pkg.scripts).length > 0) {
|
|
181
|
+
sections.push("")
|
|
182
|
+
sections.push("Scripts:")
|
|
183
|
+
for (const [name, cmd] of Object.entries(pkg.scripts)) {
|
|
184
|
+
sections.push(` ${name}: ${cmd}`)
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
if (pkg.dependencies) {
|
|
189
|
+
const depCount = Object.keys(pkg.dependencies).length
|
|
190
|
+
sections.push("")
|
|
191
|
+
sections.push(`Dependencies (${depCount}):`)
|
|
192
|
+
if (depCount <= 15) {
|
|
193
|
+
for (const [name, ver] of Object.entries(pkg.dependencies)) {
|
|
194
|
+
sections.push(` ${name}: ${ver}`)
|
|
195
|
+
}
|
|
196
|
+
} else {
|
|
197
|
+
// Show first 10 + summary
|
|
198
|
+
const entries = Object.entries(pkg.dependencies)
|
|
199
|
+
for (const [name, ver] of entries.slice(0, 10)) {
|
|
200
|
+
sections.push(` ${name}: ${ver}`)
|
|
201
|
+
}
|
|
202
|
+
sections.push(` ... and ${depCount - 10} more`)
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
if (pkg.devDependencies) {
|
|
207
|
+
const devCount = Object.keys(pkg.devDependencies).length
|
|
208
|
+
sections.push("")
|
|
209
|
+
sections.push(`DevDependencies (${devCount}):`)
|
|
210
|
+
if (devCount <= 10) {
|
|
211
|
+
for (const [name, ver] of Object.entries(pkg.devDependencies)) {
|
|
212
|
+
sections.push(` ${name}: ${ver}`)
|
|
213
|
+
}
|
|
214
|
+
} else {
|
|
215
|
+
const entries = Object.entries(pkg.devDependencies)
|
|
216
|
+
for (const [name, ver] of entries.slice(0, 5)) {
|
|
217
|
+
sections.push(` ${name}: ${ver}`)
|
|
218
|
+
}
|
|
219
|
+
sections.push(` ... and ${devCount - 5} more`)
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
return sections.join("\n")
|
|
224
|
+
} catch {
|
|
225
|
+
// Not valid JSON — generic truncation
|
|
226
|
+
return truncateGeneric(output)
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// ============================================================================
|
|
231
|
+
// Filter: Large Code Files — Structural Compression
|
|
232
|
+
// ============================================================================
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Structural compression for code files.
|
|
236
|
+
* Keeps: imports, exports, type definitions, function/class signatures, comments with TODO/FIXME/HACK
|
|
237
|
+
* Collapses: function bodies > N lines, consecutive blank lines
|
|
238
|
+
*/
|
|
239
|
+
function filterCodeFile(output: string): string {
|
|
240
|
+
const lines = output.split("\n")
|
|
241
|
+
const kept: string[] = []
|
|
242
|
+
let bodyDepth = 0
|
|
243
|
+
let bodyLines = 0
|
|
244
|
+
let skippedInBody = 0
|
|
245
|
+
const MAX_BODY_LINES = 8 // keep first N lines of a body
|
|
246
|
+
|
|
247
|
+
for (let i = 0; i < lines.length; i++) {
|
|
248
|
+
const line = lines[i]
|
|
249
|
+
const trimmed = line.trim()
|
|
250
|
+
|
|
251
|
+
// Track brace depth for body detection
|
|
252
|
+
const opens = (line.match(/\{/g) || []).length
|
|
253
|
+
const closes = (line.match(/\}/g) || []).length
|
|
254
|
+
|
|
255
|
+
// Always keep: empty lines (structure), imports, exports, type/interface/class declarations
|
|
256
|
+
// comments with TODO/FIXME/HACK, decorators
|
|
257
|
+
if (
|
|
258
|
+
trimmed === "" ||
|
|
259
|
+
/^(import |export |from )/.test(trimmed) ||
|
|
260
|
+
/^(export )?(default |abstract |async |const |let |var |function |class |interface |type |enum )/.test(trimmed) ||
|
|
261
|
+
/^(\/\/|#|\/\*|\*)/.test(trimmed) ||
|
|
262
|
+
/\b(TODO|FIXME|HACK|XXX|WARN|BUG|NOTE)\b/i.test(trimmed) ||
|
|
263
|
+
/^@/.test(trimmed) || // decorators
|
|
264
|
+
/^}\s*$/.test(trimmed) // closing brace
|
|
265
|
+
) {
|
|
266
|
+
// If we were skipping body lines, add omission marker
|
|
267
|
+
if (skippedInBody > 0) {
|
|
268
|
+
kept.push(` [... ${skippedInBody} lines omitted]`)
|
|
269
|
+
skippedInBody = 0
|
|
270
|
+
}
|
|
271
|
+
kept.push(line)
|
|
272
|
+
bodyDepth += opens - closes
|
|
273
|
+
bodyLines = 0
|
|
274
|
+
continue
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
// Inside a body (after opening brace)
|
|
278
|
+
bodyDepth += opens - closes
|
|
279
|
+
|
|
280
|
+
if (bodyDepth > 1 || (bodyDepth === 1 && bodyLines < MAX_BODY_LINES)) {
|
|
281
|
+
kept.push(line)
|
|
282
|
+
bodyLines++
|
|
283
|
+
} else if (bodyDepth === 1 && bodyLines >= MAX_BODY_LINES) {
|
|
284
|
+
// Skip body lines but track count
|
|
285
|
+
skippedInBody++
|
|
286
|
+
bodyLines++
|
|
287
|
+
} else {
|
|
288
|
+
// Top-level or unknown — keep it
|
|
289
|
+
kept.push(line)
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// Final omission marker
|
|
294
|
+
if (skippedInBody > 0) {
|
|
295
|
+
kept.push(` [... ${skippedInBody} lines omitted]`)
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
return deduplicateEmptyLines(kept.join("\n"))
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
// ============================================================================
|
|
302
|
+
// Filter: Markdown
|
|
303
|
+
// ============================================================================
|
|
304
|
+
|
|
305
|
+
function filterMarkdown(output: string): string {
|
|
306
|
+
const lines = output.split("\n")
|
|
307
|
+
const kept: string[] = []
|
|
308
|
+
let inParagraph = false
|
|
309
|
+
let paragraphLineCount = 0
|
|
310
|
+
let inCodeBlock = false
|
|
311
|
+
|
|
312
|
+
for (const line of lines) {
|
|
313
|
+
const trimmed = line.trim()
|
|
314
|
+
|
|
315
|
+
// Track code block state
|
|
316
|
+
if (trimmed.startsWith("```")) {
|
|
317
|
+
inCodeBlock = !inCodeBlock
|
|
318
|
+
kept.push(line)
|
|
319
|
+
continue
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
// Keep all lines inside code blocks
|
|
323
|
+
if (inCodeBlock) {
|
|
324
|
+
kept.push(line)
|
|
325
|
+
continue
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
// Always keep headings
|
|
329
|
+
if (/^#{1,6}\s/.test(trimmed)) {
|
|
330
|
+
kept.push(line)
|
|
331
|
+
inParagraph = false
|
|
332
|
+
paragraphLineCount = 0
|
|
333
|
+
continue
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
// Empty lines
|
|
337
|
+
if (trimmed === "") {
|
|
338
|
+
kept.push(line)
|
|
339
|
+
inParagraph = false
|
|
340
|
+
paragraphLineCount = 0
|
|
341
|
+
continue
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
// Keep first paragraph line after heading, skip the rest
|
|
345
|
+
if (!inParagraph) {
|
|
346
|
+
kept.push(line)
|
|
347
|
+
inParagraph = true
|
|
348
|
+
paragraphLineCount = 1
|
|
349
|
+
} else {
|
|
350
|
+
paragraphLineCount++
|
|
351
|
+
// Skip subsequent paragraph lines
|
|
352
|
+
if (paragraphLineCount === 2) {
|
|
353
|
+
kept.push(` [... additional paragraph content omitted]`)
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
return deduplicateEmptyLines(kept.join("\n"))
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
// ============================================================================
|
|
362
|
+
// Filter: Generic
|
|
363
|
+
// ============================================================================
|
|
364
|
+
|
|
365
|
+
function truncateGeneric(output: string): string {
|
|
366
|
+
const lines = output.split("\n")
|
|
367
|
+
const bytes = Buffer.byteLength(output, "utf-8")
|
|
368
|
+
|
|
369
|
+
if (lines.length <= 100) return output
|
|
370
|
+
|
|
371
|
+
const head = lines.slice(0, 50)
|
|
372
|
+
const tail = lines.slice(-10)
|
|
373
|
+
const omitted = lines.length - 60
|
|
374
|
+
|
|
375
|
+
return [
|
|
376
|
+
...head,
|
|
377
|
+
"",
|
|
378
|
+
`[... ${omitted} lines omitted (${formatBytes(bytes)})]`,
|
|
379
|
+
"",
|
|
380
|
+
...tail,
|
|
381
|
+
].join("\n")
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
// ============================================================================
|
|
385
|
+
// Helpers
|
|
386
|
+
// ============================================================================
|
|
387
|
+
|
|
388
|
+
function deduplicateEmptyLines(text: string): string {
|
|
389
|
+
return text.replace(/\n{3,}/g, "\n\n")
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
function formatBytes(bytes: number): string {
|
|
393
|
+
if (bytes < 1024) return `${bytes}B`
|
|
394
|
+
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)}KB`
|
|
395
|
+
return `${(bytes / (1024 * 1024)).toFixed(1)}MB`
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
function appendFilterNotice(
|
|
399
|
+
output: string,
|
|
400
|
+
originalBytes: number,
|
|
401
|
+
filteredBytes: number,
|
|
402
|
+
strategy: string,
|
|
403
|
+
): string {
|
|
404
|
+
const saved = formatBytes(originalBytes - filteredBytes)
|
|
405
|
+
return `${output}\n\n[Read output filtered: ${formatBytes(originalBytes)} → ${formatBytes(filteredBytes)} (${saved} saved, strategy: ${strategy})]`
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
// ============================================================================
|
|
409
|
+
// Main Filter Function
|
|
410
|
+
// ============================================================================
|
|
411
|
+
|
|
412
|
+
export function filterReadOutput(input: ReadOutputFilterInput): ReadOutputFilterResult {
|
|
413
|
+
const { path, output, isError, isImage } = input
|
|
414
|
+
const originalBytes = Buffer.byteLength(output, "utf-8")
|
|
415
|
+
|
|
416
|
+
// Don't filter images
|
|
417
|
+
if (isImage) {
|
|
418
|
+
return { output, filtered: false, originalBytes, filteredBytes: originalBytes, strategy: "none (image)" }
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
// Don't filter error outputs
|
|
422
|
+
if (isError) {
|
|
423
|
+
return { output, filtered: false, originalBytes, filteredBytes: originalBytes, strategy: "none (error)" }
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
// Don't filter small outputs
|
|
427
|
+
if (originalBytes < MIN_FILTER_THRESHOLD) {
|
|
428
|
+
return { output, filtered: false, originalBytes, filteredBytes: originalBytes, strategy: "none (below threshold)" }
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
const category = classifyFile(path)
|
|
432
|
+
|
|
433
|
+
let filtered: string
|
|
434
|
+
let strategyName: string
|
|
435
|
+
|
|
436
|
+
switch (category) {
|
|
437
|
+
case "lock-file":
|
|
438
|
+
filtered = filterLockFile(output, path)
|
|
439
|
+
strategyName = "lock-file (summary only)"
|
|
440
|
+
break
|
|
441
|
+
|
|
442
|
+
case "minified-file":
|
|
443
|
+
filtered = filterMinifiedFile(output, path)
|
|
444
|
+
strategyName = "minified (head only)"
|
|
445
|
+
break
|
|
446
|
+
|
|
447
|
+
case "generated-file":
|
|
448
|
+
filtered = filterGeneratedFile(output, path)
|
|
449
|
+
strategyName = "generated (head + tail)"
|
|
450
|
+
break
|
|
451
|
+
|
|
452
|
+
case "package-json":
|
|
453
|
+
filtered = filterPackageJson(output)
|
|
454
|
+
strategyName = "package.json (scripts + dep summary)"
|
|
455
|
+
break
|
|
456
|
+
|
|
457
|
+
case "code":
|
|
458
|
+
if (originalBytes >= CODE_COMPRESS_THRESHOLD) {
|
|
459
|
+
filtered = filterCodeFile(output)
|
|
460
|
+
strategyName = "code (structural compression)"
|
|
461
|
+
} else {
|
|
462
|
+
return { output, filtered: false, originalBytes, filteredBytes: originalBytes, strategy: "none (code file below threshold)" }
|
|
463
|
+
}
|
|
464
|
+
break
|
|
465
|
+
|
|
466
|
+
case "markdown":
|
|
467
|
+
filtered = filterMarkdown(output)
|
|
468
|
+
strategyName = "markdown (headings + first paragraph)"
|
|
469
|
+
break
|
|
470
|
+
|
|
471
|
+
case "config":
|
|
472
|
+
// Config files: only filter if very large
|
|
473
|
+
if (originalBytes > MAX_FILTERED_SIZE) {
|
|
474
|
+
filtered = truncateGeneric(output)
|
|
475
|
+
strategyName = "config (generic truncation)"
|
|
476
|
+
} else {
|
|
477
|
+
return { output, filtered: false, originalBytes, filteredBytes: originalBytes, strategy: "none (config, within limit)" }
|
|
478
|
+
}
|
|
479
|
+
break
|
|
480
|
+
|
|
481
|
+
default:
|
|
482
|
+
// Unknown files: only filter if very large
|
|
483
|
+
if (originalBytes > MAX_FILTERED_SIZE) {
|
|
484
|
+
filtered = truncateGeneric(output)
|
|
485
|
+
strategyName = "generic (large unknown file)"
|
|
486
|
+
} else {
|
|
487
|
+
return { output, filtered: false, originalBytes, filteredBytes: originalBytes, strategy: "none (unknown, within limit)" }
|
|
488
|
+
}
|
|
489
|
+
break
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
const filteredBytes = Buffer.byteLength(filtered, "utf-8")
|
|
493
|
+
|
|
494
|
+
// If filtering didn't help much (< 20% reduction), keep original
|
|
495
|
+
if (filteredBytes > originalBytes * 0.8) {
|
|
496
|
+
return { output, filtered: false, originalBytes, filteredBytes, strategy: `none (${category}: filtering insufficient, <20% reduction)` }
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
return {
|
|
500
|
+
output: appendFilterNotice(filtered, originalBytes, filteredBytes, strategyName),
|
|
501
|
+
filtered: true,
|
|
502
|
+
originalBytes,
|
|
503
|
+
filteredBytes,
|
|
504
|
+
strategy: strategyName,
|
|
505
|
+
}
|
|
506
|
+
}
|