@asterxsk/kiln 0.4.0 → 0.4.2
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/README.md +155 -155
- package/agent/AGENTS.md +67 -67
- package/agent/README.md +5 -5
- package/agent/extensions/ask-user/index.ts +418 -418
- package/agent/extensions/ask-user/install.ps1 +27 -27
- package/agent/extensions/ask-user/install.sh +24 -24
- package/agent/extensions/ask-user/package-lock.json +769 -769
- package/agent/extensions/ask-user/package.json +19 -19
- package/agent/extensions/ask-user/prompt.ts +45 -45
- package/agent/extensions/ask-user/tsconfig.json +7 -7
- package/agent/extensions/background-terminals/docs/implementation-guide.md +942 -942
- package/agent/extensions/background-terminals/index.ts +627 -627
- package/agent/extensions/background-terminals/install.ps1 +27 -27
- package/agent/extensions/background-terminals/install.sh +24 -24
- package/agent/extensions/background-terminals/manager.test.ts +735 -735
- package/agent/extensions/background-terminals/output.test.ts +109 -109
- package/agent/extensions/background-terminals/package-lock.json +769 -769
- package/agent/extensions/background-terminals/package.json +17 -17
- package/agent/extensions/background-terminals/prompt.test.ts +125 -125
- package/agent/extensions/background-terminals/ps.test.ts +82 -82
- package/agent/extensions/background-terminals/result-delivery.test.ts +44 -44
- package/agent/extensions/background-terminals/src/domain.ts +87 -87
- package/agent/extensions/background-terminals/src/manager.ts +907 -907
- package/agent/extensions/background-terminals/src/output.ts +84 -84
- package/agent/extensions/background-terminals/src/prompt.ts +142 -142
- package/agent/extensions/background-terminals/src/result-delivery.ts +27 -27
- package/agent/extensions/background-terminals/src/runtime.ts +36 -36
- package/agent/extensions/background-terminals/src/ui/output-view.ts +79 -79
- package/agent/extensions/background-terminals/src/ui/ps.ts +621 -621
- package/agent/extensions/background-terminals/tsconfig.json +7 -7
- package/agent/extensions/destructive/README.md +31 -31
- package/agent/extensions/destructive/index.ts +88 -88
- package/agent/extensions/destructive/install.ps1 +27 -27
- package/agent/extensions/destructive/install.sh +24 -24
- package/agent/extensions/file-search/index.spec.ts +443 -443
- package/agent/extensions/file-search/index.ts +459 -459
- package/agent/extensions/file-search/install.ps1 +27 -27
- package/agent/extensions/file-search/install.sh +24 -24
- package/agent/extensions/file-search/package-lock.json +2253 -2253
- package/agent/extensions/file-search/package.json +23 -23
- package/agent/extensions/file-search/src/args.ts +122 -122
- package/agent/extensions/file-search/src/binaries.ts +422 -422
- package/agent/extensions/file-search/src/output.ts +126 -126
- package/agent/extensions/file-search/src/process.ts +146 -146
- package/agent/extensions/file-search/src/prompt.ts +52 -52
- package/agent/extensions/file-search/tsconfig.json +7 -7
- package/agent/extensions/goal/README.md +50 -50
- package/agent/extensions/goal/index.ts +155 -155
- package/agent/extensions/goal/install.ps1 +27 -27
- package/agent/extensions/goal/install.sh +24 -24
- package/agent/extensions/kiln-update/README.md +38 -25
- package/agent/extensions/kiln-update/index.ts +177 -99
- package/agent/extensions/modelconf/PLAN.md +915 -915
- package/agent/extensions/modelconf/README.md +66 -66
- package/agent/extensions/modelconf/index.ts +296 -296
- package/agent/extensions/modelconf/install.ps1 +27 -27
- package/agent/extensions/modelconf/install.sh +24 -24
- package/agent/extensions/modelconf/package-lock.json +1809 -1809
- package/agent/extensions/modelconf/package.json +13 -13
- package/agent/extensions/modelconf/src/fuzzy.ts +26 -26
- package/agent/extensions/modelconf/src/glob.ts +13 -13
- package/agent/extensions/modelconf/src/persistence.test.ts +46 -46
- package/agent/extensions/modelconf/src/persistence.ts +164 -164
- package/agent/extensions/modelconf/src/ui/ModelConfView.test.ts +75 -75
- package/agent/extensions/modelconf/src/ui/ModelConfView.ts +1101 -1101
- package/agent/extensions/modelconf/tsconfig.json +15 -15
- package/agent/extensions/pi-web-access/CHANGELOG.md +690 -690
- package/agent/extensions/pi-web-access/LICENSE +21 -21
- package/agent/extensions/pi-web-access/README.md +470 -470
- package/agent/extensions/pi-web-access/SECURITY.md +5 -5
- package/agent/extensions/pi-web-access/activity.ts +101 -101
- package/agent/extensions/pi-web-access/auth-fetch.ts +148 -148
- package/agent/extensions/pi-web-access/brightdata-unlocker.ts +272 -272
- package/agent/extensions/pi-web-access/chrome-cookies.ts +669 -669
- package/agent/extensions/pi-web-access/content-find.ts +139 -139
- package/agent/extensions/pi-web-access/credential-source.ts +191 -191
- package/agent/extensions/pi-web-access/data-uri-sanitize.ts +406 -406
- package/agent/extensions/pi-web-access/datalab-pdf-extract.ts +568 -568
- package/agent/extensions/pi-web-access/declared-web-links.ts +173 -173
- package/agent/extensions/pi-web-access/evidence/CONTRACT-EVIDENCE.md +496 -496
- package/agent/extensions/pi-web-access/evidence/contract-probe.mjs +140 -140
- package/agent/extensions/pi-web-access/exa.ts +526 -526
- package/agent/extensions/pi-web-access/extract.ts +1196 -1196
- package/agent/extensions/pi-web-access/feature-config.ts +29 -29
- package/agent/extensions/pi-web-access/fetch-params.ts +111 -111
- package/agent/extensions/pi-web-access/gemini-adc.ts +298 -298
- package/agent/extensions/pi-web-access/gemini-api.ts +353 -353
- package/agent/extensions/pi-web-access/gemini-pdf-extract.ts +108 -108
- package/agent/extensions/pi-web-access/gemini-search.ts +21 -21
- package/agent/extensions/pi-web-access/gemini-url-context.ts +128 -128
- package/agent/extensions/pi-web-access/gemini-web-config.ts +101 -101
- package/agent/extensions/pi-web-access/gemini-web.ts +487 -487
- package/agent/extensions/pi-web-access/github-api.ts +197 -197
- package/agent/extensions/pi-web-access/github-extract.ts +746 -746
- package/agent/extensions/pi-web-access/github-issue-pr.ts +700 -700
- package/agent/extensions/pi-web-access/index.ts +1737 -1737
- package/agent/extensions/pi-web-access/package-lock.json +5808 -5808
- package/agent/extensions/pi-web-access/package.json +64 -64
- package/agent/extensions/pi-web-access/page-query.ts +96 -96
- package/agent/extensions/pi-web-access/pdf-extract.ts +409 -409
- package/agent/extensions/pi-web-access/promise-try.d.ts +7 -7
- package/agent/extensions/pi-web-access/query-rewrite.ts +51 -51
- package/agent/extensions/pi-web-access/render-search-error.ts +170 -170
- package/agent/extensions/pi-web-access/rsc-extract.ts +338 -338
- package/agent/extensions/pi-web-access/search-types.ts +20 -20
- package/agent/extensions/pi-web-access/source-check.ts +282 -282
- package/agent/extensions/pi-web-access/ssrf-protection.ts +526 -526
- package/agent/extensions/pi-web-access/storage.ts +521 -521
- package/agent/extensions/pi-web-access/summary-model-scope.ts +125 -125
- package/agent/extensions/pi-web-access/test/auth-fetch.test.mjs +208 -208
- package/agent/extensions/pi-web-access/test/brightdata-unlocker.test.mjs +840 -840
- package/agent/extensions/pi-web-access/test/chrome-cookie-extraction.test.mjs +441 -441
- package/agent/extensions/pi-web-access/test/config-path.test.mjs +283 -283
- package/agent/extensions/pi-web-access/test/content-find.test.mjs +25 -25
- package/agent/extensions/pi-web-access/test/credential-source.test.mjs +118 -118
- package/agent/extensions/pi-web-access/test/data-uri-sanitize.test.mjs +210 -210
- package/agent/extensions/pi-web-access/test/datalab-pdf-extract.test.mjs +552 -552
- package/agent/extensions/pi-web-access/test/declared-web-links.test.mjs +212 -212
- package/agent/extensions/pi-web-access/test/fetch-answer-storage.test.mjs +40 -40
- package/agent/extensions/pi-web-access/test/fetch-cache-storage.test.mjs +334 -334
- package/agent/extensions/pi-web-access/test/fetch-content-domain-policy.test.mjs +95 -95
- package/agent/extensions/pi-web-access/test/fetch-modes.test.mjs +53 -53
- package/agent/extensions/pi-web-access/test/fetch-not-found-guidance.test.mjs +92 -92
- package/agent/extensions/pi-web-access/test/fetch-params.test.mjs +86 -86
- package/agent/extensions/pi-web-access/test/fetch-render-call.test.mjs +34 -34
- package/agent/extensions/pi-web-access/test/fetch-routing.test.mjs +173 -173
- package/agent/extensions/pi-web-access/test/gemini-adc-auth.test.mjs +257 -257
- package/agent/extensions/pi-web-access/test/gemini-api-transport.test.mjs +170 -170
- package/agent/extensions/pi-web-access/test/gemini-pdf-extract.test.mjs +133 -133
- package/agent/extensions/pi-web-access/test/gemini-web-cookie-opt-in.test.mjs +178 -178
- package/agent/extensions/pi-web-access/test/gemini-web-header-overflow.test.mjs +148 -148
- package/agent/extensions/pi-web-access/test/get-search-content.test.mjs +223 -223
- package/agent/extensions/pi-web-access/test/github-extract.test.mjs +378 -378
- package/agent/extensions/pi-web-access/test/github-issue-pr.test.mjs +565 -565
- package/agent/extensions/pi-web-access/test/inline-content-config.test.mjs +99 -99
- package/agent/extensions/pi-web-access/test/lazy-extract-load.test.mjs +118 -118
- package/agent/extensions/pi-web-access/test/local-video-oversize.test.mjs +52 -52
- package/agent/extensions/pi-web-access/test/package-typebox-dependency.test.mjs +50 -50
- package/agent/extensions/pi-web-access/test/page-query.test.mjs +51 -51
- package/agent/extensions/pi-web-access/test/pdf-config.test.mjs +140 -140
- package/agent/extensions/pi-web-access/test/pdf-extract.test.mjs +500 -500
- package/agent/extensions/pi-web-access/test/proxy-transport.test.mjs +286 -286
- package/agent/extensions/pi-web-access/test/query-rewrite.test.mjs +52 -52
- package/agent/extensions/pi-web-access/test/rsc-fallback.test.mjs +102 -102
- package/agent/extensions/pi-web-access/test/search-error-render.test.mjs +152 -152
- package/agent/extensions/pi-web-access/test/search-providers.test.mjs +274 -274
- package/agent/extensions/pi-web-access/test/source-check.test.mjs +179 -179
- package/agent/extensions/pi-web-access/test/ssrf-allow-ranges-config.test.mjs +205 -205
- package/agent/extensions/pi-web-access/test/ssrf-protection.test.mjs +456 -456
- package/agent/extensions/pi-web-access/test/summary-model-scope.test.mjs +106 -106
- package/agent/extensions/pi-web-access/test/tool-registration-config.test.mjs +182 -182
- package/agent/extensions/pi-web-access/test/web-search-answer-render.test.mjs +66 -66
- package/agent/extensions/pi-web-access/test/youtube-extract-errors.test.mjs +64 -64
- package/agent/extensions/pi-web-access/tsconfig.json +11 -11
- package/agent/extensions/pi-web-access/utils.ts +451 -451
- package/agent/extensions/pi-web-access/video-extract.ts +392 -392
- package/agent/extensions/pi-web-access/youtube-extract.ts +328 -328
- package/agent/extensions/shared/activity-status.ts +31 -31
- package/agent/extensions/shared/child-session.test.ts +270 -270
- package/agent/extensions/shared/child-session.ts +148 -148
- package/agent/extensions/shared/context-utilization.test.ts +48 -48
- package/agent/extensions/shared/context-utilization.ts +47 -47
- package/agent/extensions/shared/dashboard-state.ts +99 -99
- package/agent/extensions/shared/install.ps1 +27 -27
- package/agent/extensions/shared/install.sh +24 -24
- package/agent/extensions/shared/tool-call-timeout.test.ts +117 -117
- package/agent/extensions/shared/tool-call-timeout.ts +104 -104
- package/agent/extensions/skillsconf/README.md +74 -74
- package/agent/extensions/skillsconf/index.ts +92 -92
- package/agent/extensions/skillsconf/install.ps1 +27 -27
- package/agent/extensions/skillsconf/install.sh +24 -24
- package/agent/extensions/skillsconf/package-lock.json +1809 -1809
- package/agent/extensions/skillsconf/package.json +18 -18
- package/agent/extensions/skillsconf/src/delete-skill.test.ts +64 -64
- package/agent/extensions/skillsconf/src/delete-skill.ts +45 -45
- package/agent/extensions/skillsconf/src/filter.test.ts +80 -80
- package/agent/extensions/skillsconf/src/filter.ts +74 -74
- package/agent/extensions/skillsconf/src/fuzzy.ts +26 -26
- package/agent/extensions/skillsconf/src/persistence.test.ts +72 -72
- package/agent/extensions/skillsconf/src/persistence.ts +169 -169
- package/agent/extensions/skillsconf/src/ui/SkillConfView.test.ts +337 -337
- package/agent/extensions/skillsconf/src/ui/SkillConfView.ts +758 -758
- package/agent/extensions/skillsconf/src/ui/text-input.ts +91 -91
- package/agent/extensions/skillsconf/src/ui/tui-helpers.ts +144 -144
- package/agent/extensions/skillsconf/tsconfig.json +15 -15
- package/agent/extensions/statusline/index.ts +273 -282
- package/agent/extensions/statusline/install.ps1 +27 -27
- package/agent/extensions/statusline/install.sh +24 -24
- package/agent/extensions/subagents/by-the-way.test.ts +29 -29
- package/agent/extensions/subagents/claude.test.ts +119 -119
- package/agent/extensions/subagents/codex.test.ts +102 -102
- package/agent/extensions/subagents/context-usage.test.ts +107 -107
- package/agent/extensions/subagents/docs/design-plan.md +568 -568
- package/agent/extensions/subagents/docs/effect-v4-extension-guide.md +354 -354
- package/agent/extensions/subagents/docs/effect-v4-notes.md +571 -571
- package/agent/extensions/subagents/index.ts +779 -779
- package/agent/extensions/subagents/install.ps1 +27 -27
- package/agent/extensions/subagents/install.sh +24 -24
- package/agent/extensions/subagents/manager.test.ts +276 -276
- package/agent/extensions/subagents/package-lock.json +2244 -2244
- package/agent/extensions/subagents/package.json +19 -19
- package/agent/extensions/subagents/result-delivery.test.ts +27 -27
- package/agent/extensions/subagents/src/backend.ts +73 -73
- package/agent/extensions/subagents/src/backends/claude.ts +701 -701
- package/agent/extensions/subagents/src/backends/codex.ts +1060 -1060
- package/agent/extensions/subagents/src/backends/pi.ts +575 -575
- package/agent/extensions/subagents/src/backends/stub.ts +300 -300
- package/agent/extensions/subagents/src/by-the-way.ts +21 -21
- package/agent/extensions/subagents/src/domain.ts +253 -253
- package/agent/extensions/subagents/src/format.ts +74 -74
- package/agent/extensions/subagents/src/manager.ts +736 -736
- package/agent/extensions/subagents/src/prompt.ts +92 -92
- package/agent/extensions/subagents/src/result-delivery.ts +20 -20
- package/agent/extensions/subagents/src/runtime.ts +53 -53
- package/agent/extensions/subagents/src/ui/takeover.ts +583 -583
- package/agent/extensions/subagents/src/ui/transcript.ts +201 -201
- package/agent/extensions/subagents/takeover.test.ts +29 -29
- package/agent/extensions/subagents/tsconfig.json +7 -7
- package/agent/extensions/todo/AGENTS.md +38 -38
- package/agent/extensions/todo/LICENSE +21 -21
- package/agent/extensions/todo/config.ts +55 -55
- package/agent/extensions/todo/index.ts +151 -151
- package/agent/extensions/todo/install.ps1 +27 -27
- package/agent/extensions/todo/install.sh +24 -24
- package/agent/extensions/todo/locales/de.json +17 -17
- package/agent/extensions/todo/locales/en.json +15 -15
- package/agent/extensions/todo/locales/es.json +17 -17
- package/agent/extensions/todo/locales/fr.json +17 -17
- package/agent/extensions/todo/locales/pt-BR.json +17 -17
- package/agent/extensions/todo/locales/pt.json +17 -17
- package/agent/extensions/todo/locales/ru.json +17 -17
- package/agent/extensions/todo/locales/uk.json +17 -17
- package/agent/extensions/todo/locales/zh.json +17 -17
- package/agent/extensions/todo/package-lock.json +3358 -3358
- package/agent/extensions/todo/package.json +67 -67
- package/agent/extensions/todo/state/i18n-bridge.ts +64 -64
- package/agent/extensions/todo/state/invariants.ts +20 -20
- package/agent/extensions/todo/state/replay.ts +38 -38
- package/agent/extensions/todo/state/selectors.ts +107 -107
- package/agent/extensions/todo/state/state-reducer.ts +326 -326
- package/agent/extensions/todo/state/state.ts +18 -18
- package/agent/extensions/todo/state/store.ts +82 -82
- package/agent/extensions/todo/state/task-graph.ts +57 -57
- package/agent/extensions/todo/todo-overlay.ts +200 -200
- package/agent/extensions/todo/todo.ts +155 -155
- package/agent/extensions/todo/tool/response-envelope.ts +109 -109
- package/agent/extensions/todo/tool/types.ts +206 -206
- package/agent/extensions/todo/view/format.ts +177 -177
- package/agent/extensions/trim-context/README.md +54 -54
- package/agent/extensions/trim-context/index.ts +487 -487
- package/agent/extensions/trim-context/install.ps1 +27 -27
- package/agent/extensions/trim-context/install.sh +24 -24
- package/agent/keybindings.json +7 -7
- package/agent/version.txt +1 -1
- package/bin/kiln.js +20 -13
- package/package.json +1 -1
- package/agent/extensions/taste/index.ts +0 -443
- package/agent/extensions/taste/install.ps1 +0 -27
- package/agent/extensions/taste/install.sh +0 -24
|
@@ -1,487 +1,487 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* trim-context — pi extension for crush / amp / lsp style context management
|
|
3
|
-
*
|
|
4
|
-
* Does three things:
|
|
5
|
-
* 1. CACHING: forces PI_CACHE_RETENTION=long (1h Anthropic, 24h OpenAI) + ensures
|
|
6
|
-
* Anthropic/OpenAI cache_control breakpoints on system + last messages.
|
|
7
|
-
* Without this pi uses 5m cache which misses on long tasks.
|
|
8
|
-
*
|
|
9
|
-
* 2. OUTPUT COMPRESSION: intercepts tool_result for read/bash/grep/find/ls/edit/write
|
|
10
|
-
* and aggressively truncates large outputs before they are persisted to history.
|
|
11
|
-
* Built-in pi truncates at 50KB/2000 lines - this extension compresses at
|
|
12
|
-
* 30KB/400 lines for recent, and 8KB/100 lines for older via context hook.
|
|
13
|
-
* Full output is saved to temp file and referenced in the compressed result.
|
|
14
|
-
*
|
|
15
|
-
* 3. TRIM CONTEXT (crush/amp/lsp): via `context` event, before every LLM call:
|
|
16
|
-
* - keeps last KEEP_RECENT_TURNS (6) turns verbatim
|
|
17
|
-
* - for older turns: truncates tool results to 800 chars, strips thinking blocks,
|
|
18
|
-
* deduplicates repeated file reads (keeps only last read of same file),
|
|
19
|
-
* compresses old bash outputs to tail-only
|
|
20
|
-
* - if total estimated tokens > SOFT_LIMIT (80k), prunes oldest tool results first
|
|
21
|
-
*
|
|
22
|
-
* Install: lives in ~/.pi/agent/extensions/trim-context/ (auto-discovered)
|
|
23
|
-
* Reload: /reload
|
|
24
|
-
* Command: /trimContext — show stats / toggle
|
|
25
|
-
*/
|
|
26
|
-
|
|
27
|
-
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
28
|
-
import { mkdtempSync, writeFileSync } from "node:fs";
|
|
29
|
-
import { tmpdir } from "node:os";
|
|
30
|
-
import { join } from "node:path";
|
|
31
|
-
|
|
32
|
-
// ---------------------------------------------------------------------------
|
|
33
|
-
// Config — tune here
|
|
34
|
-
// ---------------------------------------------------------------------------
|
|
35
|
-
const CONFIG = {
|
|
36
|
-
// amp strict — keep only last 3 turns verbatim (amp keeps 2-3)
|
|
37
|
-
KEEP_RECENT_TURNS: 3,
|
|
38
|
-
|
|
39
|
-
// output compression thresholds for tool_result hook (immediate)
|
|
40
|
-
IMMEDIATE_MAX_BYTES: 12 * 1024, // 12KB for read/grep/etc (amp strict)
|
|
41
|
-
IMMEDIATE_MAX_LINES: 150,
|
|
42
|
-
// bash is the leak — amp strict: 750 tokens max
|
|
43
|
-
BASH_IMMEDIATE_MAX_BYTES: 3 * 1024, // 3KB ~750 tokens hard cap
|
|
44
|
-
BASH_IMMEDIATE_MAX_LINES: 30,
|
|
45
|
-
|
|
46
|
-
// context hook thresholds for OLD messages (older than KEEP_RECENT_TURNS)
|
|
47
|
-
OLD_MAX_CHARS: 500, // was 800
|
|
48
|
-
OLD_MAX_LINES: 20, // was 30
|
|
49
|
-
OLD_BASH_TAIL_LINES: 8, // was 12 — amp strict tail-only
|
|
50
|
-
|
|
51
|
-
// soft token limit before we start pruning oldest tool results entirely
|
|
52
|
-
SOFT_TOKEN_LIMIT: 50_000, // amp strict ~200KB chars, prune earlier
|
|
53
|
-
HARD_TOKEN_LIMIT: 80_000,
|
|
54
|
-
|
|
55
|
-
// dedupe repeated read()s
|
|
56
|
-
DEDUPE_READS: true,
|
|
57
|
-
|
|
58
|
-
// strip old thinking blocks
|
|
59
|
-
STRIP_OLD_THINKING: true,
|
|
60
|
-
|
|
61
|
-
// caching
|
|
62
|
-
CACHE_RETENTION: "long" as const, // "long" = 1h anthropic, 24h openai
|
|
63
|
-
};
|
|
64
|
-
|
|
65
|
-
// ---------------------------------------------------------------------------
|
|
66
|
-
// Helpers
|
|
67
|
-
// ---------------------------------------------------------------------------
|
|
68
|
-
function estimateTokens(text: string): number {
|
|
69
|
-
return Math.ceil(text.length / 4);
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
function getTextContent(blocks: Array<{ type: string; text?: string }>): string {
|
|
73
|
-
return blocks
|
|
74
|
-
.filter((b) => b.type === "text" && typeof b.text === "string")
|
|
75
|
-
.map((b) => b.text)
|
|
76
|
-
.join("\n");
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
function truncateToLimits(
|
|
80
|
-
text: string,
|
|
81
|
-
maxChars: number,
|
|
82
|
-
maxLines: number,
|
|
83
|
-
label = "truncated"
|
|
84
|
-
): { text: string; truncated: boolean; savedChars: number } {
|
|
85
|
-
const lines = text.split("\n");
|
|
86
|
-
let truncated = false;
|
|
87
|
-
let result = text;
|
|
88
|
-
|
|
89
|
-
if (lines.length > maxLines) {
|
|
90
|
-
// keep head + tail pattern for bash/logs, head-only for reads
|
|
91
|
-
const head = lines.slice(0, Math.floor(maxLines * 0.75));
|
|
92
|
-
const tail = lines.slice(-Math.floor(maxLines * 0.25));
|
|
93
|
-
result = [...head, `\n[... ${lines.length - maxLines} lines ${label} ...]\n`, ...tail].join("\n");
|
|
94
|
-
truncated = true;
|
|
95
|
-
}
|
|
96
|
-
if (result.length > maxChars) {
|
|
97
|
-
const headChars = Math.floor(maxChars * 0.8);
|
|
98
|
-
result =
|
|
99
|
-
result.slice(0, headChars) +
|
|
100
|
-
`\n[... ${result.length - headChars} chars ${label} ...]\n` +
|
|
101
|
-
result.slice(-Math.floor(maxChars * 0.2));
|
|
102
|
-
truncated = true;
|
|
103
|
-
}
|
|
104
|
-
return { text: result, truncated, savedChars: truncated ? text.length - result.length : 0 };
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
function saveFullOutput(fullText: string, toolName: string): string {
|
|
108
|
-
try {
|
|
109
|
-
const dir = mkdtempSync(join(tmpdir(), `pi-trim-${toolName}-`));
|
|
110
|
-
const file = join(dir, "full-output.txt");
|
|
111
|
-
writeFileSync(file, fullText, "utf8");
|
|
112
|
-
return file;
|
|
113
|
-
} catch {
|
|
114
|
-
return "(failed to save)";
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
// Track compression stats across session
|
|
119
|
-
let stats = {
|
|
120
|
-
toolResultsCompressed: 0,
|
|
121
|
-
charsSaved: 0,
|
|
122
|
-
readsDeduped: 0,
|
|
123
|
-
thinkingStripped: 0,
|
|
124
|
-
contextTrims: 0,
|
|
125
|
-
};
|
|
126
|
-
|
|
127
|
-
let trimEnabled = true;
|
|
128
|
-
|
|
129
|
-
// ---------------------------------------------------------------------------
|
|
130
|
-
// Extension
|
|
131
|
-
// ---------------------------------------------------------------------------
|
|
132
|
-
export default function (pi: ExtensionAPI) {
|
|
133
|
-
// Force long cache retention before any provider is created
|
|
134
|
-
if (process.env.PI_CACHE_RETENTION !== "long") {
|
|
135
|
-
process.env.PI_CACHE_RETENTION = CONFIG.CACHE_RETENTION;
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
pi.on("session_start", async (_event, ctx) => {
|
|
139
|
-
stats = { toolResultsCompressed: 0, charsSaved: 0, readsDeduped: 0, thinkingStripped: 0, contextTrims: 0 };
|
|
140
|
-
// clear legacy statusline from previous version
|
|
141
|
-
ctx.ui.setStatus("trim-context", undefined);
|
|
142
|
-
});
|
|
143
|
-
|
|
144
|
-
pi.on("session_shutdown", async () => {
|
|
145
|
-
stats = { toolResultsCompressed: 0, charsSaved: 0, readsDeduped: 0, thinkingStripped: 0, contextTrims: 0 };
|
|
146
|
-
});
|
|
147
|
-
|
|
148
|
-
// -------------------------------------------------------------------------
|
|
149
|
-
// 1) OUTPUT COMPRESSION — tool_result hook (immediate, before persistence)
|
|
150
|
-
// -------------------------------------------------------------------------
|
|
151
|
-
pi.on("tool_result", async (event, _ctx) => {
|
|
152
|
-
if (!trimEnabled) return;
|
|
153
|
-
const content = event.content as Array<{ type: string; text?: string }>;
|
|
154
|
-
const textBlocks = content.filter((c) => c.type === "text" && typeof c.text === "string");
|
|
155
|
-
if (textBlocks.length === 0) return;
|
|
156
|
-
|
|
157
|
-
const fullText = getTextContent(content as any);
|
|
158
|
-
if (!fullText) return;
|
|
159
|
-
|
|
160
|
-
const lines = fullText.split("\n").length;
|
|
161
|
-
const bytes = Buffer.byteLength(fullText, "utf8");
|
|
162
|
-
|
|
163
|
-
// bash/powershell get much tighter limits — that's your 1-2k leak
|
|
164
|
-
const isBash = event.toolName === "bash" || event.toolName === "powershell";
|
|
165
|
-
const maxBytes = isBash ? CONFIG.BASH_IMMEDIATE_MAX_BYTES : CONFIG.IMMEDIATE_MAX_BYTES;
|
|
166
|
-
const maxLines = isBash ? CONFIG.BASH_IMMEDIATE_MAX_LINES : CONFIG.IMMEDIATE_MAX_LINES;
|
|
167
|
-
|
|
168
|
-
// Also strip ANSI + collapse for bash before measuring (saves 10-20% tokens)
|
|
169
|
-
let textForCheck = fullText;
|
|
170
|
-
if (isBash) {
|
|
171
|
-
// strip ANSI escape codes, collapse 3+ blank lines, trim trailing whitespace per line
|
|
172
|
-
textForCheck = textForCheck.replace(/\x1B\[[0-9;]*[A-Za-z]/g, "").replace(/\n{3,}/g, "\n\n");
|
|
173
|
-
}
|
|
174
|
-
const checkLines = textForCheck.split("\n").length;
|
|
175
|
-
const checkBytes = Buffer.byteLength(textForCheck, "utf8");
|
|
176
|
-
if (checkBytes <= maxBytes && checkLines <= maxLines) {
|
|
177
|
-
// if we stripped ANSI but still under limit, still persist the cleaned version
|
|
178
|
-
if (isBash && textForCheck !== fullText) {
|
|
179
|
-
return { content: [{ type: "text", text: textForCheck }] };
|
|
180
|
-
}
|
|
181
|
-
return;
|
|
182
|
-
}
|
|
183
|
-
// use cleaned text for compression if bash
|
|
184
|
-
const sourceText = isBash ? textForCheck : fullText;
|
|
185
|
-
const sourceLines = sourceText.split("\n").length;
|
|
186
|
-
const sourceBytes = Buffer.byteLength(sourceText, "utf8");
|
|
187
|
-
|
|
188
|
-
const { text: compressed, savedChars } = truncateToLimits(
|
|
189
|
-
sourceText,
|
|
190
|
-
maxBytes,
|
|
191
|
-
maxLines,
|
|
192
|
-
`output compressed by trim-context (${toolNameLabel(event.toolName)})`
|
|
193
|
-
);
|
|
194
|
-
|
|
195
|
-
const fullPath = saveFullOutput(fullText, event.toolName);
|
|
196
|
-
const notice =
|
|
197
|
-
compressed +
|
|
198
|
-
`\n\n[trim-context: ${isBash ? "bash" : event.toolName} compressed from ${(sourceBytes / 1024).toFixed(1)}KB/${sourceLines} lines ` +
|
|
199
|
-
`to ${(Buffer.byteLength(compressed, "utf8") / 1024).toFixed(1)}KB. Full saved to: ${fullPath} — limit ${maxBytes / 1024}KB/${maxLines} lines]`;
|
|
200
|
-
|
|
201
|
-
stats.toolResultsCompressed++;
|
|
202
|
-
stats.charsSaved += savedChars;
|
|
203
|
-
|
|
204
|
-
// Return patch — pi chains these, so we only override content
|
|
205
|
-
return {
|
|
206
|
-
content: [{ type: "text", text: notice }],
|
|
207
|
-
};
|
|
208
|
-
});
|
|
209
|
-
|
|
210
|
-
function toolNameLabel(name: string): string {
|
|
211
|
-
return name || "tool";
|
|
212
|
-
}
|
|
213
|
-
|
|
214
|
-
// -------------------------------------------------------------------------
|
|
215
|
-
// 2) TRIM CONTEXT — context hook (crush/amp/lsp style, before each LLM call)
|
|
216
|
-
// -------------------------------------------------------------------------
|
|
217
|
-
pi.on("context", async (event, _ctx) => {
|
|
218
|
-
if (!trimEnabled) return;
|
|
219
|
-
const messages: any[] = event.messages;
|
|
220
|
-
if (messages.length === 0) return;
|
|
221
|
-
|
|
222
|
-
// Identify turn boundaries: each user message starts a turn
|
|
223
|
-
const userIndices: number[] = [];
|
|
224
|
-
for (let i = 0; i < messages.length; i++) {
|
|
225
|
-
if (messages[i].role === "user") userIndices.push(i);
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
// Determine cutoff: keep last KEEP_RECENT_TURNS user turns verbatim
|
|
229
|
-
const keepFromUserIdx = Math.max(0, userIndices.length - CONFIG.KEEP_RECENT_TURNS);
|
|
230
|
-
const keepFromMsgIdx = keepFromUserIdx < userIndices.length ? userIndices[keepFromUserIdx] : 0;
|
|
231
|
-
|
|
232
|
-
// For dedupe: find last read of each file path among ALL messages
|
|
233
|
-
const lastReadIndexByPath = new Map<string, number>();
|
|
234
|
-
if (CONFIG.DEDUPE_READS) {
|
|
235
|
-
for (let i = 0; i < messages.length; i++) {
|
|
236
|
-
const m = messages[i];
|
|
237
|
-
if (m.role === "assistant" && Array.isArray(m.content)) {
|
|
238
|
-
for (const block of m.content) {
|
|
239
|
-
if (block.type === "toolCall" && block.name === "read" && block.arguments?.path) {
|
|
240
|
-
const p = String(block.arguments.path);
|
|
241
|
-
lastReadIndexByPath.set(p, i);
|
|
242
|
-
}
|
|
243
|
-
}
|
|
244
|
-
}
|
|
245
|
-
}
|
|
246
|
-
}
|
|
247
|
-
|
|
248
|
-
let totalChars = 0;
|
|
249
|
-
for (const m of messages) {
|
|
250
|
-
totalChars += JSON.stringify(m).length;
|
|
251
|
-
}
|
|
252
|
-
const needsPruning = estimateTokens(JSON.stringify(messages)) > CONFIG.SOFT_TOKEN_LIMIT;
|
|
253
|
-
|
|
254
|
-
let prunedCount = 0;
|
|
255
|
-
let dedupedCount = 0;
|
|
256
|
-
let thinkingStripped = 0;
|
|
257
|
-
|
|
258
|
-
const trimmed = messages.map((msg, idx) => {
|
|
259
|
-
const isRecent = idx >= keepFromMsgIdx;
|
|
260
|
-
|
|
261
|
-
// Recent turns: keep verbatim (already compressed by tool_result hook)
|
|
262
|
-
if (isRecent) return msg;
|
|
263
|
-
|
|
264
|
-
// Old turns: apply aggressive trimming
|
|
265
|
-
|
|
266
|
-
// 1) Strip thinking blocks from old assistant messages
|
|
267
|
-
if (CONFIG.STRIP_OLD_THINKING && msg.role === "assistant" && Array.isArray(msg.content)) {
|
|
268
|
-
const origLen = msg.content.length;
|
|
269
|
-
const filtered = msg.content.filter((b: any) => b.type !== "thinking");
|
|
270
|
-
if (filtered.length !== origLen) {
|
|
271
|
-
thinkingStripped++;
|
|
272
|
-
// If we stripped all content and only thinking remained, keep a placeholder
|
|
273
|
-
if (filtered.length === 0) {
|
|
274
|
-
return { ...msg, content: [{ type: "text", text: "[thinking stripped by trim-context]" }] };
|
|
275
|
-
}
|
|
276
|
-
return { ...msg, content: filtered };
|
|
277
|
-
}
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
// 2) Deduplicate old reads: if this read is not the last read of that file, replace toolResult
|
|
281
|
-
if (CONFIG.DEDUPE_READS && msg.role === "assistant" && Array.isArray(msg.content)) {
|
|
282
|
-
for (const block of msg.content) {
|
|
283
|
-
if (block.type === "toolCall" && block.name === "read" && block.arguments?.path) {
|
|
284
|
-
const p = String(block.arguments.path);
|
|
285
|
-
const lastIdx = lastReadIndexByPath.get(p);
|
|
286
|
-
if (lastIdx !== undefined && lastIdx !== idx) {
|
|
287
|
-
// This is an old superseded read — we mark for later toolResult compression
|
|
288
|
-
// We tag the assistant message so the following toolResult can be identified
|
|
289
|
-
(msg as any).__trimReadPath = p;
|
|
290
|
-
}
|
|
291
|
-
}
|
|
292
|
-
}
|
|
293
|
-
}
|
|
294
|
-
|
|
295
|
-
// 3) Compress old toolResults
|
|
296
|
-
if (msg.role === "toolResult" && Array.isArray(msg.content)) {
|
|
297
|
-
const prevMsg = idx > 0 ? messages[idx - 1] : null;
|
|
298
|
-
const isSupersededRead =
|
|
299
|
-
!!(prevMsg as any)?.__trimReadPath ||
|
|
300
|
-
(msg.toolName === "read" && (() => {
|
|
301
|
-
// Check if there's a later read of same file
|
|
302
|
-
const toolInput = (msg as any).toolName === "read" ? (msg as any).input : null;
|
|
303
|
-
// Fallback: check details if available
|
|
304
|
-
return false;
|
|
305
|
-
})());
|
|
306
|
-
|
|
307
|
-
const text = getTextContent(msg.content as any);
|
|
308
|
-
if (!text) return msg;
|
|
309
|
-
|
|
310
|
-
// If superseded read, replace entirely
|
|
311
|
-
if (isSupersededRead || (msg.toolName === "read" && CONFIG.DEDUPE_READS)) {
|
|
312
|
-
// Check if a later read exists for same file by scanning forward for toolCall read with same path
|
|
313
|
-
// We already mapped lastReadIndex — if current toolResult is before last, it's superseded
|
|
314
|
-
// We need to correlate toolResult to its toolCall. Use toolCallId matching.
|
|
315
|
-
// Simpler: if total messages has a later read, compress heavily
|
|
316
|
-
const isOld = true;
|
|
317
|
-
if (isOld && text.length > 200) {
|
|
318
|
-
// Check if any later assistant has a read toolCall
|
|
319
|
-
let hasLaterRead = false;
|
|
320
|
-
for (let j = idx + 1; j < messages.length; j++) {
|
|
321
|
-
const later = messages[j];
|
|
322
|
-
if (later.role === "assistant" && Array.isArray(later.content)) {
|
|
323
|
-
for (const b of later.content) {
|
|
324
|
-
if (b.type === "toolCall" && b.name === "read") {
|
|
325
|
-
// We can't perfectly match path without toolCallId link, but assume if ANY later read exists
|
|
326
|
-
// and this is an old read, it's likely dedupable. Be conservative: only if many reads.
|
|
327
|
-
hasLaterRead = true;
|
|
328
|
-
break;
|
|
329
|
-
}
|
|
330
|
-
}
|
|
331
|
-
}
|
|
332
|
-
if (hasLaterRead) break;
|
|
333
|
-
}
|
|
334
|
-
if (hasLaterRead && lastReadIndexByPath.size > 1) {
|
|
335
|
-
// Don't aggressively dedupe single-file sessions
|
|
336
|
-
// Instead compress to tiny placeholder
|
|
337
|
-
dedupedCount++;
|
|
338
|
-
return {
|
|
339
|
-
...msg,
|
|
340
|
-
content: [{ type: "text", text: `[trim-context: superseded read — latest version kept later in context]` }],
|
|
341
|
-
};
|
|
342
|
-
}
|
|
343
|
-
}
|
|
344
|
-
}
|
|
345
|
-
|
|
346
|
-
// General old-result compression
|
|
347
|
-
if (text.length > CONFIG.OLD_MAX_CHARS || text.split("\n").length > CONFIG.OLD_MAX_LINES) {
|
|
348
|
-
let compressed: string;
|
|
349
|
-
if (msg.toolName === "bash" || msg.toolName === "powershell") {
|
|
350
|
-
// For bash, keep tail (most recent output matters)
|
|
351
|
-
const lines = text.split("\n");
|
|
352
|
-
const tail = lines.slice(-CONFIG.OLD_BASH_TAIL_LINES);
|
|
353
|
-
const headNote = `[trim-context: old bash output compressed from ${lines.length} lines / ${(text.length / 1024).toFixed(1)}KB to ${tail.length} lines]`;
|
|
354
|
-
compressed = headNote + "\n" + tail.join("\n");
|
|
355
|
-
} else {
|
|
356
|
-
const { text: t } = truncateToLimits(text, CONFIG.OLD_MAX_CHARS, CONFIG.OLD_MAX_LINES, "old result compressed");
|
|
357
|
-
compressed = t + `\n[trim-context: compressed old ${msg.toolName} result]`;
|
|
358
|
-
}
|
|
359
|
-
prunedCount++;
|
|
360
|
-
return { ...msg, content: [{ type: "text", text: compressed }] };
|
|
361
|
-
}
|
|
362
|
-
}
|
|
363
|
-
|
|
364
|
-
return msg;
|
|
365
|
-
});
|
|
366
|
-
|
|
367
|
-
// 4) If still over soft limit, hard-prune oldest toolResults entirely (keep marker)
|
|
368
|
-
if (needsPruning) {
|
|
369
|
-
let estimated = estimateTokens(JSON.stringify(trimmed));
|
|
370
|
-
for (let i = 0; i < trimmed.length && estimated > CONFIG.SOFT_TOKEN_LIMIT; i++) {
|
|
371
|
-
const m = trimmed[i];
|
|
372
|
-
if (m.role === "toolResult" && i < keepFromMsgIdx) {
|
|
373
|
-
const text = getTextContent(m.content as any[]);
|
|
374
|
-
if (text && !text.startsWith("[trim-context:")) {
|
|
375
|
-
trimmed[i] = {
|
|
376
|
-
...m,
|
|
377
|
-
content: [{ type: "text", text: `[trim-context: pruned to save context — was ${(text.length / 1024).toFixed(1)}KB]` }],
|
|
378
|
-
};
|
|
379
|
-
estimated -= estimateTokens(text);
|
|
380
|
-
prunedCount++;
|
|
381
|
-
}
|
|
382
|
-
}
|
|
383
|
-
}
|
|
384
|
-
}
|
|
385
|
-
|
|
386
|
-
if (prunedCount > 0 || dedupedCount > 0 || thinkingStripped > 0) {
|
|
387
|
-
stats.contextTrims++;
|
|
388
|
-
stats.readsDeduped += dedupedCount;
|
|
389
|
-
stats.thinkingStripped += thinkingStripped;
|
|
390
|
-
}
|
|
391
|
-
|
|
392
|
-
// Clean up temp markers
|
|
393
|
-
for (const m of trimmed as any[]) delete m.__trimReadPath;
|
|
394
|
-
for (const m of messages as any[]) delete m.__trimReadPath;
|
|
395
|
-
|
|
396
|
-
if (prunedCount > 0 || dedupedCount > 0 || thinkingStripped > 0 || needsPruning) {
|
|
397
|
-
// Only return if we changed something — otherwise pi keeps original
|
|
398
|
-
return { messages: trimmed };
|
|
399
|
-
}
|
|
400
|
-
});
|
|
401
|
-
|
|
402
|
-
// -------------------------------------------------------------------------
|
|
403
|
-
// 3) CACHING — ensure cache_control on payload (backup to env var)
|
|
404
|
-
// -------------------------------------------------------------------------
|
|
405
|
-
pi.on("before_provider_request", async (event, _ctx) => {
|
|
406
|
-
const payload: any = event.payload;
|
|
407
|
-
|
|
408
|
-
// Anthropic: ensure system and last message have cache_control
|
|
409
|
-
// Pi already does this when PI_CACHE_RETENTION != "none", but we reinforce
|
|
410
|
-
// for proxies / custom providers that may not respect env.
|
|
411
|
-
try {
|
|
412
|
-
if (payload.system && Array.isArray(payload.system)) {
|
|
413
|
-
const lastSystem = payload.system[payload.system.length - 1];
|
|
414
|
-
if (lastSystem && !lastSystem.cache_control) {
|
|
415
|
-
lastSystem.cache_control = { type: "ephemeral", ttl: "1h" };
|
|
416
|
-
}
|
|
417
|
-
}
|
|
418
|
-
if (payload.messages && Array.isArray(payload.messages) && payload.messages.length > 0) {
|
|
419
|
-
// Add cache breakpoint to last user message if missing
|
|
420
|
-
for (let i = payload.messages.length - 1; i >= 0; i--) {
|
|
421
|
-
const m = payload.messages[i];
|
|
422
|
-
if (m.role === "user" && Array.isArray(m.content)) {
|
|
423
|
-
const lastBlock = m.content[m.content.length - 1];
|
|
424
|
-
if (lastBlock && !lastBlock.cache_control) {
|
|
425
|
-
lastBlock.cache_control = { type: "ephemeral", ttl: "1h" };
|
|
426
|
-
break;
|
|
427
|
-
}
|
|
428
|
-
} else if (m.role === "user" && typeof m.content === "string") {
|
|
429
|
-
// Convert string to cached block
|
|
430
|
-
payload.messages[i] = {
|
|
431
|
-
role: "user",
|
|
432
|
-
content: [{ type: "text", text: m.content, cache_control: { type: "ephemeral", ttl: "1h" } }],
|
|
433
|
-
};
|
|
434
|
-
break;
|
|
435
|
-
}
|
|
436
|
-
}
|
|
437
|
-
}
|
|
438
|
-
// For OpenAI-compatible: ensure prompt_cache_key / prompt_cache_retention
|
|
439
|
-
if (payload.model && typeof payload.model === "string") {
|
|
440
|
-
if (!payload.prompt_cache_retention && CONFIG.CACHE_RETENTION === "long") {
|
|
441
|
-
// Only set if provider supports it — harmless otherwise
|
|
442
|
-
payload.prompt_cache_retention = "24h";
|
|
443
|
-
}
|
|
444
|
-
}
|
|
445
|
-
} catch {
|
|
446
|
-
// never break the request
|
|
447
|
-
}
|
|
448
|
-
});
|
|
449
|
-
|
|
450
|
-
// -------------------------------------------------------------------------
|
|
451
|
-
// Command: /trim
|
|
452
|
-
// -------------------------------------------------------------------------
|
|
453
|
-
pi.registerCommand("trim", {
|
|
454
|
-
description: "Toggle trim-context (amp strict) — /trim, /trim on, /trim off, /trim show",
|
|
455
|
-
handler: async (args, ctx) => {
|
|
456
|
-
const arg = (args || "").trim().toLowerCase();
|
|
457
|
-
if (arg === "show") {
|
|
458
|
-
const totalSavedKB = (stats.charsSaved / 1024).toFixed(1);
|
|
459
|
-
ctx.ui.notify(
|
|
460
|
-
`trim-context [${trimEnabled ? "ON" : "OFF"}] amp-strict\n` +
|
|
461
|
-
` toolResults compressed: ${stats.toolResultsCompressed}\n` +
|
|
462
|
-
` context trims: ${stats.contextTrims}\n` +
|
|
463
|
-
` reads deduped: ${stats.readsDeduped}\n` +
|
|
464
|
-
` thinking stripped: ${stats.thinkingStripped}\n` +
|
|
465
|
-
` chars saved: ~${totalSavedKB}KB\n` +
|
|
466
|
-
` config: keep ${CONFIG.KEEP_RECENT_TURNS}t, old→${CONFIG.OLD_MAX_CHARS}ch/${CONFIG.OLD_MAX_LINES}ln, bash ${CONFIG.BASH_IMMEDIATE_MAX_BYTES / 1024}KB/${CONFIG.BASH_IMMEDIATE_MAX_LINES}ln (tail ${CONFIG.OLD_BASH_TAIL_LINES}), generic ${CONFIG.IMMEDIATE_MAX_BYTES / 1024}KB/${CONFIG.IMMEDIATE_MAX_LINES}ln\n` +
|
|
467
|
-
` soft limit: ${CONFIG.SOFT_TOKEN_LIMIT} tokens`,
|
|
468
|
-
"info"
|
|
469
|
-
);
|
|
470
|
-
return;
|
|
471
|
-
}
|
|
472
|
-
if (arg === "on" || arg === "enable" || arg === "enabled") {
|
|
473
|
-
trimEnabled = true;
|
|
474
|
-
ctx.ui.notify("trim-context: ON (amp strict)", "info");
|
|
475
|
-
return;
|
|
476
|
-
}
|
|
477
|
-
if (arg === "off" || arg === "disable" || arg === "disabled") {
|
|
478
|
-
trimEnabled = false;
|
|
479
|
-
ctx.ui.notify("trim-context: OFF — no compression/trimming", "warning");
|
|
480
|
-
return;
|
|
481
|
-
}
|
|
482
|
-
// toggle
|
|
483
|
-
trimEnabled = !trimEnabled;
|
|
484
|
-
ctx.ui.notify(`trim-context: ${trimEnabled ? "ON" : "OFF"}`, trimEnabled ? "info" : "warning");
|
|
485
|
-
},
|
|
486
|
-
});
|
|
487
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* trim-context — pi extension for crush / amp / lsp style context management
|
|
3
|
+
*
|
|
4
|
+
* Does three things:
|
|
5
|
+
* 1. CACHING: forces PI_CACHE_RETENTION=long (1h Anthropic, 24h OpenAI) + ensures
|
|
6
|
+
* Anthropic/OpenAI cache_control breakpoints on system + last messages.
|
|
7
|
+
* Without this pi uses 5m cache which misses on long tasks.
|
|
8
|
+
*
|
|
9
|
+
* 2. OUTPUT COMPRESSION: intercepts tool_result for read/bash/grep/find/ls/edit/write
|
|
10
|
+
* and aggressively truncates large outputs before they are persisted to history.
|
|
11
|
+
* Built-in pi truncates at 50KB/2000 lines - this extension compresses at
|
|
12
|
+
* 30KB/400 lines for recent, and 8KB/100 lines for older via context hook.
|
|
13
|
+
* Full output is saved to temp file and referenced in the compressed result.
|
|
14
|
+
*
|
|
15
|
+
* 3. TRIM CONTEXT (crush/amp/lsp): via `context` event, before every LLM call:
|
|
16
|
+
* - keeps last KEEP_RECENT_TURNS (6) turns verbatim
|
|
17
|
+
* - for older turns: truncates tool results to 800 chars, strips thinking blocks,
|
|
18
|
+
* deduplicates repeated file reads (keeps only last read of same file),
|
|
19
|
+
* compresses old bash outputs to tail-only
|
|
20
|
+
* - if total estimated tokens > SOFT_LIMIT (80k), prunes oldest tool results first
|
|
21
|
+
*
|
|
22
|
+
* Install: lives in ~/.pi/agent/extensions/trim-context/ (auto-discovered)
|
|
23
|
+
* Reload: /reload
|
|
24
|
+
* Command: /trimContext — show stats / toggle
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
28
|
+
import { mkdtempSync, writeFileSync } from "node:fs";
|
|
29
|
+
import { tmpdir } from "node:os";
|
|
30
|
+
import { join } from "node:path";
|
|
31
|
+
|
|
32
|
+
// ---------------------------------------------------------------------------
|
|
33
|
+
// Config — tune here
|
|
34
|
+
// ---------------------------------------------------------------------------
|
|
35
|
+
const CONFIG = {
|
|
36
|
+
// amp strict — keep only last 3 turns verbatim (amp keeps 2-3)
|
|
37
|
+
KEEP_RECENT_TURNS: 3,
|
|
38
|
+
|
|
39
|
+
// output compression thresholds for tool_result hook (immediate)
|
|
40
|
+
IMMEDIATE_MAX_BYTES: 12 * 1024, // 12KB for read/grep/etc (amp strict)
|
|
41
|
+
IMMEDIATE_MAX_LINES: 150,
|
|
42
|
+
// bash is the leak — amp strict: 750 tokens max
|
|
43
|
+
BASH_IMMEDIATE_MAX_BYTES: 3 * 1024, // 3KB ~750 tokens hard cap
|
|
44
|
+
BASH_IMMEDIATE_MAX_LINES: 30,
|
|
45
|
+
|
|
46
|
+
// context hook thresholds for OLD messages (older than KEEP_RECENT_TURNS)
|
|
47
|
+
OLD_MAX_CHARS: 500, // was 800
|
|
48
|
+
OLD_MAX_LINES: 20, // was 30
|
|
49
|
+
OLD_BASH_TAIL_LINES: 8, // was 12 — amp strict tail-only
|
|
50
|
+
|
|
51
|
+
// soft token limit before we start pruning oldest tool results entirely
|
|
52
|
+
SOFT_TOKEN_LIMIT: 50_000, // amp strict ~200KB chars, prune earlier
|
|
53
|
+
HARD_TOKEN_LIMIT: 80_000,
|
|
54
|
+
|
|
55
|
+
// dedupe repeated read()s
|
|
56
|
+
DEDUPE_READS: true,
|
|
57
|
+
|
|
58
|
+
// strip old thinking blocks
|
|
59
|
+
STRIP_OLD_THINKING: true,
|
|
60
|
+
|
|
61
|
+
// caching
|
|
62
|
+
CACHE_RETENTION: "long" as const, // "long" = 1h anthropic, 24h openai
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
// ---------------------------------------------------------------------------
|
|
66
|
+
// Helpers
|
|
67
|
+
// ---------------------------------------------------------------------------
|
|
68
|
+
function estimateTokens(text: string): number {
|
|
69
|
+
return Math.ceil(text.length / 4);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function getTextContent(blocks: Array<{ type: string; text?: string }>): string {
|
|
73
|
+
return blocks
|
|
74
|
+
.filter((b) => b.type === "text" && typeof b.text === "string")
|
|
75
|
+
.map((b) => b.text)
|
|
76
|
+
.join("\n");
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function truncateToLimits(
|
|
80
|
+
text: string,
|
|
81
|
+
maxChars: number,
|
|
82
|
+
maxLines: number,
|
|
83
|
+
label = "truncated"
|
|
84
|
+
): { text: string; truncated: boolean; savedChars: number } {
|
|
85
|
+
const lines = text.split("\n");
|
|
86
|
+
let truncated = false;
|
|
87
|
+
let result = text;
|
|
88
|
+
|
|
89
|
+
if (lines.length > maxLines) {
|
|
90
|
+
// keep head + tail pattern for bash/logs, head-only for reads
|
|
91
|
+
const head = lines.slice(0, Math.floor(maxLines * 0.75));
|
|
92
|
+
const tail = lines.slice(-Math.floor(maxLines * 0.25));
|
|
93
|
+
result = [...head, `\n[... ${lines.length - maxLines} lines ${label} ...]\n`, ...tail].join("\n");
|
|
94
|
+
truncated = true;
|
|
95
|
+
}
|
|
96
|
+
if (result.length > maxChars) {
|
|
97
|
+
const headChars = Math.floor(maxChars * 0.8);
|
|
98
|
+
result =
|
|
99
|
+
result.slice(0, headChars) +
|
|
100
|
+
`\n[... ${result.length - headChars} chars ${label} ...]\n` +
|
|
101
|
+
result.slice(-Math.floor(maxChars * 0.2));
|
|
102
|
+
truncated = true;
|
|
103
|
+
}
|
|
104
|
+
return { text: result, truncated, savedChars: truncated ? text.length - result.length : 0 };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function saveFullOutput(fullText: string, toolName: string): string {
|
|
108
|
+
try {
|
|
109
|
+
const dir = mkdtempSync(join(tmpdir(), `pi-trim-${toolName}-`));
|
|
110
|
+
const file = join(dir, "full-output.txt");
|
|
111
|
+
writeFileSync(file, fullText, "utf8");
|
|
112
|
+
return file;
|
|
113
|
+
} catch {
|
|
114
|
+
return "(failed to save)";
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// Track compression stats across session
|
|
119
|
+
let stats = {
|
|
120
|
+
toolResultsCompressed: 0,
|
|
121
|
+
charsSaved: 0,
|
|
122
|
+
readsDeduped: 0,
|
|
123
|
+
thinkingStripped: 0,
|
|
124
|
+
contextTrims: 0,
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
let trimEnabled = true;
|
|
128
|
+
|
|
129
|
+
// ---------------------------------------------------------------------------
|
|
130
|
+
// Extension
|
|
131
|
+
// ---------------------------------------------------------------------------
|
|
132
|
+
export default function (pi: ExtensionAPI) {
|
|
133
|
+
// Force long cache retention before any provider is created
|
|
134
|
+
if (process.env.PI_CACHE_RETENTION !== "long") {
|
|
135
|
+
process.env.PI_CACHE_RETENTION = CONFIG.CACHE_RETENTION;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
139
|
+
stats = { toolResultsCompressed: 0, charsSaved: 0, readsDeduped: 0, thinkingStripped: 0, contextTrims: 0 };
|
|
140
|
+
// clear legacy statusline from previous version
|
|
141
|
+
ctx.ui.setStatus("trim-context", undefined);
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
pi.on("session_shutdown", async () => {
|
|
145
|
+
stats = { toolResultsCompressed: 0, charsSaved: 0, readsDeduped: 0, thinkingStripped: 0, contextTrims: 0 };
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
// -------------------------------------------------------------------------
|
|
149
|
+
// 1) OUTPUT COMPRESSION — tool_result hook (immediate, before persistence)
|
|
150
|
+
// -------------------------------------------------------------------------
|
|
151
|
+
pi.on("tool_result", async (event, _ctx) => {
|
|
152
|
+
if (!trimEnabled) return;
|
|
153
|
+
const content = event.content as Array<{ type: string; text?: string }>;
|
|
154
|
+
const textBlocks = content.filter((c) => c.type === "text" && typeof c.text === "string");
|
|
155
|
+
if (textBlocks.length === 0) return;
|
|
156
|
+
|
|
157
|
+
const fullText = getTextContent(content as any);
|
|
158
|
+
if (!fullText) return;
|
|
159
|
+
|
|
160
|
+
const lines = fullText.split("\n").length;
|
|
161
|
+
const bytes = Buffer.byteLength(fullText, "utf8");
|
|
162
|
+
|
|
163
|
+
// bash/powershell get much tighter limits — that's your 1-2k leak
|
|
164
|
+
const isBash = event.toolName === "bash" || event.toolName === "powershell";
|
|
165
|
+
const maxBytes = isBash ? CONFIG.BASH_IMMEDIATE_MAX_BYTES : CONFIG.IMMEDIATE_MAX_BYTES;
|
|
166
|
+
const maxLines = isBash ? CONFIG.BASH_IMMEDIATE_MAX_LINES : CONFIG.IMMEDIATE_MAX_LINES;
|
|
167
|
+
|
|
168
|
+
// Also strip ANSI + collapse for bash before measuring (saves 10-20% tokens)
|
|
169
|
+
let textForCheck = fullText;
|
|
170
|
+
if (isBash) {
|
|
171
|
+
// strip ANSI escape codes, collapse 3+ blank lines, trim trailing whitespace per line
|
|
172
|
+
textForCheck = textForCheck.replace(/\x1B\[[0-9;]*[A-Za-z]/g, "").replace(/\n{3,}/g, "\n\n");
|
|
173
|
+
}
|
|
174
|
+
const checkLines = textForCheck.split("\n").length;
|
|
175
|
+
const checkBytes = Buffer.byteLength(textForCheck, "utf8");
|
|
176
|
+
if (checkBytes <= maxBytes && checkLines <= maxLines) {
|
|
177
|
+
// if we stripped ANSI but still under limit, still persist the cleaned version
|
|
178
|
+
if (isBash && textForCheck !== fullText) {
|
|
179
|
+
return { content: [{ type: "text", text: textForCheck }] };
|
|
180
|
+
}
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
// use cleaned text for compression if bash
|
|
184
|
+
const sourceText = isBash ? textForCheck : fullText;
|
|
185
|
+
const sourceLines = sourceText.split("\n").length;
|
|
186
|
+
const sourceBytes = Buffer.byteLength(sourceText, "utf8");
|
|
187
|
+
|
|
188
|
+
const { text: compressed, savedChars } = truncateToLimits(
|
|
189
|
+
sourceText,
|
|
190
|
+
maxBytes,
|
|
191
|
+
maxLines,
|
|
192
|
+
`output compressed by trim-context (${toolNameLabel(event.toolName)})`
|
|
193
|
+
);
|
|
194
|
+
|
|
195
|
+
const fullPath = saveFullOutput(fullText, event.toolName);
|
|
196
|
+
const notice =
|
|
197
|
+
compressed +
|
|
198
|
+
`\n\n[trim-context: ${isBash ? "bash" : event.toolName} compressed from ${(sourceBytes / 1024).toFixed(1)}KB/${sourceLines} lines ` +
|
|
199
|
+
`to ${(Buffer.byteLength(compressed, "utf8") / 1024).toFixed(1)}KB. Full saved to: ${fullPath} — limit ${maxBytes / 1024}KB/${maxLines} lines]`;
|
|
200
|
+
|
|
201
|
+
stats.toolResultsCompressed++;
|
|
202
|
+
stats.charsSaved += savedChars;
|
|
203
|
+
|
|
204
|
+
// Return patch — pi chains these, so we only override content
|
|
205
|
+
return {
|
|
206
|
+
content: [{ type: "text", text: notice }],
|
|
207
|
+
};
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
function toolNameLabel(name: string): string {
|
|
211
|
+
return name || "tool";
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// -------------------------------------------------------------------------
|
|
215
|
+
// 2) TRIM CONTEXT — context hook (crush/amp/lsp style, before each LLM call)
|
|
216
|
+
// -------------------------------------------------------------------------
|
|
217
|
+
pi.on("context", async (event, _ctx) => {
|
|
218
|
+
if (!trimEnabled) return;
|
|
219
|
+
const messages: any[] = event.messages;
|
|
220
|
+
if (messages.length === 0) return;
|
|
221
|
+
|
|
222
|
+
// Identify turn boundaries: each user message starts a turn
|
|
223
|
+
const userIndices: number[] = [];
|
|
224
|
+
for (let i = 0; i < messages.length; i++) {
|
|
225
|
+
if (messages[i].role === "user") userIndices.push(i);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
// Determine cutoff: keep last KEEP_RECENT_TURNS user turns verbatim
|
|
229
|
+
const keepFromUserIdx = Math.max(0, userIndices.length - CONFIG.KEEP_RECENT_TURNS);
|
|
230
|
+
const keepFromMsgIdx = keepFromUserIdx < userIndices.length ? userIndices[keepFromUserIdx] : 0;
|
|
231
|
+
|
|
232
|
+
// For dedupe: find last read of each file path among ALL messages
|
|
233
|
+
const lastReadIndexByPath = new Map<string, number>();
|
|
234
|
+
if (CONFIG.DEDUPE_READS) {
|
|
235
|
+
for (let i = 0; i < messages.length; i++) {
|
|
236
|
+
const m = messages[i];
|
|
237
|
+
if (m.role === "assistant" && Array.isArray(m.content)) {
|
|
238
|
+
for (const block of m.content) {
|
|
239
|
+
if (block.type === "toolCall" && block.name === "read" && block.arguments?.path) {
|
|
240
|
+
const p = String(block.arguments.path);
|
|
241
|
+
lastReadIndexByPath.set(p, i);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
let totalChars = 0;
|
|
249
|
+
for (const m of messages) {
|
|
250
|
+
totalChars += JSON.stringify(m).length;
|
|
251
|
+
}
|
|
252
|
+
const needsPruning = estimateTokens(JSON.stringify(messages)) > CONFIG.SOFT_TOKEN_LIMIT;
|
|
253
|
+
|
|
254
|
+
let prunedCount = 0;
|
|
255
|
+
let dedupedCount = 0;
|
|
256
|
+
let thinkingStripped = 0;
|
|
257
|
+
|
|
258
|
+
const trimmed = messages.map((msg, idx) => {
|
|
259
|
+
const isRecent = idx >= keepFromMsgIdx;
|
|
260
|
+
|
|
261
|
+
// Recent turns: keep verbatim (already compressed by tool_result hook)
|
|
262
|
+
if (isRecent) return msg;
|
|
263
|
+
|
|
264
|
+
// Old turns: apply aggressive trimming
|
|
265
|
+
|
|
266
|
+
// 1) Strip thinking blocks from old assistant messages
|
|
267
|
+
if (CONFIG.STRIP_OLD_THINKING && msg.role === "assistant" && Array.isArray(msg.content)) {
|
|
268
|
+
const origLen = msg.content.length;
|
|
269
|
+
const filtered = msg.content.filter((b: any) => b.type !== "thinking");
|
|
270
|
+
if (filtered.length !== origLen) {
|
|
271
|
+
thinkingStripped++;
|
|
272
|
+
// If we stripped all content and only thinking remained, keep a placeholder
|
|
273
|
+
if (filtered.length === 0) {
|
|
274
|
+
return { ...msg, content: [{ type: "text", text: "[thinking stripped by trim-context]" }] };
|
|
275
|
+
}
|
|
276
|
+
return { ...msg, content: filtered };
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
// 2) Deduplicate old reads: if this read is not the last read of that file, replace toolResult
|
|
281
|
+
if (CONFIG.DEDUPE_READS && msg.role === "assistant" && Array.isArray(msg.content)) {
|
|
282
|
+
for (const block of msg.content) {
|
|
283
|
+
if (block.type === "toolCall" && block.name === "read" && block.arguments?.path) {
|
|
284
|
+
const p = String(block.arguments.path);
|
|
285
|
+
const lastIdx = lastReadIndexByPath.get(p);
|
|
286
|
+
if (lastIdx !== undefined && lastIdx !== idx) {
|
|
287
|
+
// This is an old superseded read — we mark for later toolResult compression
|
|
288
|
+
// We tag the assistant message so the following toolResult can be identified
|
|
289
|
+
(msg as any).__trimReadPath = p;
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
// 3) Compress old toolResults
|
|
296
|
+
if (msg.role === "toolResult" && Array.isArray(msg.content)) {
|
|
297
|
+
const prevMsg = idx > 0 ? messages[idx - 1] : null;
|
|
298
|
+
const isSupersededRead =
|
|
299
|
+
!!(prevMsg as any)?.__trimReadPath ||
|
|
300
|
+
(msg.toolName === "read" && (() => {
|
|
301
|
+
// Check if there's a later read of same file
|
|
302
|
+
const toolInput = (msg as any).toolName === "read" ? (msg as any).input : null;
|
|
303
|
+
// Fallback: check details if available
|
|
304
|
+
return false;
|
|
305
|
+
})());
|
|
306
|
+
|
|
307
|
+
const text = getTextContent(msg.content as any);
|
|
308
|
+
if (!text) return msg;
|
|
309
|
+
|
|
310
|
+
// If superseded read, replace entirely
|
|
311
|
+
if (isSupersededRead || (msg.toolName === "read" && CONFIG.DEDUPE_READS)) {
|
|
312
|
+
// Check if a later read exists for same file by scanning forward for toolCall read with same path
|
|
313
|
+
// We already mapped lastReadIndex — if current toolResult is before last, it's superseded
|
|
314
|
+
// We need to correlate toolResult to its toolCall. Use toolCallId matching.
|
|
315
|
+
// Simpler: if total messages has a later read, compress heavily
|
|
316
|
+
const isOld = true;
|
|
317
|
+
if (isOld && text.length > 200) {
|
|
318
|
+
// Check if any later assistant has a read toolCall
|
|
319
|
+
let hasLaterRead = false;
|
|
320
|
+
for (let j = idx + 1; j < messages.length; j++) {
|
|
321
|
+
const later = messages[j];
|
|
322
|
+
if (later.role === "assistant" && Array.isArray(later.content)) {
|
|
323
|
+
for (const b of later.content) {
|
|
324
|
+
if (b.type === "toolCall" && b.name === "read") {
|
|
325
|
+
// We can't perfectly match path without toolCallId link, but assume if ANY later read exists
|
|
326
|
+
// and this is an old read, it's likely dedupable. Be conservative: only if many reads.
|
|
327
|
+
hasLaterRead = true;
|
|
328
|
+
break;
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
if (hasLaterRead) break;
|
|
333
|
+
}
|
|
334
|
+
if (hasLaterRead && lastReadIndexByPath.size > 1) {
|
|
335
|
+
// Don't aggressively dedupe single-file sessions
|
|
336
|
+
// Instead compress to tiny placeholder
|
|
337
|
+
dedupedCount++;
|
|
338
|
+
return {
|
|
339
|
+
...msg,
|
|
340
|
+
content: [{ type: "text", text: `[trim-context: superseded read — latest version kept later in context]` }],
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
// General old-result compression
|
|
347
|
+
if (text.length > CONFIG.OLD_MAX_CHARS || text.split("\n").length > CONFIG.OLD_MAX_LINES) {
|
|
348
|
+
let compressed: string;
|
|
349
|
+
if (msg.toolName === "bash" || msg.toolName === "powershell") {
|
|
350
|
+
// For bash, keep tail (most recent output matters)
|
|
351
|
+
const lines = text.split("\n");
|
|
352
|
+
const tail = lines.slice(-CONFIG.OLD_BASH_TAIL_LINES);
|
|
353
|
+
const headNote = `[trim-context: old bash output compressed from ${lines.length} lines / ${(text.length / 1024).toFixed(1)}KB to ${tail.length} lines]`;
|
|
354
|
+
compressed = headNote + "\n" + tail.join("\n");
|
|
355
|
+
} else {
|
|
356
|
+
const { text: t } = truncateToLimits(text, CONFIG.OLD_MAX_CHARS, CONFIG.OLD_MAX_LINES, "old result compressed");
|
|
357
|
+
compressed = t + `\n[trim-context: compressed old ${msg.toolName} result]`;
|
|
358
|
+
}
|
|
359
|
+
prunedCount++;
|
|
360
|
+
return { ...msg, content: [{ type: "text", text: compressed }] };
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
return msg;
|
|
365
|
+
});
|
|
366
|
+
|
|
367
|
+
// 4) If still over soft limit, hard-prune oldest toolResults entirely (keep marker)
|
|
368
|
+
if (needsPruning) {
|
|
369
|
+
let estimated = estimateTokens(JSON.stringify(trimmed));
|
|
370
|
+
for (let i = 0; i < trimmed.length && estimated > CONFIG.SOFT_TOKEN_LIMIT; i++) {
|
|
371
|
+
const m = trimmed[i];
|
|
372
|
+
if (m.role === "toolResult" && i < keepFromMsgIdx) {
|
|
373
|
+
const text = getTextContent(m.content as any[]);
|
|
374
|
+
if (text && !text.startsWith("[trim-context:")) {
|
|
375
|
+
trimmed[i] = {
|
|
376
|
+
...m,
|
|
377
|
+
content: [{ type: "text", text: `[trim-context: pruned to save context — was ${(text.length / 1024).toFixed(1)}KB]` }],
|
|
378
|
+
};
|
|
379
|
+
estimated -= estimateTokens(text);
|
|
380
|
+
prunedCount++;
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
if (prunedCount > 0 || dedupedCount > 0 || thinkingStripped > 0) {
|
|
387
|
+
stats.contextTrims++;
|
|
388
|
+
stats.readsDeduped += dedupedCount;
|
|
389
|
+
stats.thinkingStripped += thinkingStripped;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
// Clean up temp markers
|
|
393
|
+
for (const m of trimmed as any[]) delete m.__trimReadPath;
|
|
394
|
+
for (const m of messages as any[]) delete m.__trimReadPath;
|
|
395
|
+
|
|
396
|
+
if (prunedCount > 0 || dedupedCount > 0 || thinkingStripped > 0 || needsPruning) {
|
|
397
|
+
// Only return if we changed something — otherwise pi keeps original
|
|
398
|
+
return { messages: trimmed };
|
|
399
|
+
}
|
|
400
|
+
});
|
|
401
|
+
|
|
402
|
+
// -------------------------------------------------------------------------
|
|
403
|
+
// 3) CACHING — ensure cache_control on payload (backup to env var)
|
|
404
|
+
// -------------------------------------------------------------------------
|
|
405
|
+
pi.on("before_provider_request", async (event, _ctx) => {
|
|
406
|
+
const payload: any = event.payload;
|
|
407
|
+
|
|
408
|
+
// Anthropic: ensure system and last message have cache_control
|
|
409
|
+
// Pi already does this when PI_CACHE_RETENTION != "none", but we reinforce
|
|
410
|
+
// for proxies / custom providers that may not respect env.
|
|
411
|
+
try {
|
|
412
|
+
if (payload.system && Array.isArray(payload.system)) {
|
|
413
|
+
const lastSystem = payload.system[payload.system.length - 1];
|
|
414
|
+
if (lastSystem && !lastSystem.cache_control) {
|
|
415
|
+
lastSystem.cache_control = { type: "ephemeral", ttl: "1h" };
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
if (payload.messages && Array.isArray(payload.messages) && payload.messages.length > 0) {
|
|
419
|
+
// Add cache breakpoint to last user message if missing
|
|
420
|
+
for (let i = payload.messages.length - 1; i >= 0; i--) {
|
|
421
|
+
const m = payload.messages[i];
|
|
422
|
+
if (m.role === "user" && Array.isArray(m.content)) {
|
|
423
|
+
const lastBlock = m.content[m.content.length - 1];
|
|
424
|
+
if (lastBlock && !lastBlock.cache_control) {
|
|
425
|
+
lastBlock.cache_control = { type: "ephemeral", ttl: "1h" };
|
|
426
|
+
break;
|
|
427
|
+
}
|
|
428
|
+
} else if (m.role === "user" && typeof m.content === "string") {
|
|
429
|
+
// Convert string to cached block
|
|
430
|
+
payload.messages[i] = {
|
|
431
|
+
role: "user",
|
|
432
|
+
content: [{ type: "text", text: m.content, cache_control: { type: "ephemeral", ttl: "1h" } }],
|
|
433
|
+
};
|
|
434
|
+
break;
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
// For OpenAI-compatible: ensure prompt_cache_key / prompt_cache_retention
|
|
439
|
+
if (payload.model && typeof payload.model === "string") {
|
|
440
|
+
if (!payload.prompt_cache_retention && CONFIG.CACHE_RETENTION === "long") {
|
|
441
|
+
// Only set if provider supports it — harmless otherwise
|
|
442
|
+
payload.prompt_cache_retention = "24h";
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
} catch {
|
|
446
|
+
// never break the request
|
|
447
|
+
}
|
|
448
|
+
});
|
|
449
|
+
|
|
450
|
+
// -------------------------------------------------------------------------
|
|
451
|
+
// Command: /trim
|
|
452
|
+
// -------------------------------------------------------------------------
|
|
453
|
+
pi.registerCommand("trim", {
|
|
454
|
+
description: "Toggle trim-context (amp strict) — /trim, /trim on, /trim off, /trim show",
|
|
455
|
+
handler: async (args, ctx) => {
|
|
456
|
+
const arg = (args || "").trim().toLowerCase();
|
|
457
|
+
if (arg === "show") {
|
|
458
|
+
const totalSavedKB = (stats.charsSaved / 1024).toFixed(1);
|
|
459
|
+
ctx.ui.notify(
|
|
460
|
+
`trim-context [${trimEnabled ? "ON" : "OFF"}] amp-strict\n` +
|
|
461
|
+
` toolResults compressed: ${stats.toolResultsCompressed}\n` +
|
|
462
|
+
` context trims: ${stats.contextTrims}\n` +
|
|
463
|
+
` reads deduped: ${stats.readsDeduped}\n` +
|
|
464
|
+
` thinking stripped: ${stats.thinkingStripped}\n` +
|
|
465
|
+
` chars saved: ~${totalSavedKB}KB\n` +
|
|
466
|
+
` config: keep ${CONFIG.KEEP_RECENT_TURNS}t, old→${CONFIG.OLD_MAX_CHARS}ch/${CONFIG.OLD_MAX_LINES}ln, bash ${CONFIG.BASH_IMMEDIATE_MAX_BYTES / 1024}KB/${CONFIG.BASH_IMMEDIATE_MAX_LINES}ln (tail ${CONFIG.OLD_BASH_TAIL_LINES}), generic ${CONFIG.IMMEDIATE_MAX_BYTES / 1024}KB/${CONFIG.IMMEDIATE_MAX_LINES}ln\n` +
|
|
467
|
+
` soft limit: ${CONFIG.SOFT_TOKEN_LIMIT} tokens`,
|
|
468
|
+
"info"
|
|
469
|
+
);
|
|
470
|
+
return;
|
|
471
|
+
}
|
|
472
|
+
if (arg === "on" || arg === "enable" || arg === "enabled") {
|
|
473
|
+
trimEnabled = true;
|
|
474
|
+
ctx.ui.notify("trim-context: ON (amp strict)", "info");
|
|
475
|
+
return;
|
|
476
|
+
}
|
|
477
|
+
if (arg === "off" || arg === "disable" || arg === "disabled") {
|
|
478
|
+
trimEnabled = false;
|
|
479
|
+
ctx.ui.notify("trim-context: OFF — no compression/trimming", "warning");
|
|
480
|
+
return;
|
|
481
|
+
}
|
|
482
|
+
// toggle
|
|
483
|
+
trimEnabled = !trimEnabled;
|
|
484
|
+
ctx.ui.notify(`trim-context: ${trimEnabled ? "ON" : "OFF"}`, trimEnabled ? "info" : "warning");
|
|
485
|
+
},
|
|
486
|
+
});
|
|
487
|
+
}
|