@asterxsk/kiln 0.1.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.
Files changed (263) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +170 -0
  3. package/agent/AGENTS.md +67 -0
  4. package/agent/README.md +5 -0
  5. package/agent/extensions/AGENTS.md +68 -0
  6. package/agent/extensions/ask-user/index.ts +418 -0
  7. package/agent/extensions/ask-user/install.ps1 +23 -0
  8. package/agent/extensions/ask-user/install.sh +21 -0
  9. package/agent/extensions/ask-user/package-lock.json +769 -0
  10. package/agent/extensions/ask-user/package.json +19 -0
  11. package/agent/extensions/ask-user/prompt.ts +45 -0
  12. package/agent/extensions/ask-user/tsconfig.json +7 -0
  13. package/agent/extensions/background-terminals/docs/implementation-guide.md +942 -0
  14. package/agent/extensions/background-terminals/index.ts +627 -0
  15. package/agent/extensions/background-terminals/install.ps1 +23 -0
  16. package/agent/extensions/background-terminals/install.sh +21 -0
  17. package/agent/extensions/background-terminals/manager.test.ts +735 -0
  18. package/agent/extensions/background-terminals/output.test.ts +109 -0
  19. package/agent/extensions/background-terminals/package-lock.json +769 -0
  20. package/agent/extensions/background-terminals/package.json +17 -0
  21. package/agent/extensions/background-terminals/prompt.test.ts +125 -0
  22. package/agent/extensions/background-terminals/ps.test.ts +82 -0
  23. package/agent/extensions/background-terminals/result-delivery.test.ts +44 -0
  24. package/agent/extensions/background-terminals/src/domain.ts +87 -0
  25. package/agent/extensions/background-terminals/src/manager.ts +907 -0
  26. package/agent/extensions/background-terminals/src/output.ts +84 -0
  27. package/agent/extensions/background-terminals/src/prompt.ts +142 -0
  28. package/agent/extensions/background-terminals/src/result-delivery.ts +27 -0
  29. package/agent/extensions/background-terminals/src/runtime.ts +36 -0
  30. package/agent/extensions/background-terminals/src/ui/output-view.ts +79 -0
  31. package/agent/extensions/background-terminals/src/ui/ps.ts +621 -0
  32. package/agent/extensions/background-terminals/tsconfig.json +7 -0
  33. package/agent/extensions/destructive/README.md +31 -0
  34. package/agent/extensions/destructive/index.ts +88 -0
  35. package/agent/extensions/destructive/install.ps1 +23 -0
  36. package/agent/extensions/destructive/install.sh +21 -0
  37. package/agent/extensions/file-search/index.spec.ts +443 -0
  38. package/agent/extensions/file-search/index.ts +459 -0
  39. package/agent/extensions/file-search/install.ps1 +23 -0
  40. package/agent/extensions/file-search/install.sh +21 -0
  41. package/agent/extensions/file-search/package-lock.json +2253 -0
  42. package/agent/extensions/file-search/package.json +23 -0
  43. package/agent/extensions/file-search/src/args.ts +122 -0
  44. package/agent/extensions/file-search/src/binaries.ts +422 -0
  45. package/agent/extensions/file-search/src/output.ts +126 -0
  46. package/agent/extensions/file-search/src/process.ts +146 -0
  47. package/agent/extensions/file-search/src/prompt.ts +52 -0
  48. package/agent/extensions/file-search/tsconfig.json +7 -0
  49. package/agent/extensions/goal/README.md +50 -0
  50. package/agent/extensions/goal/index.ts +155 -0
  51. package/agent/extensions/goal/install.ps1 +23 -0
  52. package/agent/extensions/goal/install.sh +21 -0
  53. package/agent/extensions/modelconf/PLAN.md +915 -0
  54. package/agent/extensions/modelconf/README.md +66 -0
  55. package/agent/extensions/modelconf/index.ts +296 -0
  56. package/agent/extensions/modelconf/install.ps1 +23 -0
  57. package/agent/extensions/modelconf/install.sh +21 -0
  58. package/agent/extensions/modelconf/package-lock.json +1809 -0
  59. package/agent/extensions/modelconf/package.json +13 -0
  60. package/agent/extensions/modelconf/src/fuzzy.ts +26 -0
  61. package/agent/extensions/modelconf/src/glob.ts +13 -0
  62. package/agent/extensions/modelconf/src/persistence.test.ts +46 -0
  63. package/agent/extensions/modelconf/src/persistence.ts +164 -0
  64. package/agent/extensions/modelconf/src/ui/ModelConfView.test.ts +75 -0
  65. package/agent/extensions/modelconf/src/ui/ModelConfView.ts +1101 -0
  66. package/agent/extensions/modelconf/tsconfig.json +15 -0
  67. package/agent/extensions/pi-web-access/CHANGELOG.md +690 -0
  68. package/agent/extensions/pi-web-access/LICENSE +21 -0
  69. package/agent/extensions/pi-web-access/README.md +470 -0
  70. package/agent/extensions/pi-web-access/SECURITY.md +5 -0
  71. package/agent/extensions/pi-web-access/activity.ts +101 -0
  72. package/agent/extensions/pi-web-access/auth-fetch.ts +148 -0
  73. package/agent/extensions/pi-web-access/banner.png +0 -0
  74. package/agent/extensions/pi-web-access/brightdata-unlocker.ts +272 -0
  75. package/agent/extensions/pi-web-access/chrome-cookies.ts +669 -0
  76. package/agent/extensions/pi-web-access/content-find.ts +139 -0
  77. package/agent/extensions/pi-web-access/credential-source.ts +191 -0
  78. package/agent/extensions/pi-web-access/data-uri-sanitize.ts +406 -0
  79. package/agent/extensions/pi-web-access/datalab-pdf-extract.ts +568 -0
  80. package/agent/extensions/pi-web-access/declared-web-links.ts +173 -0
  81. package/agent/extensions/pi-web-access/evidence/CONTRACT-EVIDENCE.md +496 -0
  82. package/agent/extensions/pi-web-access/evidence/contract-probe.mjs +140 -0
  83. package/agent/extensions/pi-web-access/exa.ts +526 -0
  84. package/agent/extensions/pi-web-access/extract.ts +1196 -0
  85. package/agent/extensions/pi-web-access/feature-config.ts +29 -0
  86. package/agent/extensions/pi-web-access/fetch-params.ts +111 -0
  87. package/agent/extensions/pi-web-access/gemini-adc.ts +298 -0
  88. package/agent/extensions/pi-web-access/gemini-api.ts +353 -0
  89. package/agent/extensions/pi-web-access/gemini-pdf-extract.ts +108 -0
  90. package/agent/extensions/pi-web-access/gemini-search.ts +21 -0
  91. package/agent/extensions/pi-web-access/gemini-url-context.ts +128 -0
  92. package/agent/extensions/pi-web-access/gemini-web-config.ts +101 -0
  93. package/agent/extensions/pi-web-access/gemini-web.ts +487 -0
  94. package/agent/extensions/pi-web-access/github-api.ts +197 -0
  95. package/agent/extensions/pi-web-access/github-extract.ts +746 -0
  96. package/agent/extensions/pi-web-access/github-issue-pr.ts +700 -0
  97. package/agent/extensions/pi-web-access/index.ts +1737 -0
  98. package/agent/extensions/pi-web-access/package-lock.json +5808 -0
  99. package/agent/extensions/pi-web-access/package.json +64 -0
  100. package/agent/extensions/pi-web-access/page-query.ts +96 -0
  101. package/agent/extensions/pi-web-access/pdf-extract.ts +409 -0
  102. package/agent/extensions/pi-web-access/pi-web-fetch-demo.mp4 +0 -0
  103. package/agent/extensions/pi-web-access/promise-try.d.ts +7 -0
  104. package/agent/extensions/pi-web-access/query-rewrite.ts +51 -0
  105. package/agent/extensions/pi-web-access/render-search-error.ts +170 -0
  106. package/agent/extensions/pi-web-access/rsc-extract.ts +338 -0
  107. package/agent/extensions/pi-web-access/search-types.ts +20 -0
  108. package/agent/extensions/pi-web-access/source-check.ts +282 -0
  109. package/agent/extensions/pi-web-access/ssrf-protection.ts +526 -0
  110. package/agent/extensions/pi-web-access/storage.ts +521 -0
  111. package/agent/extensions/pi-web-access/summary-model-scope.ts +125 -0
  112. package/agent/extensions/pi-web-access/test/auth-fetch.test.mjs +208 -0
  113. package/agent/extensions/pi-web-access/test/brightdata-unlocker.test.mjs +840 -0
  114. package/agent/extensions/pi-web-access/test/chrome-cookie-extraction.test.mjs +441 -0
  115. package/agent/extensions/pi-web-access/test/config-path.test.mjs +283 -0
  116. package/agent/extensions/pi-web-access/test/content-find.test.mjs +25 -0
  117. package/agent/extensions/pi-web-access/test/credential-source.test.mjs +118 -0
  118. package/agent/extensions/pi-web-access/test/data-uri-sanitize.test.mjs +210 -0
  119. package/agent/extensions/pi-web-access/test/datalab-pdf-extract.test.mjs +552 -0
  120. package/agent/extensions/pi-web-access/test/declared-web-links.test.mjs +212 -0
  121. package/agent/extensions/pi-web-access/test/fetch-answer-storage.test.mjs +40 -0
  122. package/agent/extensions/pi-web-access/test/fetch-cache-storage.test.mjs +334 -0
  123. package/agent/extensions/pi-web-access/test/fetch-content-domain-policy.test.mjs +95 -0
  124. package/agent/extensions/pi-web-access/test/fetch-modes.test.mjs +53 -0
  125. package/agent/extensions/pi-web-access/test/fetch-not-found-guidance.test.mjs +92 -0
  126. package/agent/extensions/pi-web-access/test/fetch-params.test.mjs +86 -0
  127. package/agent/extensions/pi-web-access/test/fetch-render-call.test.mjs +34 -0
  128. package/agent/extensions/pi-web-access/test/fetch-routing.test.mjs +173 -0
  129. package/agent/extensions/pi-web-access/test/gemini-adc-auth.test.mjs +257 -0
  130. package/agent/extensions/pi-web-access/test/gemini-api-transport.test.mjs +170 -0
  131. package/agent/extensions/pi-web-access/test/gemini-pdf-extract.test.mjs +133 -0
  132. package/agent/extensions/pi-web-access/test/gemini-web-cookie-opt-in.test.mjs +178 -0
  133. package/agent/extensions/pi-web-access/test/gemini-web-header-overflow.test.mjs +148 -0
  134. package/agent/extensions/pi-web-access/test/get-search-content.test.mjs +223 -0
  135. package/agent/extensions/pi-web-access/test/github-extract.test.mjs +378 -0
  136. package/agent/extensions/pi-web-access/test/github-issue-pr.test.mjs +565 -0
  137. package/agent/extensions/pi-web-access/test/inline-content-config.test.mjs +99 -0
  138. package/agent/extensions/pi-web-access/test/lazy-extract-load.test.mjs +118 -0
  139. package/agent/extensions/pi-web-access/test/local-video-oversize.test.mjs +52 -0
  140. package/agent/extensions/pi-web-access/test/package-typebox-dependency.test.mjs +50 -0
  141. package/agent/extensions/pi-web-access/test/page-query.test.mjs +51 -0
  142. package/agent/extensions/pi-web-access/test/pdf-config.test.mjs +140 -0
  143. package/agent/extensions/pi-web-access/test/pdf-extract.test.mjs +500 -0
  144. package/agent/extensions/pi-web-access/test/proxy-transport.test.mjs +286 -0
  145. package/agent/extensions/pi-web-access/test/query-rewrite.test.mjs +52 -0
  146. package/agent/extensions/pi-web-access/test/rsc-fallback.test.mjs +102 -0
  147. package/agent/extensions/pi-web-access/test/search-error-render.test.mjs +152 -0
  148. package/agent/extensions/pi-web-access/test/search-providers.test.mjs +274 -0
  149. package/agent/extensions/pi-web-access/test/source-check.test.mjs +179 -0
  150. package/agent/extensions/pi-web-access/test/ssrf-allow-ranges-config.test.mjs +205 -0
  151. package/agent/extensions/pi-web-access/test/ssrf-protection.test.mjs +456 -0
  152. package/agent/extensions/pi-web-access/test/summary-model-scope.test.mjs +106 -0
  153. package/agent/extensions/pi-web-access/test/tool-registration-config.test.mjs +182 -0
  154. package/agent/extensions/pi-web-access/test/web-search-answer-render.test.mjs +66 -0
  155. package/agent/extensions/pi-web-access/test/youtube-extract-errors.test.mjs +64 -0
  156. package/agent/extensions/pi-web-access/tsconfig.json +11 -0
  157. package/agent/extensions/pi-web-access/utils.ts +451 -0
  158. package/agent/extensions/pi-web-access/video-extract.ts +392 -0
  159. package/agent/extensions/pi-web-access/youtube-extract.ts +328 -0
  160. package/agent/extensions/shared/activity-status.ts +31 -0
  161. package/agent/extensions/shared/child-session.test.ts +270 -0
  162. package/agent/extensions/shared/child-session.ts +148 -0
  163. package/agent/extensions/shared/context-utilization.test.ts +48 -0
  164. package/agent/extensions/shared/context-utilization.ts +47 -0
  165. package/agent/extensions/shared/dashboard-state.ts +99 -0
  166. package/agent/extensions/shared/install.ps1 +23 -0
  167. package/agent/extensions/shared/install.sh +21 -0
  168. package/agent/extensions/shared/tool-call-timeout.test.ts +117 -0
  169. package/agent/extensions/shared/tool-call-timeout.ts +104 -0
  170. package/agent/extensions/skillsconf/README.md +74 -0
  171. package/agent/extensions/skillsconf/index.ts +92 -0
  172. package/agent/extensions/skillsconf/install.ps1 +23 -0
  173. package/agent/extensions/skillsconf/install.sh +21 -0
  174. package/agent/extensions/skillsconf/package-lock.json +1809 -0
  175. package/agent/extensions/skillsconf/package.json +18 -0
  176. package/agent/extensions/skillsconf/src/delete-skill.test.ts +64 -0
  177. package/agent/extensions/skillsconf/src/delete-skill.ts +45 -0
  178. package/agent/extensions/skillsconf/src/filter.test.ts +80 -0
  179. package/agent/extensions/skillsconf/src/filter.ts +74 -0
  180. package/agent/extensions/skillsconf/src/fuzzy.ts +26 -0
  181. package/agent/extensions/skillsconf/src/persistence.test.ts +72 -0
  182. package/agent/extensions/skillsconf/src/persistence.ts +169 -0
  183. package/agent/extensions/skillsconf/src/ui/SkillConfView.test.ts +337 -0
  184. package/agent/extensions/skillsconf/src/ui/SkillConfView.ts +758 -0
  185. package/agent/extensions/skillsconf/src/ui/text-input.ts +91 -0
  186. package/agent/extensions/skillsconf/src/ui/tui-helpers.ts +144 -0
  187. package/agent/extensions/skillsconf/tsconfig.json +15 -0
  188. package/agent/extensions/status line/index.ts +282 -0
  189. package/agent/extensions/status line/install.ps1 +23 -0
  190. package/agent/extensions/status line/install.sh +21 -0
  191. package/agent/extensions/subagents/by-the-way.test.ts +29 -0
  192. package/agent/extensions/subagents/claude.test.ts +119 -0
  193. package/agent/extensions/subagents/codex.test.ts +102 -0
  194. package/agent/extensions/subagents/context-usage.test.ts +107 -0
  195. package/agent/extensions/subagents/docs/design-plan.md +568 -0
  196. package/agent/extensions/subagents/docs/effect-v4-extension-guide.md +354 -0
  197. package/agent/extensions/subagents/docs/effect-v4-notes.md +571 -0
  198. package/agent/extensions/subagents/index.ts +779 -0
  199. package/agent/extensions/subagents/install.ps1 +23 -0
  200. package/agent/extensions/subagents/install.sh +21 -0
  201. package/agent/extensions/subagents/manager.test.ts +276 -0
  202. package/agent/extensions/subagents/package-lock.json +2244 -0
  203. package/agent/extensions/subagents/package.json +19 -0
  204. package/agent/extensions/subagents/result-delivery.test.ts +27 -0
  205. package/agent/extensions/subagents/src/backend.ts +73 -0
  206. package/agent/extensions/subagents/src/backends/claude.ts +701 -0
  207. package/agent/extensions/subagents/src/backends/codex.ts +1060 -0
  208. package/agent/extensions/subagents/src/backends/pi.ts +575 -0
  209. package/agent/extensions/subagents/src/backends/stub.ts +300 -0
  210. package/agent/extensions/subagents/src/by-the-way.ts +21 -0
  211. package/agent/extensions/subagents/src/domain.ts +253 -0
  212. package/agent/extensions/subagents/src/format.ts +74 -0
  213. package/agent/extensions/subagents/src/manager.ts +736 -0
  214. package/agent/extensions/subagents/src/prompt.ts +92 -0
  215. package/agent/extensions/subagents/src/result-delivery.ts +20 -0
  216. package/agent/extensions/subagents/src/runtime.ts +53 -0
  217. package/agent/extensions/subagents/src/ui/takeover.ts +583 -0
  218. package/agent/extensions/subagents/src/ui/transcript.ts +201 -0
  219. package/agent/extensions/subagents/takeover.test.ts +29 -0
  220. package/agent/extensions/subagents/tsconfig.json +7 -0
  221. package/agent/extensions/taste/index.ts +443 -0
  222. package/agent/extensions/taste/install.ps1 +23 -0
  223. package/agent/extensions/taste/install.sh +21 -0
  224. package/agent/extensions/todo/AGENTS.md +38 -0
  225. package/agent/extensions/todo/LICENSE +21 -0
  226. package/agent/extensions/todo/config.ts +55 -0
  227. package/agent/extensions/todo/index.ts +151 -0
  228. package/agent/extensions/todo/install.ps1 +23 -0
  229. package/agent/extensions/todo/install.sh +21 -0
  230. package/agent/extensions/todo/locales/de.json +17 -0
  231. package/agent/extensions/todo/locales/en.json +15 -0
  232. package/agent/extensions/todo/locales/es.json +17 -0
  233. package/agent/extensions/todo/locales/fr.json +17 -0
  234. package/agent/extensions/todo/locales/pt-BR.json +17 -0
  235. package/agent/extensions/todo/locales/pt.json +17 -0
  236. package/agent/extensions/todo/locales/ru.json +17 -0
  237. package/agent/extensions/todo/locales/uk.json +17 -0
  238. package/agent/extensions/todo/locales/zh.json +17 -0
  239. package/agent/extensions/todo/package-lock.json +3358 -0
  240. package/agent/extensions/todo/package.json +67 -0
  241. package/agent/extensions/todo/state/i18n-bridge.ts +64 -0
  242. package/agent/extensions/todo/state/invariants.ts +20 -0
  243. package/agent/extensions/todo/state/replay.ts +38 -0
  244. package/agent/extensions/todo/state/selectors.ts +107 -0
  245. package/agent/extensions/todo/state/state-reducer.ts +326 -0
  246. package/agent/extensions/todo/state/state.ts +18 -0
  247. package/agent/extensions/todo/state/store.ts +82 -0
  248. package/agent/extensions/todo/state/task-graph.ts +57 -0
  249. package/agent/extensions/todo/todo-overlay.ts +200 -0
  250. package/agent/extensions/todo/todo.ts +155 -0
  251. package/agent/extensions/todo/tool/response-envelope.ts +109 -0
  252. package/agent/extensions/todo/tool/types.ts +206 -0
  253. package/agent/extensions/todo/verify-ref-system.js +0 -0
  254. package/agent/extensions/todo/view/format.ts +177 -0
  255. package/agent/extensions/trim-context/README.md +54 -0
  256. package/agent/extensions/trim-context/index.ts +487 -0
  257. package/agent/extensions/trim-context/install.ps1 +23 -0
  258. package/agent/extensions/trim-context/install.sh +21 -0
  259. package/agent/install.ps1 +527 -0
  260. package/agent/install.sh +511 -0
  261. package/agent/keybindings.json +7 -0
  262. package/bin/kiln.js +359 -0
  263. package/package.json +21 -0
