@izhimu/pi-caveman 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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 izhimu
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,141 @@
1
+ # pi-caveman
2
+
3
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
4
+ [![pi extension](https://img.shields.io/badge/pi-extension-green.svg)](https://github.com/earendil-works/pi)
5
+
6
+ Caveman mode for [pi](https://github.com/earendil-works/pi). Ultra-compressed communication — cuts **65% output tokens** (measured), full technical accuracy.
7
+
8
+ Upstream: [JuliusBrussee/caveman](https://github.com/JuliusBrussee/caveman)
9
+
10
+ ## Features
11
+
12
+ - **Auto-activates** on every pi session (default: `full` intensity)
13
+ - **6 intensity levels** — from lite (professional but tight) to wenyan-ultra (classical Chinese extreme compression)
14
+ - **Per-turn reinforcement** keeps model in caveman mode even after context compression
15
+ - **Natural language triggers** — "talk like caveman", "be brief", "stop caveman"
16
+ - **Status bar** shows current mode with color-coded indicator
17
+ - **Configurable** via env var, repo-local, or user-global config
18
+ - **Token savings stats** — tracks and displays estimated savings per session
19
+
20
+ ## Install
21
+
22
+ ### From git (recommended)
23
+
24
+ ```bash
25
+ # Global
26
+ pi install git:github.com/izhimu/pi-caveman
27
+
28
+ # Project-local (shared with team via .pi/settings.json)
29
+ pi install git:github.com/izhimu/pi-caveman -l
30
+ ```
31
+
32
+ ### From local path
33
+
34
+ ```bash
35
+ pi install /path/to/pi-caveman
36
+ pi install ./relative/path/to/pi-caveman
37
+ ```
38
+
39
+ ### Quick test (no install)
40
+
41
+ ```bash
42
+ pi -e ./extensions/caveman.ts
43
+ ```
44
+
45
+ ## Commands
46
+
47
+ | Command | Effect |
48
+ |---------|--------|
49
+ | `/caveman` | Activate with default mode |
50
+ | `/caveman lite` | Lite mode — no filler, keep articles |
51
+ | `/caveman full` | Full mode — fragments OK, short synonyms |
52
+ | `/caveman ultra` | Ultra mode — one word when one word enough |
53
+ | `/caveman wenyan` | 文言文 mode (classical Chinese) |
54
+ | `/caveman off` | Deactivate |
55
+ | `/caveman-config` | Show/set default mode |
56
+ | `/caveman-off` | Convenience alias for `/caveman off` |
57
+ | `/caveman-status` | Show current mode and config |
58
+
59
+ Natural-language triggers also work: "talk like caveman", "stop caveman", "normal mode".
60
+
61
+ ## Intensity Levels
62
+
63
+ | Level | Description |
64
+ |-------|-------------|
65
+ | **lite** | No filler/hedging. Keep articles + full sentences. Professional but tight |
66
+ | **full** | Drop articles, fragments OK, short synonyms. Classic caveman |
67
+ | **ultra** | Strip conjunctions. One word when one word enough |
68
+ | **wenyan-lite** | Semi-classical Chinese. Drop filler but keep grammar structure |
69
+ | **wenyan-full** | Maximum classical Chinese terseness. 80-90% character reduction |
70
+ | **wenyan-ultra** | Extreme abbreviation with classical Chinese feel |
71
+
72
+ ### Examples
73
+
74
+ **Q: "Why React component re-render?"**
75
+
76
+ - **lite:** "Your component re-renders because you create a new object reference each render. Wrap it in `useMemo`."
77
+ - **full:** "New object ref each render. Inline object prop = new ref = re-render. Wrap in `useMemo`."
78
+ - **ultra:** "Inline obj prop, new ref, re-render. `useMemo`."
79
+ - **wenyan-full:** "每繪新生對象參照,故重繪;以 useMemo 包之則免。"
80
+
81
+ ## Configuration
82
+
83
+ Quickest way: `/caveman-config ultra` — writes user config, shows all available modes.
84
+
85
+ Default mode resolution order:
86
+
87
+ 1. `CAVEMAN_DEFAULT_MODE` environment variable
88
+ 2. Repo-local: `.caveman/config.json` or `.caveman.json` (walks up to root)
89
+ 3. User: `~/.config/caveman/config.json` (or `%APPDATA%\caveman\config.json` on Windows)
90
+ 4. `full` (fallback)
91
+
92
+ Manual config:
93
+ ```json
94
+ {
95
+ "defaultMode": "ultra"
96
+ }
97
+ ```
98
+
99
+ ## How It Works
100
+
101
+ pi loads extensions from `~/.pi/agent/extensions/` and `.pi/extensions/`. This extension hooks into four lifecycle events:
102
+
103
+ 1. **`session_start`** — writes mode flag, notifies user
104
+ 2. **`before_agent_start`** — injects reinforcement line per turn
105
+ 3. **`input`** — intercepts `/caveman` commands and natural-language triggers
106
+ 4. **`turn_end`** — updates status bar with savings stats
107
+
108
+ The `SKILL.md` in `skills/caveman/` is auto-discovered by pi's skill system and loaded into system context.
109
+
110
+ ## Project Structure
111
+
112
+ ```
113
+ pi-caveman/
114
+ ├── extensions/
115
+ │ └── caveman.ts # pi ExtensionAPI integration
116
+ ├── skills/
117
+ │ └── caveman/
118
+ │ └── SKILL.md # Caveman behavior rules
119
+ ├── package.json # pi package manifest
120
+ ├── tsconfig.json
121
+ ├── LICENSE
122
+ └── README.md
123
+ ```
124
+
125
+ ## Flag File
126
+
127
+ Mode state persisted at `~/.pi/.caveman-active`. Mode transitions logged to `~/.pi/.caveman-mode-log.jsonl`.
128
+
129
+ ## Contributing
130
+
131
+ Contributions welcome! Please:
132
+
133
+ 1. Fork the repository
134
+ 2. Create a feature branch (`git checkout -b feat/amazing-feature`)
135
+ 3. Commit your changes (`git commit -m 'feat: add amazing feature'`)
136
+ 4. Push to the branch (`git push origin feat/amazing-feature`)
137
+ 5. Open a Pull Request
138
+
139
+ ## License
140
+
141
+ [MIT](LICENSE) © [izhimu](https://github.com/izhimu)
@@ -0,0 +1,629 @@
1
+ // pi-caveman — pi extension
2
+ //
3
+ // Caveman mode for pi: auto-activates per session, /caveman commands,
4
+ // per-turn reinforcement injection, status bar integration.
5
+ //
6
+ // Flag file: ~/.pi/.caveman-active
7
+ // Config: ~/.config/caveman/config.json or CAVEMAN_DEFAULT_MODE env
8
+ // Upstream: https://github.com/JuliusBrussee/caveman
9
+
10
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
11
+ import {
12
+ existsSync, mkdirSync, readFileSync,
13
+ writeFileSync, unlinkSync, appendFileSync, renameSync,
14
+ } from "node:fs";
15
+ import { join, dirname, sep } from "node:path";
16
+ import { homedir } from "node:os";
17
+ import { fileURLToPath } from "node:url";
18
+
19
+ // ES module __dirname equivalent
20
+ const __filename = fileURLToPath(import.meta.url);
21
+ const __dirname = dirname(__filename);
22
+
23
+ // ── Constants ───────────────────────────────────────────────────────────────
24
+
25
+ const VALID_MODES = [
26
+ "lite", "full", "ultra",
27
+ "wenyan-lite", "wenyan", "wenyan-full", "wenyan-ultra",
28
+ "commit", "review", "compress",
29
+ ] as const;
30
+
31
+ type Mode = (typeof VALID_MODES)[number];
32
+
33
+ // Modes with independent skills — not caveman intensity levels
34
+ const INDEPENDENT: Record<string, true> = {
35
+ commit: true, review: true, compress: true,
36
+ };
37
+
38
+ // ── Session stats ───────────────────────────────────────────────────────────
39
+
40
+ interface SessionStats {
41
+ turns: number;
42
+ outputTokens: number;
43
+ cacheReadTokens: number;
44
+ inputTokens: number;
45
+ }
46
+
47
+ let sessionStats: SessionStats = {
48
+ turns: 0, outputTokens: 0, cacheReadTokens: 0, inputTokens: 0,
49
+ };
50
+
51
+ let sessionExplicitOff = false;
52
+
53
+ const COMPRESSION_RATIOS: Record<string, number> = {
54
+ 'full': 0.65,
55
+ 'lite': 0.35,
56
+ 'ultra': 0.75,
57
+ 'wenyan': 0.80,
58
+ 'wenyan-lite': 0.60,
59
+ 'wenyan-ultra': 0.85,
60
+ };
61
+
62
+ function estimateSavings(outputTokens: number, mode: string) {
63
+ const ratio = COMPRESSION_RATIOS[mode];
64
+ if (!ratio) return null;
65
+ const estWithout = Math.round(outputTokens / (1 - ratio));
66
+ const estSaved = estWithout - outputTokens;
67
+ return { estWithout, estSaved, pct: Math.round(ratio * 100) };
68
+ }
69
+
70
+ // ── Display helpers ────────────────────────────────────────────────────────
71
+
72
+ const ESC = "\x1b[";
73
+ const RST = `${ESC}0m`;
74
+ const DIM = `${ESC}2m`;
75
+ const BOLD = `${ESC}1m`;
76
+ const GREEN = `${ESC}32m`;
77
+ const YELLOW = `${ESC}33m`;
78
+ const RED = `${ESC}31m`;
79
+ const CYAN = `${ESC}36m`;
80
+ const GRAY = `${ESC}90m`;
81
+
82
+ function modeColor(mode: string): string {
83
+ if (mode === "off") return GRAY;
84
+ if (mode.startsWith("wenyan")) return CYAN;
85
+ if (mode === "lite") return YELLOW;
86
+ return GREEN; // full, ultra
87
+ }
88
+
89
+ function bar(pct: number, width = 20): string {
90
+ const filled = Math.round((pct / 100) * width);
91
+ return "█".repeat(filled) + "░".repeat(width - filled);
92
+ }
93
+
94
+ function truncatePath(p: string, max = 40): string {
95
+ if (p.length <= max) return p;
96
+ const parts = p.split(sep);
97
+ const tail = parts.slice(-2).join(sep);
98
+ return "…" + sep + tail;
99
+ }
100
+
101
+ // ── Paths ───────────────────────────────────────────────────────────────────
102
+
103
+ const xdg = process.env.XDG_CONFIG_HOME;
104
+ const piDir = xdg ? join(xdg, "pi") : join(homedir(), ".pi");
105
+ const flagPath = join(piDir, ".caveman-active");
106
+
107
+ // ── Config resolution (mirrors caveman/src/hooks/caveman-config.js) ─────────
108
+
109
+ function cavemanConfigDir(): string {
110
+ const xdgHome = process.env.XDG_CONFIG_HOME;
111
+ if (xdgHome) return join(xdgHome, "caveman");
112
+ if (process.platform === "win32") {
113
+ return join(
114
+ process.env.APPDATA || join(homedir(), "AppData", "Roaming"),
115
+ "caveman",
116
+ );
117
+ }
118
+ return join(homedir(), ".config", "caveman");
119
+ }
120
+
121
+ function findRepoConfig(start: string): string | null {
122
+ let dir = start;
123
+ for (let i = 0; i < 64; i++) {
124
+ const a = join(dir, ".caveman", "config.json");
125
+ if (existsSync(a)) return a;
126
+ const b = join(dir, ".caveman.json");
127
+ if (existsSync(b)) return b;
128
+ const parent = dirname(dir);
129
+ if (parent === dir) break;
130
+ dir = parent;
131
+ }
132
+ return null;
133
+ }
134
+
135
+ function readConfigMode(configPath: string): string | null {
136
+ try {
137
+ const parsed = JSON.parse(readFileSync(configPath, "utf-8"));
138
+ const m = parsed?.defaultMode;
139
+ return typeof m === "string" ? m : null;
140
+ } catch {
141
+ return null;
142
+ }
143
+ }
144
+
145
+ function isValidMode(m: string): m is Mode {
146
+ return (VALID_MODES as readonly string[]).includes(m);
147
+ }
148
+
149
+ function resolveDefault(): string {
150
+ // 1. Env var (short-circuits)
151
+ const env = process.env.CAVEMAN_DEFAULT_MODE;
152
+ if (env) {
153
+ const lower = env.toLowerCase();
154
+ if (isValidMode(lower) || lower === "off") return lower;
155
+ }
156
+ // 2. Repo-local config
157
+ const repo = findRepoConfig(process.cwd());
158
+ if (repo) {
159
+ const m = readConfigMode(repo);
160
+ if (m) {
161
+ const lower = m.toLowerCase();
162
+ if (isValidMode(lower) || lower === "off") return lower;
163
+ }
164
+ }
165
+ // 3. User config
166
+ const user = join(cavemanConfigDir(), "config.json");
167
+ if (existsSync(user)) {
168
+ const m = readConfigMode(user);
169
+ if (m) {
170
+ const lower = m.toLowerCase();
171
+ if (isValidMode(lower) || lower === "off") return lower;
172
+ }
173
+ }
174
+ // 4. Default
175
+ return "full";
176
+ }
177
+
178
+ // ── Flag I/O ────────────────────────────────────────────────────────────────
179
+
180
+ function readFlag(): string | null {
181
+ try {
182
+ const content = readFileSync(flagPath, "utf-8").trim();
183
+ return isValidMode(content) ? content : null;
184
+ } catch {
185
+ return null;
186
+ }
187
+ }
188
+
189
+ function writeFlag(mode: string): void {
190
+ try {
191
+ const dir = dirname(flagPath);
192
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
193
+ const tmp = `${flagPath}.tmp.${process.pid}`;
194
+ writeFileSync(tmp, mode, { mode: 0o600 });
195
+ renameSync(tmp, flagPath);
196
+ } catch {
197
+ // Silent fail — never block session
198
+ }
199
+ }
200
+
201
+ function deleteFlag(): void {
202
+ try { if (existsSync(flagPath)) unlinkSync(flagPath); } catch {}
203
+ }
204
+
205
+ function logModeChange(newMode: string | null): void {
206
+ try {
207
+ const prev = readFlag();
208
+ if (prev === newMode) return;
209
+ const dir = dirname(flagPath);
210
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
211
+ const entry = JSON.stringify({
212
+ ts: new Date().toISOString(), mode: newMode, prev,
213
+ }) + "\n";
214
+ appendFileSync(join(dir, ".caveman-mode-log.jsonl"), entry, { mode: 0o600 });
215
+ } catch {}
216
+ }
217
+
218
+ // ── Mode switching ──────────────────────────────────────────────────────────
219
+
220
+ function applyMode(mode: string | "off"): void {
221
+ if (mode === "off") { logModeChange(null); deleteFlag(); }
222
+ else { logModeChange(mode); writeFlag(mode); }
223
+ }
224
+
225
+ interface UI {
226
+ hasUI: boolean;
227
+ ui: {
228
+ notify(msg: string, level: string): void;
229
+ };
230
+ }
231
+
232
+ function notifyMode(ui: UI, mode: string): void {
233
+ if (!ui.hasUI) return;
234
+ const label = mode === "wenyan" ? "wenyan-full" : mode;
235
+ ui.ui.notify(`caveman: ${label}`, "info");
236
+ }
237
+
238
+ function clearStatus(ui: UI): void {
239
+ if (!ui.hasUI) return;
240
+ ui.ui.notify("caveman: off", "info");
241
+ }
242
+
243
+ // ── Mode parsing (mirrors caveman opencode plugin) ──────────────────────────
244
+
245
+ function parseModeChange(promptRaw: string): string | "off" | null {
246
+ let prompt = (promptRaw || "").trim();
247
+ if (!prompt) return null;
248
+
249
+ // Natural-language deactivation (checked first)
250
+ if (
251
+ /\b(stop|disable|deactivate|turn off)\b.*\bcaveman\b/i.test(prompt) ||
252
+ /\bcaveman\b.*\b(stop|disable|deactivate|turn off)\b/i.test(prompt) ||
253
+ /\bnormal mode\b/i.test(prompt)
254
+ ) return "off";
255
+
256
+ // Slash-command
257
+ const lower = prompt.toLowerCase();
258
+ if (lower.startsWith("/caveman")) {
259
+ const parts = lower.split(/\s+/);
260
+ const cmd = parts[0];
261
+ const arg = parts[1] || "";
262
+
263
+ if (cmd === "/caveman-commit") return "commit";
264
+ if (cmd === "/caveman-review") return "review";
265
+ if (cmd === "/caveman-compress") return "compress";
266
+
267
+ if (cmd === "/caveman") {
268
+ if (!arg) return resolveDefault();
269
+ if (arg === "off" || arg === "stop" || arg === "disable") return "off";
270
+ if (arg === "wenyan-full") return "wenyan";
271
+ if (isValidMode(arg) && !INDEPENDENT[arg]) return arg;
272
+ return null; // unknown arg — don't silently overwrite
273
+ }
274
+ }
275
+
276
+ // Natural-language activation
277
+ if (
278
+ /\b(activate|enable|turn on|start|talk like)\b.*\bcaveman\b/i.test(prompt) ||
279
+ /\bcaveman\b.*\b(mode|activate|enable|turn on|start)\b/i.test(prompt)
280
+ ) {
281
+ const mode = resolveDefault();
282
+ return mode === "off" ? null : mode;
283
+ }
284
+
285
+ return null;
286
+ }
287
+
288
+ // ── SKILL.md loading (mirrors caveman-activate.js) ──────────────────────────
289
+
290
+ // Resolve SKILL.md path — try relative to this extension file first, then skills dir
291
+ const SKILL_CANDIDATES = [
292
+ join(__dirname, "..", "skills", "caveman", "SKILL.md"),
293
+ join(__dirname, "skills", "caveman", "SKILL.md"),
294
+ ];
295
+
296
+ function findSkillPath(): string | null {
297
+ for (const candidate of SKILL_CANDIDATES) {
298
+ if (existsSync(candidate)) return candidate;
299
+ }
300
+ return null;
301
+ }
302
+
303
+ // Load and filter SKILL.md content for the active mode.
304
+ // Mirrors caveman-activate.js: strips frontmatter, keeps only the active
305
+ // level's table row and example lines.
306
+ function loadFilteredSkillContent(mode: string): string | null {
307
+ const skillPath = findSkillPath();
308
+ if (!skillPath) return null;
309
+
310
+ try {
311
+ const raw = readFileSync(skillPath, "utf-8");
312
+ // Strip YAML frontmatter
313
+ const body = raw.replace(/^---[\s\S]*?---\s*/, "");
314
+ const modeLabel = mode === "wenyan" ? "wenyan-full" : mode;
315
+
316
+ // Filter: keep header rows + only the active level's row
317
+ const filtered = body.split("\n").reduce<string[]>((acc, line) => {
318
+ // Intensity table rows start with | **level** |
319
+ const tableRowMatch = line.match(/^\|\s*\*\*(\S+?)\*\*\s*\|/);
320
+ if (tableRowMatch) {
321
+ if (tableRowMatch[1] === modeLabel) acc.push(line);
322
+ return acc;
323
+ }
324
+ // Example lines start with "- level:"
325
+ const exampleMatch = line.match(/^- (\S+?):\s/);
326
+ if (exampleMatch) {
327
+ if (exampleMatch[1] === modeLabel) acc.push(line);
328
+ return acc;
329
+ }
330
+ acc.push(line);
331
+ return acc;
332
+ }, []);
333
+
334
+ return filtered.join("\n");
335
+ } catch {
336
+ return null;
337
+ }
338
+ }
339
+
340
+ // ── Reinforcement line ──────────────────────────────────────────────────────
341
+
342
+ function reinforcementLine(mode: string): string {
343
+ const label = mode === "wenyan" ? "wenyan-full" : mode;
344
+ const wenyanHint = mode.startsWith("wenyan")
345
+ ? " MUST respond in 文言文 (classical Chinese). Use classical particles (之/乃/為/其), omit subjects, verbs precede objects."
346
+ : "";
347
+ return (
348
+ `[CAVEMAN ACTIVE — intensity: ${label}.${wenyanHint} ` +
349
+ "Respond terse like smart caveman. All technical substance stay. " +
350
+ "Only fluff die. Fragments OK. Short synonyms. " +
351
+ "No filler/hedging/pleasantries. Code unchanged. Technical terms exact.]"
352
+ );
353
+ }
354
+
355
+ // ── Argument completions ────────────────────────────────────────────────────
356
+
357
+ const MODE_CHOICES = [
358
+ { value: "lite", label: "lite", description: "no filler/hedging, keep articles" },
359
+ { value: "full", label: "full", description: "drop articles, fragments OK (default)" },
360
+ { value: "ultra", label: "ultra", description: "one word when one word enough" },
361
+ { value: "wenyan-lite", label: "wenyan-lite", description: "semi-classical, keep grammar" },
362
+ { value: "wenyan", label: "wenyan", description: "maximum classical terseness (文言文)" },
363
+ { value: "wenyan-ultra",label: "wenyan-ultra", description: "extreme abbreviation, classical feel" },
364
+ { value: "off", label: "off", description: "disabled" },
365
+ ];
366
+
367
+ function getModeCompletions(prefix: string) {
368
+ const lower = prefix.toLowerCase();
369
+ const matches = MODE_CHOICES.filter(m =>
370
+ m.value.startsWith(lower) || m.label.startsWith(lower)
371
+ );
372
+ return matches.length > 0 ? matches : null;
373
+ }
374
+
375
+ // ── Extension factory ───────────────────────────────────────────────────────
376
+
377
+ export default function cavemanExtension(pi: ExtensionAPI) {
378
+ // ── session_start: auto-activate ──────────────────────────────────────
379
+ pi.on("session_start", async (_event, ctx) => {
380
+ sessionStats = { turns: 0, outputTokens: 0, cacheReadTokens: 0, inputTokens: 0 };
381
+ sessionExplicitOff = false;
382
+ const mode = resolveDefault();
383
+ if (mode === "off") { deleteFlag(); return; }
384
+ applyMode(mode);
385
+ notifyMode(ctx, mode);
386
+ });
387
+
388
+ // ── turn_end: accumulate token stats ─────────────────────────────────
389
+ pi.on("turn_end", (event) => {
390
+ const e = event as unknown as Record<string, unknown>;
391
+ const msg = e?.message as Record<string, unknown> | undefined;
392
+ const usage = msg?.usage as Record<string, number> | undefined;
393
+ if (usage) {
394
+ sessionStats.turns++;
395
+ sessionStats.outputTokens += usage.output ?? 0;
396
+ sessionStats.cacheReadTokens += usage.cacheRead ?? 0;
397
+ sessionStats.inputTokens += usage.input ?? 0;
398
+ }
399
+ });
400
+
401
+ // ── /caveman command ──────────────────────────────────────────────────
402
+ pi.registerCommand("caveman", {
403
+ description: "Switch caveman mode (lite|full|ultra|wenyan|off)",
404
+ getArgumentCompletions: (prefix) => getModeCompletions(prefix),
405
+ handler: async (args, ctx) => {
406
+ const arg = (args || "").trim().toLowerCase();
407
+
408
+ // No arg → activate default
409
+ if (!arg) {
410
+ const mode = resolveDefault();
411
+ if (mode === "off") { deleteFlag(); return; }
412
+ applyMode(mode);
413
+ notifyMode(ctx, mode);
414
+ return;
415
+ }
416
+
417
+ // Off
418
+ if (arg === "off" || arg === "stop" || arg === "disable") {
419
+ sessionExplicitOff = true;
420
+ applyMode("off");
421
+ clearStatus(ctx);
422
+ return;
423
+ }
424
+
425
+ // Wenyan alias
426
+ if (arg === "wenyan-full") {
427
+ applyMode("wenyan");
428
+ if (ctx.hasUI) {
429
+ ctx.ui.notify("caveman: wenyan-full", "info");
430
+ }
431
+ return;
432
+ }
433
+
434
+ // Valid mode
435
+ if (isValidMode(arg) && !INDEPENDENT[arg]) {
436
+ applyMode(arg);
437
+ notifyMode(ctx, arg);
438
+ return;
439
+ }
440
+
441
+ // Unknown
442
+ if (ctx.hasUI) {
443
+ ctx.ui.notify(
444
+ `unknown mode "${arg}". Use: lite|full|ultra|wenyan-lite|wenyan|wenyan-ultra|off`,
445
+ "warning",
446
+ );
447
+ }
448
+ },
449
+ });
450
+
451
+ // ── /caveman-status command ────────────────────────────────────────────
452
+ pi.registerCommand("caveman-status", {
453
+ description: "Show current caveman mode and config",
454
+ handler: async (_args, ctx) => {
455
+ const active = readFlag();
456
+ const def = resolveDefault();
457
+ const configPath = join(cavemanConfigDir(), "config.json");
458
+ const repoConfig = findRepoConfig(process.cwd());
459
+ const mode = active || "off";
460
+
461
+ const mc = modeColor(mode);
462
+ const modeLabel = mode === "wenyan" ? "wenyan-full" : mode;
463
+ const defLabel = def === "wenyan" ? "wenyan-full" : def;
464
+
465
+ const lines: string[] = [
466
+ `${BOLD}Caveman${RST}: ${mc}${modeLabel}${RST}${def !== mode ? ` ${DIM}(default: ${defLabel})${RST}` : ""}`,
467
+ "",
468
+ ` ${sessionStats.turns} turns ${DIM}│${RST} ${sessionStats.outputTokens.toLocaleString()} out ${DIM}│${RST} ${sessionStats.cacheReadTokens.toLocaleString()} cached ${DIM}│${RST} ${sessionStats.inputTokens.toLocaleString()} in`,
469
+ ];
470
+
471
+ const savings = estimateSavings(sessionStats.outputTokens, mode);
472
+ if (savings && savings.estSaved > 0) {
473
+ lines.push(
474
+ "",
475
+ ` saved ${GREEN}${savings.estSaved.toLocaleString()}${RST} tokens ${DIM}(~${savings.pct}%)${RST} ${GREEN}${bar(savings.pct)}${RST}`,
476
+ );
477
+ }
478
+
479
+ const configLines: string[] = [];
480
+ if (process.env.CAVEMAN_DEFAULT_MODE) {
481
+ configLines.push(` env ${DIM}CAVEMAN_DEFAULT_MODE=${process.env.CAVEMAN_DEFAULT_MODE}${RST}`);
482
+ }
483
+ if (existsSync(configPath)) configLines.push(` user ${DIM}${truncatePath(configPath)}${RST}`);
484
+ if (repoConfig) configLines.push(` repo ${DIM}${truncatePath(repoConfig)}${RST}`);
485
+ configLines.push(` flag ${DIM}${truncatePath(flagPath)}${RST}`);
486
+
487
+ if (configLines.length) {
488
+ lines.push("", ...configLines);
489
+ }
490
+
491
+ const msg = lines.join("\n");
492
+ if (ctx.hasUI) ctx.ui.notify(msg, "info");
493
+ pi.sendMessage({
494
+ content: msg,
495
+ attribution: "user",
496
+ }, { triggerTurn: false });
497
+ },
498
+ });
499
+
500
+ // ── /caveman-config command ──────────────────────────────────────────
501
+ const INTENSITY_MODES = ["lite", "full", "ultra", "wenyan-lite", "wenyan", "wenyan-ultra", "off"];
502
+
503
+ pi.registerCommand("caveman-config", {
504
+ description: "Set default caveman mode for new sessions",
505
+ getArgumentCompletions: (prefix) => getModeCompletions(prefix),
506
+ handler: async (args, ctx) => {
507
+ const arg = (args || "").trim().toLowerCase();
508
+
509
+ // No arg → show current config + available options
510
+ if (!arg) {
511
+ const def = resolveDefault();
512
+ const configPath = join(cavemanConfigDir(), "config.json");
513
+ const repoConfig = findRepoConfig(process.cwd());
514
+
515
+ const lines: string[] = [
516
+ `Current default: ${def}`,
517
+ "",
518
+ "Available modes:",
519
+ " lite — no filler/hedging, keep articles + full sentences",
520
+ " full — drop articles, fragments OK, short synonyms (default)",
521
+ " ultra — one word when one word enough, no abbreviations",
522
+ " wenyan-lite — semi-classical, keep grammar structure",
523
+ " wenyan — maximum classical terseness (文言文)",
524
+ " wenyan-ultra — extreme abbreviation, classical feel",
525
+ " off — disabled by default",
526
+ "",
527
+ "Usage: /caveman-config <mode>",
528
+ `Config file: ${configPath}`,
529
+ ];
530
+ if (process.env.CAVEMAN_DEFAULT_MODE) {
531
+ lines.push(`Note: CAVEMAN_DEFAULT_MODE=${process.env.CAVEMAN_DEFAULT_MODE} overrides config file`);
532
+ }
533
+ if (repoConfig) {
534
+ lines.push(`Note: repo config at ${repoConfig} overrides user config`);
535
+ }
536
+
537
+ const msg = lines.join("\n");
538
+ if (ctx.hasUI) ctx.ui.notify(msg, "info");
539
+ pi.sendMessage({
540
+ customType: "caveman-config",
541
+ content: msg,
542
+ display: true,
543
+ attribution: "user",
544
+ }, { triggerTurn: false });
545
+ return;
546
+ }
547
+
548
+ // Validate
549
+ if (!isValidMode(arg) && arg !== "off") {
550
+ if (ctx.hasUI) {
551
+ ctx.ui.notify(
552
+ `unknown mode "${arg}". Available: ${INTENSITY_MODES.join(", ")}`,
553
+ "warning",
554
+ );
555
+ }
556
+ return;
557
+ }
558
+
559
+ // Write to user config
560
+ const configDir = cavemanConfigDir();
561
+ const cfgPath = join(configDir, "config.json");
562
+
563
+ try {
564
+ if (!existsSync(configDir)) mkdirSync(configDir, { recursive: true });
565
+
566
+ let existing: Record<string, unknown> = {};
567
+ if (existsSync(cfgPath)) {
568
+ try { existing = JSON.parse(readFileSync(cfgPath, "utf-8")); } catch {}
569
+ }
570
+ existing.defaultMode = arg;
571
+ writeFileSync(cfgPath, JSON.stringify(existing, null, 2) + "\n", { mode: 0o600 });
572
+
573
+ const label = arg === "off" ? "off" : arg;
574
+ if (ctx.hasUI) {
575
+ ctx.ui.notify(`default mode set to: ${label}`, "info");
576
+ ctx.ui.notify(`config: ${cfgPath}`, "info");
577
+ }
578
+ pi.sendMessage({
579
+ customType: "caveman-config",
580
+ content: `Default mode saved: ${label}\nConfig: ${cfgPath}\nEffective on next session.`,
581
+ display: true,
582
+ attribution: "user",
583
+ }, { triggerTurn: false });
584
+ } catch (e) {
585
+ if (ctx.hasUI) ctx.ui.notify(`failed to write config: ${e}`, "error");
586
+ }
587
+ },
588
+ });
589
+
590
+ // ── before_agent_start: per-turn reinforcement ────────────────────────
591
+ // Injects full SKILL.md content (filtered to active mode) + reinforcement line.
592
+ // Mirrors caveman-activate.js behavior: the model sees the complete ruleset
593
+ // on every turn, not just a one-line reminder.
594
+ pi.on("before_agent_start", async (_event, _ctx) => {
595
+ let active = readFlag();
596
+ if (!active && !sessionExplicitOff) active = resolveDefault();
597
+ if (!active || active === "off" || INDEPENDENT[active]) return null;
598
+
599
+ const skillContent = loadFilteredSkillContent(active);
600
+ const header = `CAVEMAN MODE ACTIVE — level: ${active === "wenyan" ? "wenyan-full" : active}\n\n`;
601
+
602
+ // If SKILL.md found, inject full filtered content; fall back to reinforcement line
603
+ const content = skillContent
604
+ ? header + skillContent
605
+ : reinforcementLine(active);
606
+
607
+ return {
608
+ message: {
609
+ customType: "caveman-reinforcement",
610
+ content,
611
+ display: false,
612
+ attribution: "system",
613
+ },
614
+ };
615
+ });
616
+
617
+ // ── input: intercept user prompts for mode changes ─────────────────────
618
+ pi.on("input", async (event, _ctx) => {
619
+ if (!event || typeof event !== "object" || !("text" in event)) return;
620
+ const text = event.text;
621
+ if (typeof text !== "string") return;
622
+ const change = parseModeChange(text);
623
+ if (change) {
624
+ if (change === "off") sessionExplicitOff = true;
625
+ applyMode(change);
626
+ }
627
+ });
628
+
629
+ }
package/package.json ADDED
@@ -0,0 +1,26 @@
1
+ {
2
+ "name": "@izhimu/pi-caveman",
3
+ "version": "0.1.0",
4
+ "description": "Caveman mode for pi — ultra-compressed communication, 65% output token savings",
5
+ "type": "module",
6
+ "keywords": ["pi-package", "caveman", "token-savings", "compression"],
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/izhimu/pi-caveman.git"
10
+ },
11
+ "author": "izhimu",
12
+ "license": "MIT",
13
+ "peerDependencies": {
14
+ "@earendil-works/pi-coding-agent": "*"
15
+ },
16
+ "pi": {
17
+ "extensions": ["./extensions"],
18
+ "skills": ["./skills"]
19
+ },
20
+ "files": [
21
+ "extensions/",
22
+ "skills/",
23
+ "README.md",
24
+ "LICENSE"
25
+ ]
26
+ }
@@ -0,0 +1,78 @@
1
+ ---
2
+ name: caveman
3
+ description: >
4
+ Ultra-compressed communication mode. Cuts output tokens 65% (measured) by speaking like caveman
5
+ while keeping full technical accuracy. Supports intensity levels: lite, full (default), ultra,
6
+ wenyan-lite, wenyan-full, wenyan-ultra.
7
+ Use when user says "caveman mode", "talk like caveman", "use caveman", "less tokens",
8
+ "be brief", or invokes /caveman. Also auto-triggers when token efficiency is requested.
9
+ ---
10
+
11
+ Respond terse like smart caveman. All technical substance stay. Only fluff die.
12
+
13
+ ## Persistence
14
+
15
+ ACTIVE EVERY RESPONSE. No revert after many turns. No filler drift. Still active if unsure. Off only: "stop caveman" / "normal mode".
16
+
17
+ Default: **full**. Switch: `/caveman lite|full|ultra`.
18
+
19
+ ## Rules
20
+
21
+ Drop: articles (a/an/the), filler (just/really/basically/actually/simply), pleasantries (sure/certainly/of course/happy to), hedging. Fragments OK. Short synonyms (big not extensive, fix not "implement a solution for"). No tool-call narration, no decorative tables/emoji, no dumping long raw error logs unless asked — quote shortest decisive line. Standard well-known tech acronyms OK (DB/API/HTTP); never invent new abbreviations (cfg/impl/req/res/fn) — tokenizer split them same as full word: zero token saved, reader still decode. Full word cheaper AND clearer. No causal arrows (→) either — own token, save nothing. Technical terms exact. Code blocks unchanged. Errors quoted exact.
22
+
23
+ Preserve user's dominant language. User write Portuguese → reply Portuguese caveman. User write Spanish → reply Spanish caveman. Compress the style, not the language. No forced English openings or status phrases. ALWAYS keep technical terms, code, API names, CLI commands, commit-type keywords (feat/fix/...), and exact error strings verbatim — unless user explicitly ask for translation.
24
+
25
+ No self-reference. Never name or announce the style. No "caveman mode on", "me caveman think", no third-person caveman tags. Output caveman-only — never normal answer plus "Caveman:" recap. Exception: user explicitly ask what the mode is.
26
+
27
+ Pattern: `[thing] [action] [reason]. [next step].`
28
+
29
+ Not: "Sure! I'd be happy to help you with that. The issue you're experiencing is likely caused by..."
30
+ Yes: "Bug in auth middleware. Token expiry check use `<` not `<=`. Fix:"
31
+
32
+ ## Intensity
33
+
34
+ | Level | What change |
35
+ |-------|------------|
36
+ | **lite** | No filler/hedging. Keep articles + full sentences. Professional but tight |
37
+ | **full** | Drop articles, fragments OK, short synonyms. Classic caveman. No tool-call narration, no decorative tables/emoji, no long raw error-log dumps unless asked. Standard acronyms OK; no invented abbreviations |
38
+ | **ultra** | Strip conjunctions when cause-then-effect stay unambiguous. One word when one word enough. State each fact once. NO prose abbreviations (cfg/impl/req/res/fn/auth), NO arrows (X → Y) — measured zero token saving under tokenizer, cost decode clarity. Code symbols, function names, API names, error strings: never touch |
39
+ | **wenyan-lite** | Semi-classical. Drop filler/hedging but keep grammar structure, classical register |
40
+ | **wenyan-full** | Maximum classical terseness. Fully 文言文. 80-90% character reduction. Classical sentence patterns, verbs precede objects, subjects often omitted, classical particles (之/乃/為/其) |
41
+ | **wenyan-ultra** | Extreme abbreviation while keeping classical Chinese feel. Maximum compression, ultra terse |
42
+
43
+ Example — "Why React component re-render?"
44
+ - lite: "Your component re-renders because you create a new object reference each render. Wrap it in `useMemo`."
45
+ - full: "New object ref each render. Inline object prop = new ref = re-render. Wrap in `useMemo`."
46
+ - ultra: "Inline obj prop, new ref, re-render. `useMemo`."
47
+ - wenyan-lite: "組件頻重繪,以每繪新生對象參照故。以 useMemo 包之。"
48
+ - wenyan-full: "每繪新生對象參照,故重繪;以 useMemo 包之則免。"
49
+ - wenyan-ultra: "新參照則重繪。useMemo 包之。"
50
+
51
+ Example — "Explain database connection pooling."
52
+ - lite: "Connection pooling reuses open connections instead of creating new ones per request. Avoids repeated handshake overhead."
53
+ - full: "Pool reuse open DB connections. No new connection per request. Skip handshake overhead."
54
+ - ultra: "Pool reuse open DB connections. No per-request handshake."
55
+ - wenyan-full: "池蓄已開之連,不逐請而新開,省握手之費。"
56
+ - wenyan-ultra: "池蓄連,免逐請新開,省握手。"
57
+
58
+ ## Auto-Clarity
59
+
60
+ Drop caveman when:
61
+ - Security warnings
62
+ - Irreversible action confirmations
63
+ - Multi-step sequences where fragment order or omitted conjunctions risk misread
64
+ - Compression itself creates technical ambiguity (e.g., `"migrate table drop column backup first"` — order unclear without articles/conjunctions)
65
+ - User asks to clarify or repeats question
66
+
67
+ Resume caveman after clear part done.
68
+
69
+ Example — destructive op:
70
+ > **Warning:** This will permanently delete all rows in the `users` table and cannot be undone.
71
+ > ```sql
72
+ > DROP TABLE users;
73
+ > ```
74
+ > Caveman resume. Verify backup exist first.
75
+
76
+ ## Boundaries
77
+
78
+ Code/commits/PRs: write normal. "stop caveman" or "normal mode": revert. Level persist until changed or session end.