@@ -0,0 +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
+ }
@@ -0,0 +1,23 @@
1
+ #!/usr/bin/env pwsh
2
+ # Per-extension installer — Windows / PowerShell
3
+ # Installs npm dependencies for this extension. No-op if no package.json.
4
+ $ErrorActionPreference = "Stop"
5
+ $extDir = $PSScriptRoot
6
+ if (-not $extDir) { $extDir = Split-Path -Parent $MyInvocation.MyCommand.Path }
7
+ if (-not (Test-Path "$extDir/package.json")) {
8
+ Write-Host " - no package.json — skipping" -ForegroundColor DarkGray
9
+ exit 0
10
+ }
11
+ if (-not (Get-Command npm -ErrorAction SilentlyContinue)) {
12
+ Write-Host " x npm not found — install Node.js 22+" -ForegroundColor Red
13
+ exit 1
14
+ }
15
+ if (Test-Path "$extDir/package-lock.json") {
16
+ Write-Host " - npm ci" -ForegroundColor DarkGray
17
+ npm --prefix $extDir ci --no-audit --no-fund
18
+ } else {
19
+ Write-Host " - npm install" -ForegroundColor DarkGray
20
+ npm --prefix $extDir install --no-audit --no-fund
21
+ }
22
+ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
23
+ Write-Host " + done" -ForegroundColor Green
@@ -0,0 +1,21 @@
1
+ #!/bin/sh
2
+ # Per-extension installer — macOS / Linux
3
+ # Installs npm dependencies for this extension. No-op if no package.json.
4
+ set -eu
5
+ EXT_DIR="$(cd "$(dirname "$0")" && pwd)"
6
+ if [ ! -f "$EXT_DIR/package.json" ]; then
7
+ echo " · no package.json — skipping"
8
+ exit 0
9
+ fi
10
+ if ! command -v npm >/dev/null 2>&1; then
11
+ echo " ✖ npm not found — install Node.js 22+" >&2
12
+ exit 1
13
+ fi
14
+ if [ -f "$EXT_DIR/package-lock.json" ]; then
15
+ echo " · npm ci"
16
+ npm --prefix "$EXT_DIR" ci --no-audit --no-fund
17
+ else
18
+ echo " · npm install"
19
+ npm --prefix "$EXT_DIR" install --no-audit --no-fund
20
+ fi
21
+ echo " ✓ done"