@izhimu/pi-caveman 0.4.0 → 0.5.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.
@@ -1,750 +1,741 @@
1
- // pi-caveman — pi & oh-my-pi extension
2
- //
3
- // Caveman mode for pi & oh-my-pi: auto-activates per session, /caveman commands,
4
- // per-turn reinforcement injection.
5
- //
6
- // Flag file: ~/.pi/.caveman-active or ~/.omp/.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 & Canonical Mode Mapping ─────────────────────────────────────
24
-
25
- export const VALID_MODES = ["caveman", "ultracave", "megacave"] as const;
26
- export type Mode = (typeof VALID_MODES)[number];
27
-
28
- export const LEGACY_MODE_MAP: Record<string, Mode> = {
29
- "full": "caveman",
30
- "lite": "caveman",
31
- "ultra": "ultracave",
32
- "wenyan": "megacave",
33
- "wenyan-lite": "megacave",
34
- "wenyan-full": "megacave",
35
- "wenyan-ultra": "megacave",
36
- };
37
-
38
- export function canonicalMode(raw: string): Mode | null {
39
- const lower = raw.trim().toLowerCase();
40
- if ((VALID_MODES as readonly string[]).includes(lower)) return lower as Mode;
41
- return LEGACY_MODE_MAP[lower] ?? null;
42
- }
43
-
44
- // ── Session stats ───────────────────────────────────────────────────────────
45
-
46
- interface SessionStats {
47
- turns: number;
48
- outputTokens: number;
49
- cacheReadTokens: number;
50
- inputTokens: number;
51
- }
52
-
53
- let sessionStats: SessionStats = {
54
- turns: 0, outputTokens: 0, cacheReadTokens: 0, inputTokens: 0,
55
- };
56
-
57
- let sessionExplicitOff = false;
58
-
59
- export const COMPRESSION_RATIOS: Record<string, number> = {
60
- caveman: 0.65,
61
- ultracave: 0.75,
62
- megacave: 0.80,
63
- // legacy aliases for backwards compatibility
64
- full: 0.65,
65
- lite: 0.35,
66
- ultra: 0.75,
67
- wenyan: 0.80,
68
- "wenyan-lite": 0.60,
69
- "wenyan-full": 0.80,
70
- "wenyan-ultra": 0.85,
71
- };
72
-
73
- export function estimateSavings(outputTokens: number, mode: string) {
74
- const canon = canonicalMode(mode) || mode;
75
- const ratio = COMPRESSION_RATIOS[canon] ?? COMPRESSION_RATIOS[mode];
76
- if (!ratio) return null;
77
- const estWithout = Math.round(outputTokens / (1 - ratio));
78
- const estSaved = estWithout - outputTokens;
79
- return { estWithout, estSaved, pct: Math.round(ratio * 100) };
80
- }
81
-
82
- // ── Display helpers ────────────────────────────────────────────────────────
83
-
84
- const ESC = "\x1b[";
85
- const RST = `${ESC}0m`;
86
- const DIM = `${ESC}2m`;
87
- const BOLD = `${ESC}1m`;
88
- const GREEN = `${ESC}32m`;
89
- const CYAN = `${ESC}36m`;
90
- const GRAY = `${ESC}90m`;
91
-
92
- export function modeColor(mode: string): string {
93
- if (mode === "off") return GRAY;
94
- if (mode === "megacave" || mode.startsWith("wenyan")) return CYAN;
95
- return GREEN; // caveman, ultracave, full, ultra
96
- }
97
-
98
- function bar(pct: number, width = 20): string {
99
- const filled = Math.round((pct / 100) * width);
100
- return "█".repeat(filled) + "░".repeat(width - filled);
101
- }
102
-
103
- function truncatePath(p: string, max = 40): string {
104
- if (p.length <= max) return p;
105
- const parts = p.split(sep);
106
- const tail = parts.slice(-2).join(sep);
107
- return "…" + sep + tail;
108
- }
109
-
110
- // ── Paths & Host Resolution ─────────────────────────────────────────────────
111
-
112
- export function resolveHostDir(): string {
113
- const isOmp =
114
- process.title === "omp" ||
115
- Boolean(process.env.OMP_PROFILE) ||
116
- process.env.PI_CONFIG_DIR === ".omp" ||
117
- Boolean(process.env.OMP_AUTORESEARCH_DB_DIR) ||
118
- (typeof process.argv[1] === "string" && process.argv[1].includes("@oh-my-pi"));
119
- const dirName = isOmp ? "omp" : "pi";
120
- const xdg = process.env.XDG_CONFIG_HOME;
121
- return xdg ? join(xdg, dirName) : join(homedir(), `.${dirName}`);
122
- }
123
-
124
- export function getFlagPath(): string {
125
- return join(resolveHostDir(), ".caveman-active");
126
- }
127
-
128
- // ── Config resolution (mirrors caveman/src/hooks/caveman-config.js) ─────────
129
-
130
- export function cavemanConfigDir(): string {
131
- const xdgHome = process.env.XDG_CONFIG_HOME;
132
- if (xdgHome) return join(xdgHome, "caveman");
133
- if (process.platform === "win32") {
134
- return join(
135
- process.env.APPDATA || join(homedir(), "AppData", "Roaming"),
136
- "caveman",
137
- );
138
- }
139
- return join(homedir(), ".config", "caveman");
140
- }
141
-
142
- export function findRepoConfig(start: string): string | null {
143
- let dir = start;
144
- for (let i = 0; i < 64; i++) {
145
- const a = join(dir, ".caveman", "config.json");
146
- if (existsSync(a)) return a;
147
- const b = join(dir, ".caveman.json");
148
- if (existsSync(b)) return b;
149
- const parent = dirname(dir);
150
- if (parent === dir) break;
151
- dir = parent;
152
- }
153
- return null;
154
- }
155
-
156
- export function readConfigMode(configPath: string): string | null {
157
- try {
158
- const parsed = JSON.parse(readFileSync(configPath, "utf-8"));
159
- const m = parsed?.defaultMode;
160
- return typeof m === "string" ? m : null;
161
- } catch {
162
- return null;
163
- }
164
- }
165
-
166
- export function resolveDefault(): Mode | "off" {
167
- // 1. Env var (short-circuits)
168
- const env = process.env.CAVEMAN_DEFAULT_MODE;
169
- if (env) {
170
- const lower = env.toLowerCase();
171
- if (lower === "off") return "off";
172
- const canon = canonicalMode(lower);
173
- if (canon) return canon;
174
- }
175
- // 2. Repo-local config
176
- const repo = findRepoConfig(process.cwd());
177
- if (repo) {
178
- const m = readConfigMode(repo);
179
- if (m) {
180
- const lower = m.toLowerCase();
181
- if (lower === "off") return "off";
182
- const canon = canonicalMode(lower);
183
- if (canon) return canon;
184
- }
185
- }
186
- // 3. User config
187
- const user = join(cavemanConfigDir(), "config.json");
188
- if (existsSync(user)) {
189
- const m = readConfigMode(user);
190
- if (m) {
191
- const lower = m.toLowerCase();
192
- if (lower === "off") return "off";
193
- const canon = canonicalMode(lower);
194
- if (canon) return canon;
195
- }
196
- }
197
- // 4. Default
198
- return "caveman";
199
- }
200
-
201
- // ── Flag I/O ────────────────────────────────────────────────────────────────
202
-
203
- export function readFlag(): Mode | null {
204
- const flagPath = getFlagPath();
205
- try {
206
- if (existsSync(flagPath)) {
207
- const content = readFileSync(flagPath, "utf-8").trim();
208
- return canonicalMode(content);
209
- }
210
- } catch {}
211
-
212
- // Fallback: cross-host check if running under omp but flag written in ~/.pi (or vice versa)
213
- try {
214
- const xdg = process.env.XDG_CONFIG_HOME;
215
- const fallbackDir = flagPath.includes(".omp")
216
- ? (xdg ? join(xdg, "pi") : join(homedir(), ".pi"))
217
- : (xdg ? join(xdg, "omp") : join(homedir(), ".omp"));
218
- const fallbackPath = join(fallbackDir, ".caveman-active");
219
- if (existsSync(fallbackPath)) {
220
- const content = readFileSync(fallbackPath, "utf-8").trim();
221
- return canonicalMode(content);
222
- }
223
- } catch {}
224
-
225
- return null;
226
- }
227
-
228
- export function writeFlag(mode: Mode): void {
229
- const flagPath = getFlagPath();
230
- try {
231
- const dir = dirname(flagPath);
232
- if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
233
- const tmp = `${flagPath}.tmp.${process.pid}`;
234
- writeFileSync(tmp, mode, { mode: 0o600 });
235
- renameSync(tmp, flagPath);
236
- } catch {
237
- // Silent fail — never block session
238
- }
239
- }
240
-
241
- export function deleteFlag(): void {
242
- const flagPath = getFlagPath();
243
- try { if (existsSync(flagPath)) unlinkSync(flagPath); } catch {}
244
- try {
245
- const xdg = process.env.XDG_CONFIG_HOME;
246
- const fallbackDir = flagPath.includes(".omp")
247
- ? (xdg ? join(xdg, "pi") : join(homedir(), ".pi"))
248
- : (xdg ? join(xdg, "omp") : join(homedir(), ".omp"));
249
- const fallbackPath = join(fallbackDir, ".caveman-active");
250
- if (existsSync(fallbackPath)) unlinkSync(fallbackPath);
251
- } catch {}
252
- }
253
-
254
- function logModeChange(newMode: Mode | null): void {
255
- try {
256
- const prev = readFlag();
257
- if (prev === newMode) return;
258
- const dir = dirname(getFlagPath());
259
- if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
260
- const entry = JSON.stringify({
261
- ts: new Date().toISOString(), mode: newMode, prev,
262
- }) + "\n";
263
- appendFileSync(join(dir, ".caveman-mode-log.jsonl"), entry, { mode: 0o600 });
264
- } catch {}
265
- }
266
-
267
- export function saveUserConfigMode(mode: string): void {
268
- try {
269
- const configDir = cavemanConfigDir();
270
- const cfgPath = join(configDir, "config.json");
271
- if (!existsSync(configDir)) mkdirSync(configDir, { recursive: true });
272
- let existing: Record<string, unknown> = {};
273
- if (existsSync(cfgPath)) {
274
- try { existing = JSON.parse(readFileSync(cfgPath, "utf-8")); } catch {}
275
- }
276
- existing.defaultMode = mode;
277
- writeFileSync(cfgPath, JSON.stringify(existing, null, 2) + "\n", { mode: 0o600 });
278
- } catch {}
279
- }
280
-
281
- export function applyMode(mode: Mode | "off"): void {
282
- if (mode === "off") { logModeChange(null); deleteFlag(); }
283
- else { logModeChange(mode); writeFlag(mode); }
284
- }
285
-
286
- interface UI {
287
- hasUI: boolean;
288
- ui: {
289
- notify(msg: string, level?: "info" | "warning" | "error"): void;
290
- setStatus?(key: string, text: string | undefined): void;
291
- };
292
- }
293
-
294
- function notifyMode(ui: UI, mode: string): void {
295
- if (!ui.hasUI) return;
296
- ui.ui.notify(`caveman: ${mode}`, "info");
297
- ui.ui.setStatus?.("caveman", undefined);
298
- }
299
-
300
- function clearStatus(ui: UI): void {
301
- if (!ui.hasUI) return;
302
- ui.ui.setStatus?.("caveman", undefined);
303
- ui.ui.notify("caveman: off", "info");
304
- }
305
-
306
- // ── SKILL.md and Thesis loading (mirrors caveman 3.2.0) ─────────────────────
307
-
308
- export function findSkillPath(skillId: string): string | null {
309
- const candidates = [
310
- join(__dirname, "..", "skills", skillId, "SKILL.md"),
311
- join(__dirname, "skills", skillId, "SKILL.md"),
312
- ];
313
- for (const candidate of candidates) {
314
- if (existsSync(candidate)) return candidate;
315
- }
316
- return null;
317
- }
318
-
319
- export function loadSkillContent(mode: Mode): string | null {
320
- const skillPath = findSkillPath(mode);
321
- if (!skillPath) return null;
322
- try {
323
- const raw = readFileSync(skillPath, "utf-8");
324
- return raw.replace(/^---[\s\S]*?---\s*/, "");
325
- } catch {
326
- return null;
327
- }
328
- }
329
-
330
- export const FALLBACK_THESIS: Record<Mode, string> = {
331
- caveman: "Respond terse like smart caveman. All technical substance stay. Only fluff die.",
332
- ultracave: "Respond terse like smart caveman. All technical substance stay. Only fluff die. Then cut again.",
333
- megacave: "以文言答。技術之實皆存,唯贅言去之。",
334
- };
335
-
336
- export function getThesisLine(mode: Mode): string {
337
- const skillPath = findSkillPath(mode);
338
- if (skillPath) {
339
- try {
340
- const raw = readFileSync(skillPath, "utf-8");
341
- const body = raw.replace(/^---[\s\S]*?---\s*/, "");
342
- const lines = body.split("\n");
343
- const titleIndex = lines.findIndex((l) => l.trim().startsWith("# "));
344
- if (titleIndex !== -1) {
345
- for (let i = titleIndex + 1; i < lines.length; i++) {
346
- const line = lines[i].trim();
347
- if (line) return line;
348
- }
349
- }
350
- } catch {}
351
- }
352
- return FALLBACK_THESIS[mode] ?? FALLBACK_THESIS.caveman;
353
- }
354
-
355
- export function reinforcementLine(mode: Mode): string {
356
- const thesis = getThesisLine(mode);
357
- return (
358
- `CAVEMAN MODE ACTIVE (${mode}). ${thesis} ` +
359
- "Answer only what was asked: no unrequested background, lists, examples, walkthroughs, or follow-up offers; " +
360
- "give code, steps, or warnings when the task needs them. " +
361
- "Security warnings, irreversible actions, multi-step order: normal prose. " +
362
- "Technical terms, code, commands, paths, and errors stay exact."
363
- );
364
- }
365
-
366
- // ── Mode parsing (mirrors caveman hooks/caveman-parse.js) ───────────────────
367
-
368
- const QUOTED_SPAN_REGEX = /(["`])(?:(?!\1).)*\1/g;
369
-
370
- export function normalizeModeArg(arg: string): string {
371
- return (arg || "").replace(/^[^a-z0-9]+/, "").replace(/[^a-z0-9-]+$/, "");
372
- }
373
-
374
- export interface ModeResolution {
375
- action: "set" | "clear" | "status" | "unresolved";
376
- mode?: Mode;
377
- }
378
-
379
- export function resolveModeArg(rawArg: string, getDefault: () => Mode | "off"): ModeResolution {
380
- const arg = normalizeModeArg(rawArg);
381
- if (!arg) {
382
- if (rawArg) return { action: "unresolved" };
383
- const def = getDefault();
384
- return def === "off" ? { action: "clear" } : { action: "set", mode: def };
385
- }
386
- if (arg === "off" || arg === "stop" || arg === "disable") return { action: "clear" };
387
- if (arg === "status") return { action: "status" };
388
- const canon = canonicalMode(arg);
389
- if (canon) return { action: "set", mode: canon };
390
- return { action: "unresolved" };
391
- }
392
-
393
- // Whitelist gap between activation verb and "caveman" to prevent false positives
394
- const ACTIVATION_VERBS = "(?:activate|enable|start|turn on|use|switch to|want|give me)";
395
- const ACTIVATION_GAP = "(?:\\s+(?:the|to|into|on|in|please|now|it|me|my|this|that|mode))*";
396
- const ACTIVATION_VERB_PHRASE = new RegExp(
397
- "\\b" + ACTIVATION_VERBS + "\\b" + ACTIVATION_GAP + "\\s+caveman\\b"
398
- );
399
- const ACTIVATION_TALK_LIKE = /\btalk\s+like\s+(?:a\s+|an\s+|the\s+)?caveman\b/;
400
-
401
- // Negation guard: "don't activate caveman" must not activate caveman
402
- const NEGATOR = /\b(?:don['’]?t|do not|doesn['’]?t|does not|won['’]?t|will not|never|no need to|rather not)\b/;
403
- const CLAUSE_BOUNDARY = /[.;!?,:—–]|\s-+\s|\bbut\b|\bthen\b/g;
404
-
405
- export function negatedBefore(text: string, index: number): boolean {
406
- CLAUSE_BOUNDARY.lastIndex = 0;
407
- let clauseStart = 0;
408
- let m: RegExpExecArray | null;
409
- while ((m = CLAUSE_BOUNDARY.exec(text)) !== null) {
410
- if (m.index >= index) break;
411
- clauseStart = m.index + m[0].length;
412
- }
413
- return NEGATOR.test(text.slice(clauseStart, index));
414
- }
415
-
416
- const BREVITY_TRIGGER = /\b(less tokens|fewer tokens|be brief|be terse|shorter answers)\b(?!\s+(in|for|on|about|when|during|with)\b)/;
417
-
418
- const ACTIVATION_TRIGGERS: RegExp[] = [
419
- ACTIVATION_VERB_PHRASE,
420
- ACTIVATION_TALK_LIKE,
421
- /\bcaveman\s+mode\s+(on|please|now)\b/,
422
- /^caveman(\s+mode)?\s*[.!]*$/,
423
- BREVITY_TRIGGER,
424
- ].map((re) => new RegExp(re.source, re.flags.includes("g") ? re.flags : re.flags + "g"));
425
-
426
- export function wantsActivation(text: string): boolean {
427
- for (const re of ACTIVATION_TRIGGERS) {
428
- re.lastIndex = 0;
429
- let m: RegExpExecArray | null;
430
- while ((m = re.exec(text)) !== null) {
431
- if (!negatedBefore(text, m.index)) return true;
432
- if (m.index === re.lastIndex) re.lastIndex++;
433
- }
434
- }
435
- return false;
436
- }
437
-
438
- export function parseModeChange(promptRaw: string): Mode | "off" | null {
439
- let prompt = (promptRaw || "").trim();
440
- if (!prompt) return null;
441
-
442
- const collapsed = prompt.toLowerCase().replace(/\s+/g, " ");
443
- const naturalLanguage = !prompt.startsWith("/");
444
- const nlPrompt = naturalLanguage ? collapsed.replace(QUOTED_SPAN_REGEX, " ") : "";
445
-
446
- // Natural-language deactivation (checked first)
447
- if (naturalLanguage) {
448
- const wantsOff =
449
- /\b(stop|disable|deactivate|quit|exit|kill)\s+(the\s+)?caveman\b/.test(nlPrompt) ||
450
- /\bcaveman(\s+mode)?\s+(off|stop|disabled?)\b/.test(nlPrompt) ||
451
- /\bturn\s+off\s+(the\s+)?caveman\b/.test(nlPrompt) ||
452
- /^(please\s+)?(go\s+|back\s+to\s+|switch\s+(back\s+)?to\s+|return\s+to\s+)?normal\s+mode\b/.test(nlPrompt) ||
453
- (/\bnormal\s+mode\b/.test(nlPrompt) && /\bcaveman\b/.test(nlPrompt));
454
-
455
- if (wantsOff) return "off";
456
-
457
- // Direct invocation keywords
458
- const ultraIdx = nlPrompt.search(/\bultracave\b/);
459
- if (ultraIdx !== -1 && !negatedBefore(nlPrompt, ultraIdx)) {
460
- return "ultracave";
461
- }
462
- const megaIdx = nlPrompt.search(/\bmegacave\b/);
463
- if (megaIdx !== -1 && !negatedBefore(nlPrompt, megaIdx)) {
464
- return "megacave";
465
- }
466
-
467
- // Natural-language activation (exclude questions)
468
- const isQuestion =
469
- /^(what|whats|what's|how|why|when|where|who|does|do|did|is|are|can|could|would|should|tell me|explain)\b/.test(nlPrompt);
470
-
471
- if (!isQuestion && wantsActivation(nlPrompt)) {
472
- const def = resolveDefault();
473
- return def !== "off" ? def : null;
474
- }
475
- }
476
-
477
- // Slash commands
478
- if (prompt.startsWith("/")) {
479
- const parts = prompt.split(/\s+/);
480
- const cmd = parts[0].toLowerCase();
481
- const rawArg = parts[1] || "";
482
-
483
- if (cmd === "/ultracave" || cmd === "/caveman:ultracave") {
484
- return "ultracave";
485
- }
486
- if (cmd === "/megacave" || cmd === "/caveman:megacave") {
487
- return "megacave";
488
- }
489
- if (cmd === "/caveman" || cmd === "/caveman:caveman") {
490
- const res = resolveModeArg(rawArg, resolveDefault);
491
- if (res.action === "set" && res.mode) return res.mode;
492
- if (res.action === "clear") return "off";
493
- return null;
494
- }
495
- }
496
-
497
- return null;
498
- }
499
-
500
- // ── Argument completions ────────────────────────────────────────────────────
501
-
502
- const MODE_CHOICES = [
503
- { value: "caveman", label: "caveman", description: "smart caveman voice (default)" },
504
- { value: "ultracave", label: "ultracave", description: "maximum compression, grammar stripped" },
505
- { value: "megacave", label: "megacave", description: "Classical Chinese (文言文)" },
506
- { value: "status", label: "status", description: "show current mode and stats" },
507
- { value: "off", label: "off", description: "disabled" },
508
- ];
509
-
510
- function getModeCompletions(prefix: string) {
511
- const lower = prefix.toLowerCase();
512
- const matches = MODE_CHOICES.filter(m =>
513
- m.value.startsWith(lower) || m.label.startsWith(lower)
514
- );
515
- return matches.length > 0 ? matches : null;
516
- }
517
-
518
- // ── Status display ──────────────────────────────────────────────────────────
519
-
520
- function displayStatus(
521
- pi: ExtensionAPI,
522
- ctx: { hasUI: boolean; ui: { notify(msg: string, level?: "info" | "warning" | "error"): void } },
523
- ): void {
524
- const active = readFlag();
525
- const def = resolveDefault();
526
- const configPath = join(cavemanConfigDir(), "config.json");
527
- const repoConfig = findRepoConfig(process.cwd());
528
- const mode = active || "off";
529
-
530
- const mc = modeColor(mode);
531
-
532
- const lines: string[] = [
533
- `${BOLD}Caveman${RST}: ${mc}${mode}${RST}${def !== mode ? ` ${DIM}(default: ${def})${RST}` : ""}`,
534
- "",
535
- ` ${sessionStats.turns} turns ${DIM}│${RST} ${sessionStats.outputTokens.toLocaleString()} out ${DIM}│${RST} ${sessionStats.cacheReadTokens.toLocaleString()} cached ${DIM}│${RST} ${sessionStats.inputTokens.toLocaleString()} in`,
536
- ];
537
-
538
- const savings = estimateSavings(sessionStats.outputTokens, mode);
539
- if (savings && savings.estSaved > 0) {
540
- lines.push(
541
- "",
542
- ` saved ${GREEN}${savings.estSaved.toLocaleString()}${RST} tokens ${DIM}(~${savings.pct}%)${RST} ${GREEN}${bar(savings.pct)}${RST}`,
543
- );
544
- }
545
-
546
- const configLines: string[] = [];
547
- if (process.env.CAVEMAN_DEFAULT_MODE) {
548
- configLines.push(` env ${DIM}CAVEMAN_DEFAULT_MODE=${process.env.CAVEMAN_DEFAULT_MODE}${RST}`);
549
- }
550
- if (existsSync(configPath)) configLines.push(` user ${DIM}${truncatePath(configPath)}${RST}`);
551
- if (repoConfig) configLines.push(` repo ${DIM}${truncatePath(repoConfig)}${RST}`);
552
- configLines.push(` flag ${DIM}${truncatePath(getFlagPath())}${RST}`);
553
-
554
- if (configLines.length) {
555
- lines.push("", ...configLines);
556
- }
557
-
558
- const msg = lines.join("\n");
559
- if (ctx.hasUI) ctx.ui.notify(msg, "info");
560
- pi.sendMessage({
561
- content: msg,
562
- attribution: "user",
563
- }, { triggerTurn: false });
564
- }
565
-
566
- // ── Extension factory ───────────────────────────────────────────────────────
567
-
568
- export default function cavemanExtension(pi: ExtensionAPI) {
569
- let lastInjectedMode: Mode | null = null;
570
-
571
- // ── session_start: auto-activate ──────────────────────────────────────
572
- pi.on("session_start", async (event, ctx) => {
573
- const e = event as Record<string, unknown> | undefined;
574
- const reason = e?.reason as string | undefined;
575
- const isContinuation = reason === "resume" || reason === "reload" || reason === "fork";
576
- if (!isContinuation) {
577
- sessionStats = { turns: 0, outputTokens: 0, cacheReadTokens: 0, inputTokens: 0 };
578
- sessionExplicitOff = false;
579
- lastInjectedMode = null;
580
- }
581
-
582
- let mode = readFlag();
583
- if (!mode && !sessionExplicitOff) {
584
- const def = resolveDefault();
585
- if (def !== "off") mode = def;
586
- }
587
- if (!mode || (mode as string) === "off") {
588
- deleteFlag();
589
- clearStatus(ctx);
590
- return;
591
- }
592
- applyMode(mode);
593
- notifyMode(ctx, mode);
594
- });
595
-
596
- // ── turn_end: accumulate token stats ─────────────────────────────────
597
- pi.on("turn_end", (event) => {
598
- const e = event as unknown as Record<string, unknown>;
599
- const msg = e?.message as Record<string, unknown> | undefined;
600
- const usage = msg?.usage as Record<string, number> | undefined;
601
- if (usage) {
602
- sessionStats.turns++;
603
- sessionStats.outputTokens += usage.output ?? 0;
604
- sessionStats.cacheReadTokens += usage.cacheRead ?? 0;
605
- sessionStats.inputTokens += usage.input ?? 0;
606
- }
607
- });
608
-
609
- // ── /caveman command ──────────────────────────────────────────────────
610
- pi.registerCommand("caveman", {
611
- description: "Switch and persist caveman mode (caveman|ultracave|megacave|status|off)",
612
- getArgumentCompletions: (prefix) => getModeCompletions(prefix),
613
- handler: async (args, ctx) => {
614
- const rawArg = (args || "").trim();
615
-
616
- // Bare /caveman -> activate default and persist
617
- if (!rawArg) {
618
- const def = resolveDefault();
619
- const mode = def === "off" ? "caveman" : def;
620
- sessionExplicitOff = false;
621
- lastInjectedMode = null;
622
- applyMode(mode);
623
- saveUserConfigMode(mode);
624
- notifyMode(ctx, mode);
625
- return;
626
- }
627
-
628
- const res = resolveModeArg(rawArg, resolveDefault);
629
-
630
- if (res.action === "status") {
631
- displayStatus(pi, ctx);
632
- return;
633
- }
634
-
635
- if (res.action === "set" && res.mode) {
636
- sessionExplicitOff = false;
637
- lastInjectedMode = null;
638
- applyMode(res.mode);
639
- saveUserConfigMode(res.mode);
640
- notifyMode(ctx, res.mode);
641
- return;
642
- }
643
-
644
- if (res.action === "clear") {
645
- sessionExplicitOff = true;
646
- lastInjectedMode = null;
647
- applyMode("off");
648
- saveUserConfigMode("off");
649
- clearStatus(ctx);
650
- return;
651
- }
652
-
653
- // Unknown
654
- if (ctx.hasUI) {
655
- ctx.ui.notify(
656
- `unknown mode "${rawArg}". Use: caveman|ultracave|megacave|status|off`,
657
- "warning",
658
- );
659
- }
660
- },
661
- });
662
-
663
- // ── /ultracave command ────────────────────────────────────────────────
664
- pi.registerCommand("ultracave", {
665
- description: "Switch to ultracave mode (maximum compression, fragments only)",
666
- handler: async (_args, ctx) => {
667
- sessionExplicitOff = false;
668
- lastInjectedMode = null;
669
- applyMode("ultracave");
670
- saveUserConfigMode("ultracave");
671
- notifyMode(ctx, "ultracave");
672
- },
673
- });
674
-
675
- // ── /megacave command ─────────────────────────────────────────────────
676
- pi.registerCommand("megacave", {
677
- description: "Switch to megacave mode (Classical Chinese 文言文)",
678
- handler: async (_args, ctx) => {
679
- sessionExplicitOff = false;
680
- lastInjectedMode = null;
681
- applyMode("megacave");
682
- saveUserConfigMode("megacave");
683
- notifyMode(ctx, "megacave");
684
- },
685
- });
686
-
687
- // ── /caveman-status command ────────────────────────────────────────────
688
- pi.registerCommand("caveman-status", {
689
- description: "Show current caveman mode and config",
690
- handler: async (_args, ctx) => {
691
- displayStatus(pi, ctx);
692
- },
693
- });
694
-
695
- // ── before_agent_start: per-turn reinforcement ────────────────────────
696
- // Injects full SKILL.md content on activation / mode-switch.
697
- // Subsequent continuing turns use a lightweight single-line reminder to preserve tokens & prompt cache.
698
- pi.on("before_agent_start", async (_event, _ctx) => {
699
- let active = readFlag();
700
- if (!active && !sessionExplicitOff) {
701
- const def = resolveDefault();
702
- if (def !== "off") active = def;
703
- }
704
- if (!active || (active as string) === "off") {
705
- lastInjectedMode = null;
706
- return null;
707
- }
708
-
709
- const modeChanged = active !== lastInjectedMode;
710
- lastInjectedMode = active;
711
-
712
- let content: string;
713
- if (modeChanged) {
714
- const skillContent = loadSkillContent(active);
715
- const header = `CAVEMAN MODE ACTIVE — mode: ${active}\n\n`;
716
- content = skillContent
717
- ? header + skillContent
718
- : reinforcementLine(active);
719
- } else {
720
- content = reinforcementLine(active);
721
- }
722
-
723
- return {
724
- message: {
725
- customType: "caveman-reinforcement",
726
- content,
727
- display: false,
728
- },
729
- };
730
- });
731
-
732
- // ── input: intercept user prompts for mode changes ─────────────────────
733
- pi.on("input", async (event, _ctx) => {
734
- if (!event || typeof event !== "object" || !("text" in event)) return;
735
- const text = event.text;
736
- if (typeof text !== "string") return;
737
- const change = parseModeChange(text);
738
- if (change) {
739
- if (change === "off") {
740
- sessionExplicitOff = true;
741
- lastInjectedMode = null;
742
- } else {
743
- sessionExplicitOff = false;
744
- lastInjectedMode = null;
745
- }
746
- applyMode(change);
747
- saveUserConfigMode(change);
748
- }
749
- });
750
- }
1
+ // pi-caveman — pi & oh-my-pi extension
2
+ //
3
+ // Caveman mode for pi & oh-my-pi: auto-activates per session, /caveman commands,
4
+ // per-turn reinforcement injection.
5
+ //
6
+ // Flag file: ~/.pi/.caveman-active or ~/.omp/.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 & Canonical Mode Mapping ─────────────────────────────────────
24
+
25
+ export const VALID_MODES = ["caveman", "ultracave", "megacave"] as const;
26
+ export type Mode = (typeof VALID_MODES)[number];
27
+
28
+ export const LEGACY_MODE_MAP: Record<string, Mode> = {
29
+ "full": "caveman",
30
+ "lite": "caveman",
31
+ "ultra": "ultracave",
32
+ "wenyan": "megacave",
33
+ "wenyan-lite": "megacave",
34
+ "wenyan-full": "megacave",
35
+ "wenyan-ultra": "megacave",
36
+ };
37
+
38
+ export function canonicalMode(raw: string): Mode | null {
39
+ const lower = raw.trim().toLowerCase();
40
+ if ((VALID_MODES as readonly string[]).includes(lower)) return lower as Mode;
41
+ return LEGACY_MODE_MAP[lower] ?? null;
42
+ }
43
+
44
+ // ── Session stats ───────────────────────────────────────────────────────────
45
+
46
+ interface SessionStats {
47
+ turns: number;
48
+ outputTokens: number;
49
+ cacheReadTokens: number;
50
+ inputTokens: number;
51
+ }
52
+
53
+ let sessionStats: SessionStats = {
54
+ turns: 0, outputTokens: 0, cacheReadTokens: 0, inputTokens: 0,
55
+ };
56
+
57
+ let sessionExplicitOff = false;
58
+
59
+ export const COMPRESSION_RATIOS: Record<string, number> = {
60
+ caveman: 0.65,
61
+ ultracave: 0.75,
62
+ megacave: 0.80,
63
+ // legacy aliases for backwards compatibility
64
+ full: 0.65,
65
+ lite: 0.35,
66
+ ultra: 0.75,
67
+ wenyan: 0.80,
68
+ "wenyan-lite": 0.60,
69
+ "wenyan-full": 0.80,
70
+ "wenyan-ultra": 0.85,
71
+ };
72
+
73
+ export function estimateSavings(outputTokens: number, mode: string) {
74
+ const canon = canonicalMode(mode) || mode;
75
+ const ratio = COMPRESSION_RATIOS[canon] ?? COMPRESSION_RATIOS[mode];
76
+ if (!ratio) return null;
77
+ const estWithout = Math.round(outputTokens / (1 - ratio));
78
+ const estSaved = estWithout - outputTokens;
79
+ return { estWithout, estSaved, pct: Math.round(ratio * 100) };
80
+ }
81
+
82
+ // ── Display helpers ────────────────────────────────────────────────────────
83
+
84
+ const ESC = "\x1b[";
85
+ const RST = `${ESC}0m`;
86
+ const DIM = `${ESC}2m`;
87
+ const BOLD = `${ESC}1m`;
88
+ const GREEN = `${ESC}32m`;
89
+ const CYAN = `${ESC}36m`;
90
+ const GRAY = `${ESC}90m`;
91
+
92
+ export function modeColor(mode: string): string {
93
+ if (mode === "off") return GRAY;
94
+ if (mode === "megacave" || mode.startsWith("wenyan")) return CYAN;
95
+ return GREEN; // caveman, ultracave, full, ultra
96
+ }
97
+
98
+ function bar(pct: number, width = 20): string {
99
+ const filled = Math.round((pct / 100) * width);
100
+ return "█".repeat(filled) + "░".repeat(width - filled);
101
+ }
102
+
103
+ function truncatePath(p: string, max = 40): string {
104
+ if (p.length <= max) return p;
105
+ const parts = p.split(sep);
106
+ const tail = parts.slice(-2).join(sep);
107
+ return "…" + sep + tail;
108
+ }
109
+
110
+ // ── Paths & Host Resolution ─────────────────────────────────────────────────
111
+
112
+ export function resolveHostDir(): string {
113
+ const isOmp =
114
+ process.title === "omp" ||
115
+ Boolean(process.env.OMP_PROFILE) ||
116
+ process.env.PI_CONFIG_DIR === ".omp" ||
117
+ Boolean(process.env.OMP_AUTORESEARCH_DB_DIR) ||
118
+ (typeof process.argv[1] === "string" && process.argv[1].includes("@oh-my-pi"));
119
+ const dirName = isOmp ? "omp" : "pi";
120
+ const xdg = process.env.XDG_CONFIG_HOME;
121
+ return xdg ? join(xdg, dirName) : join(homedir(), `.${dirName}`);
122
+ }
123
+
124
+ export function getFlagPath(): string {
125
+ return join(resolveHostDir(), ".caveman-active");
126
+ }
127
+
128
+ // ── Config resolution (mirrors caveman/src/hooks/caveman-config.js) ─────────
129
+
130
+ export function cavemanConfigDir(): string {
131
+ const xdgHome = process.env.XDG_CONFIG_HOME;
132
+ if (xdgHome) return join(xdgHome, "caveman");
133
+ if (process.platform === "win32") {
134
+ return join(
135
+ process.env.APPDATA || join(homedir(), "AppData", "Roaming"),
136
+ "caveman",
137
+ );
138
+ }
139
+ return join(homedir(), ".config", "caveman");
140
+ }
141
+
142
+ export function findRepoConfig(start: string): string | null {
143
+ let dir = start;
144
+ for (let i = 0; i < 64; i++) {
145
+ const a = join(dir, ".caveman", "config.json");
146
+ if (existsSync(a)) return a;
147
+ const b = join(dir, ".caveman.json");
148
+ if (existsSync(b)) return b;
149
+ const parent = dirname(dir);
150
+ if (parent === dir) break;
151
+ dir = parent;
152
+ }
153
+ return null;
154
+ }
155
+
156
+ export function readConfigMode(configPath: string): string | null {
157
+ try {
158
+ const parsed = JSON.parse(readFileSync(configPath, "utf-8"));
159
+ const m = parsed?.defaultMode;
160
+ return typeof m === "string" ? m : null;
161
+ } catch {
162
+ return null;
163
+ }
164
+ }
165
+
166
+ export function resolveDefault(): Mode | "off" {
167
+ // 1. Env var (short-circuits)
168
+ const env = process.env.CAVEMAN_DEFAULT_MODE;
169
+ if (env) {
170
+ const lower = env.toLowerCase();
171
+ if (lower === "off") return "off";
172
+ const canon = canonicalMode(lower);
173
+ if (canon) return canon;
174
+ }
175
+ // 2. Repo-local config
176
+ const repo = findRepoConfig(process.cwd());
177
+ if (repo) {
178
+ const m = readConfigMode(repo);
179
+ if (m) {
180
+ const lower = m.toLowerCase();
181
+ if (lower === "off") return "off";
182
+ const canon = canonicalMode(lower);
183
+ if (canon) return canon;
184
+ }
185
+ }
186
+ // 3. User config
187
+ const user = join(cavemanConfigDir(), "config.json");
188
+ if (existsSync(user)) {
189
+ const m = readConfigMode(user);
190
+ if (m) {
191
+ const lower = m.toLowerCase();
192
+ if (lower === "off") return "off";
193
+ const canon = canonicalMode(lower);
194
+ if (canon) return canon;
195
+ }
196
+ }
197
+ // 4. Default
198
+ return "caveman";
199
+ }
200
+
201
+ // ── Flag I/O ────────────────────────────────────────────────────────────────
202
+
203
+ export function readFlag(): Mode | null {
204
+ const flagPath = getFlagPath();
205
+ try {
206
+ if (existsSync(flagPath)) {
207
+ const content = readFileSync(flagPath, "utf-8").trim();
208
+ return canonicalMode(content);
209
+ }
210
+ } catch {}
211
+
212
+ // Fallback: cross-host check if running under omp but flag written in ~/.pi (or vice versa)
213
+ try {
214
+ const xdg = process.env.XDG_CONFIG_HOME;
215
+ const fallbackDir = flagPath.includes(".omp")
216
+ ? (xdg ? join(xdg, "pi") : join(homedir(), ".pi"))
217
+ : (xdg ? join(xdg, "omp") : join(homedir(), ".omp"));
218
+ const fallbackPath = join(fallbackDir, ".caveman-active");
219
+ if (existsSync(fallbackPath)) {
220
+ const content = readFileSync(fallbackPath, "utf-8").trim();
221
+ return canonicalMode(content);
222
+ }
223
+ } catch {}
224
+
225
+ return null;
226
+ }
227
+
228
+ export function writeFlag(mode: Mode): void {
229
+ const flagPath = getFlagPath();
230
+ try {
231
+ const dir = dirname(flagPath);
232
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
233
+ const tmp = `${flagPath}.tmp.${process.pid}`;
234
+ writeFileSync(tmp, mode, { mode: 0o600 });
235
+ renameSync(tmp, flagPath);
236
+ } catch {
237
+ // Silent fail — never block session
238
+ }
239
+ }
240
+
241
+ export function deleteFlag(): void {
242
+ const flagPath = getFlagPath();
243
+ try { if (existsSync(flagPath)) unlinkSync(flagPath); } catch {}
244
+ try {
245
+ const xdg = process.env.XDG_CONFIG_HOME;
246
+ const fallbackDir = flagPath.includes(".omp")
247
+ ? (xdg ? join(xdg, "pi") : join(homedir(), ".pi"))
248
+ : (xdg ? join(xdg, "omp") : join(homedir(), ".omp"));
249
+ const fallbackPath = join(fallbackDir, ".caveman-active");
250
+ if (existsSync(fallbackPath)) unlinkSync(fallbackPath);
251
+ } catch {}
252
+ }
253
+
254
+ function logModeChange(newMode: Mode | null): void {
255
+ try {
256
+ const prev = readFlag();
257
+ if (prev === newMode) return;
258
+ const dir = dirname(getFlagPath());
259
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
260
+ const entry = JSON.stringify({
261
+ ts: new Date().toISOString(), mode: newMode, prev,
262
+ }) + "\n";
263
+ appendFileSync(join(dir, ".caveman-mode-log.jsonl"), entry, { mode: 0o600 });
264
+ } catch {}
265
+ }
266
+
267
+ export function saveUserConfigMode(mode: string): void {
268
+ try {
269
+ const configDir = cavemanConfigDir();
270
+ const cfgPath = join(configDir, "config.json");
271
+ if (!existsSync(configDir)) mkdirSync(configDir, { recursive: true });
272
+ let existing: Record<string, unknown> = {};
273
+ if (existsSync(cfgPath)) {
274
+ try { existing = JSON.parse(readFileSync(cfgPath, "utf-8")); } catch {}
275
+ }
276
+ existing.defaultMode = mode;
277
+ writeFileSync(cfgPath, JSON.stringify(existing, null, 2) + "\n", { mode: 0o600 });
278
+ } catch {}
279
+ }
280
+
281
+ export function applyMode(mode: Mode | "off"): void {
282
+ if (mode === "off") { logModeChange(null); deleteFlag(); }
283
+ else { logModeChange(mode); writeFlag(mode); }
284
+ }
285
+
286
+ interface UI {
287
+ hasUI: boolean;
288
+ ui: {
289
+ notify(msg: string, level?: "info" | "warning" | "error"): void;
290
+ setStatus?(key: string, text: string | undefined): void;
291
+ };
292
+ }
293
+
294
+ function notifyMode(ui: UI, mode: string): void {
295
+ if (!ui.hasUI) return;
296
+ ui.ui.notify(`caveman: ${mode}`, "info");
297
+ ui.ui.setStatus?.("caveman", undefined);
298
+ }
299
+
300
+ function clearStatus(ui: UI): void {
301
+ if (!ui.hasUI) return;
302
+ ui.ui.setStatus?.("caveman", undefined);
303
+ ui.ui.notify("caveman: off", "info");
304
+ }
305
+
306
+ // ── SKILL.md and Thesis loading (mirrors caveman 3.2.0) ─────────────────────
307
+
308
+ export function findSkillPath(skillId: string): string | null {
309
+ const candidates = [
310
+ join(__dirname, "..", "skills", skillId, "SKILL.md"),
311
+ join(__dirname, "skills", skillId, "SKILL.md"),
312
+ ];
313
+ for (const candidate of candidates) {
314
+ if (existsSync(candidate)) return candidate;
315
+ }
316
+ return null;
317
+ }
318
+
319
+ export function loadSkillContent(mode: Mode): string | null {
320
+ const skillPath = findSkillPath(mode);
321
+ if (!skillPath) return null;
322
+ try {
323
+ const raw = readFileSync(skillPath, "utf-8");
324
+ return raw.replace(/^---[\s\S]*?---\s*/, "");
325
+ } catch {
326
+ return null;
327
+ }
328
+ }
329
+
330
+ export const FALLBACK_THESIS: Record<Mode, string> = {
331
+ caveman: "Respond terse like smart caveman. All technical substance stay. Only fluff die.",
332
+ ultracave: "Respond terse like smart caveman. All technical substance stay. Only fluff die. Then cut again.",
333
+ megacave: "以文言答。技術之實皆存,唯贅言去之。",
334
+ };
335
+
336
+ export function getThesisLine(mode: Mode): string {
337
+ const skillPath = findSkillPath(mode);
338
+ if (skillPath) {
339
+ try {
340
+ const raw = readFileSync(skillPath, "utf-8");
341
+ const body = raw.replace(/^---[\s\S]*?---\s*/, "");
342
+ const lines = body.split("\n");
343
+ const titleIndex = lines.findIndex((l) => l.trim().startsWith("# "));
344
+ if (titleIndex !== -1) {
345
+ for (let i = titleIndex + 1; i < lines.length; i++) {
346
+ const line = lines[i].trim();
347
+ if (line) return line;
348
+ }
349
+ }
350
+ } catch {}
351
+ }
352
+ return FALLBACK_THESIS[mode] ?? FALLBACK_THESIS.caveman;
353
+ }
354
+
355
+ export function reinforcementLine(mode: Mode): string {
356
+ const thesis = getThesisLine(mode);
357
+ return (
358
+ `CAVEMAN MODE ACTIVE (${mode}). ${thesis} ` +
359
+ "Answer only what was asked: no unrequested background, lists, examples, walkthroughs, or follow-up offers; " +
360
+ "give code, steps, or warnings when the task needs them. " +
361
+ "Security warnings, irreversible actions, multi-step order: normal prose. " +
362
+ "Technical terms, code, commands, paths, and errors stay exact."
363
+ );
364
+ }
365
+
366
+ // ── Mode parsing (mirrors caveman hooks/caveman-parse.js) ───────────────────
367
+
368
+ const QUOTED_SPAN_REGEX = /(["`])(?:(?!\1).)*\1/g;
369
+
370
+ export function normalizeModeArg(arg: string): string {
371
+ return (arg || "").replace(/^[^a-z0-9]+/, "").replace(/[^a-z0-9-]+$/, "");
372
+ }
373
+
374
+ export interface ModeResolution {
375
+ action: "set" | "clear" | "status" | "unresolved";
376
+ mode?: Mode;
377
+ }
378
+
379
+ export function resolveModeArg(rawArg: string, getDefault: () => Mode | "off"): ModeResolution {
380
+ const arg = normalizeModeArg(rawArg);
381
+ if (!arg) {
382
+ if (rawArg) return { action: "unresolved" };
383
+ const def = getDefault();
384
+ return def === "off" ? { action: "clear" } : { action: "set", mode: def };
385
+ }
386
+ if (arg === "off" || arg === "stop" || arg === "disable") return { action: "clear" };
387
+ if (arg === "status") return { action: "status" };
388
+ const canon = canonicalMode(arg);
389
+ if (canon) return { action: "set", mode: canon };
390
+ return { action: "unresolved" };
391
+ }
392
+
393
+ // Whitelist gap between activation verb and "caveman" to prevent false positives
394
+ const ACTIVATION_VERBS = "(?:activate|enable|start|turn on|use|switch to|want|give me)";
395
+ const ACTIVATION_GAP = "(?:\\s+(?:the|to|into|on|in|please|now|it|me|my|this|that|mode))*";
396
+ const ACTIVATION_VERB_PHRASE = new RegExp(
397
+ "\\b" + ACTIVATION_VERBS + "\\b" + ACTIVATION_GAP + "\\s+caveman\\b"
398
+ );
399
+ const ACTIVATION_TALK_LIKE = /\btalk\s+like\s+(?:a\s+|an\s+|the\s+)?caveman\b/;
400
+
401
+ // Negation guard: "don't activate caveman" must not activate caveman
402
+ const NEGATOR = /\b(?:don['’]?t|do not|doesn['’]?t|does not|won['’]?t|will not|never|no need to|rather not)\b/;
403
+ const CLAUSE_BOUNDARY = /[.;!?,:—–]|\s-+\s|\bbut\b|\bthen\b/g;
404
+
405
+ export function negatedBefore(text: string, index: number): boolean {
406
+ CLAUSE_BOUNDARY.lastIndex = 0;
407
+ let clauseStart = 0;
408
+ let m: RegExpExecArray | null;
409
+ while ((m = CLAUSE_BOUNDARY.exec(text)) !== null) {
410
+ if (m.index >= index) break;
411
+ clauseStart = m.index + m[0].length;
412
+ }
413
+ return NEGATOR.test(text.slice(clauseStart, index));
414
+ }
415
+
416
+ const BREVITY_TRIGGER = /\b(less tokens|fewer tokens|be brief|be terse|shorter answers)\b(?!\s+(in|for|on|about|when|during|with)\b)/;
417
+
418
+ const ACTIVATION_TRIGGERS: RegExp[] = [
419
+ ACTIVATION_VERB_PHRASE,
420
+ ACTIVATION_TALK_LIKE,
421
+ /\bcaveman\s+mode\s+(on|please|now)\b/,
422
+ /^caveman(\s+mode)?\s*[.!]*$/,
423
+ BREVITY_TRIGGER,
424
+ ].map((re) => new RegExp(re.source, re.flags.includes("g") ? re.flags : re.flags + "g"));
425
+
426
+ export function wantsActivation(text: string): boolean {
427
+ for (const re of ACTIVATION_TRIGGERS) {
428
+ re.lastIndex = 0;
429
+ let m: RegExpExecArray | null;
430
+ while ((m = re.exec(text)) !== null) {
431
+ if (!negatedBefore(text, m.index)) return true;
432
+ if (m.index === re.lastIndex) re.lastIndex++;
433
+ }
434
+ }
435
+ return false;
436
+ }
437
+
438
+ export function parseModeChange(promptRaw: string): Mode | "off" | null {
439
+ let prompt = (promptRaw || "").trim();
440
+ if (!prompt) return null;
441
+
442
+ const collapsed = prompt.toLowerCase().replace(/\s+/g, " ");
443
+ const naturalLanguage = !prompt.startsWith("/");
444
+ const nlPrompt = naturalLanguage ? collapsed.replace(QUOTED_SPAN_REGEX, " ") : "";
445
+
446
+ // Natural-language deactivation (checked first)
447
+ if (naturalLanguage) {
448
+ const wantsOff =
449
+ /\b(stop|disable|deactivate|quit|exit|kill)\s+(the\s+)?caveman\b/.test(nlPrompt) ||
450
+ /\bcaveman(\s+mode)?\s+(off|stop|disabled?)\b/.test(nlPrompt) ||
451
+ /\bturn\s+off\s+(the\s+)?caveman\b/.test(nlPrompt) ||
452
+ /^(please\s+)?(go\s+|back\s+to\s+|switch\s+(back\s+)?to\s+|return\s+to\s+)?normal\s+mode\b/.test(nlPrompt) ||
453
+ (/\bnormal\s+mode\b/.test(nlPrompt) && /\bcaveman\b/.test(nlPrompt));
454
+
455
+ if (wantsOff) return "off";
456
+
457
+ // Direct invocation keywords
458
+ const ultraIdx = nlPrompt.search(/\bultracave\b/);
459
+ if (ultraIdx !== -1 && !negatedBefore(nlPrompt, ultraIdx)) {
460
+ return "ultracave";
461
+ }
462
+ const megaIdx = nlPrompt.search(/\bmegacave\b/);
463
+ if (megaIdx !== -1 && !negatedBefore(nlPrompt, megaIdx)) {
464
+ return "megacave";
465
+ }
466
+
467
+ // Natural-language activation (exclude questions)
468
+ const isQuestion =
469
+ /^(what|whats|what's|how|why|when|where|who|does|do|did|is|are|can|could|would|should|tell me|explain)\b/.test(nlPrompt);
470
+
471
+ if (!isQuestion && wantsActivation(nlPrompt)) {
472
+ const def = resolveDefault();
473
+ return def !== "off" ? def : null;
474
+ }
475
+ }
476
+
477
+ // Slash commands
478
+ if (prompt.startsWith("/")) {
479
+ const parts = prompt.split(/\s+/);
480
+ const cmd = parts[0].toLowerCase();
481
+ const rawArg = parts[1] || "";
482
+
483
+ if (cmd === "/caveman" || cmd === "/caveman:caveman") {
484
+ const res = resolveModeArg(rawArg, resolveDefault);
485
+ if (res.action === "set" && res.mode) return res.mode;
486
+ if (res.action === "clear") return "off";
487
+ return null;
488
+ }
489
+ }
490
+
491
+ return null;
492
+ }
493
+
494
+ // ── Argument completions ────────────────────────────────────────────────────
495
+
496
+ const MODE_CHOICES = [
497
+ { value: "caveman", label: "caveman", description: "smart caveman voice (default)" },
498
+ { value: "ultracave", label: "ultracave", description: "maximum compression, grammar stripped" },
499
+ { value: "megacave", label: "megacave", description: "Classical Chinese (文言文)" },
500
+ { value: "status", label: "status", description: "show current mode and stats" },
501
+ { value: "off", label: "off", description: "disabled" },
502
+ ];
503
+
504
+ function getModeCompletions(prefix: string) {
505
+ const lower = prefix.toLowerCase();
506
+ const matches = MODE_CHOICES.filter(m =>
507
+ m.value.startsWith(lower) || m.label.startsWith(lower)
508
+ );
509
+ return matches.length > 0 ? matches : null;
510
+ }
511
+
512
+ // ── Status display ──────────────────────────────────────────────────────────
513
+
514
+ function displayStatus(
515
+ pi: ExtensionAPI,
516
+ ctx: { hasUI: boolean; ui: { notify(msg: string, level?: "info" | "warning" | "error"): void } },
517
+ ): void {
518
+ const active = readFlag();
519
+ const def = resolveDefault();
520
+ const configPath = join(cavemanConfigDir(), "config.json");
521
+ const repoConfig = findRepoConfig(process.cwd());
522
+ const mode = active || "off";
523
+
524
+ const mc = modeColor(mode);
525
+
526
+ const lines: string[] = [
527
+ `${BOLD}Caveman${RST}: ${mc}${mode}${RST}${def !== mode ? ` ${DIM}(default: ${def})${RST}` : ""}`,
528
+ "",
529
+ ` ${sessionStats.turns} turns ${DIM}│${RST} ${sessionStats.outputTokens.toLocaleString()} out ${DIM}│${RST} ${sessionStats.cacheReadTokens.toLocaleString()} cached ${DIM}│${RST} ${sessionStats.inputTokens.toLocaleString()} in`,
530
+ ];
531
+
532
+ const savings = estimateSavings(sessionStats.outputTokens, mode);
533
+ if (savings && savings.estSaved > 0) {
534
+ lines.push(
535
+ "",
536
+ ` saved ${GREEN}${savings.estSaved.toLocaleString()}${RST} tokens ${DIM}(~${savings.pct}%)${RST} ${GREEN}${bar(savings.pct)}${RST}`,
537
+ );
538
+ }
539
+
540
+ const configLines: string[] = [];
541
+ if (process.env.CAVEMAN_DEFAULT_MODE) {
542
+ configLines.push(` env ${DIM}CAVEMAN_DEFAULT_MODE=${process.env.CAVEMAN_DEFAULT_MODE}${RST}`);
543
+ }
544
+ if (existsSync(configPath)) configLines.push(` user ${DIM}${truncatePath(configPath)}${RST}`);
545
+ if (repoConfig) configLines.push(` repo ${DIM}${truncatePath(repoConfig)}${RST}`);
546
+ configLines.push(` flag ${DIM}${truncatePath(getFlagPath())}${RST}`);
547
+
548
+ if (configLines.length) {
549
+ lines.push("", ...configLines);
550
+ }
551
+
552
+ const msg = lines.join("\n");
553
+ if (ctx.hasUI) ctx.ui.notify(msg, "info");
554
+ pi.sendMessage({
555
+ customType: "caveman-status",
556
+ content: msg,
557
+ display: false,
558
+ }, { triggerTurn: false });
559
+ }
560
+
561
+ // ── Extension factory ───────────────────────────────────────────────────────
562
+
563
+ function isContinuationReason(reason: string | undefined): boolean {
564
+ return reason === "resume" || reason === "reload" || reason === "fork";
565
+ }
566
+
567
+ export default function cavemanExtension(pi: ExtensionAPI) {
568
+ let lastInjectedMode: Mode | null = null;
569
+
570
+ const resetSessionState = (): void => {
571
+ sessionStats = { turns: 0, outputTokens: 0, cacheReadTokens: 0, inputTokens: 0 };
572
+ sessionExplicitOff = false;
573
+ lastInjectedMode = null;
574
+ };
575
+
576
+ const activateSession = (ctx: UI): void => {
577
+ let mode = readFlag();
578
+ if (!mode && !sessionExplicitOff) {
579
+ const def = resolveDefault();
580
+ if (def !== "off") mode = def;
581
+ }
582
+ if (!mode || (mode as string) === "off") {
583
+ deleteFlag();
584
+ clearStatus(ctx);
585
+ return;
586
+ }
587
+ applyMode(mode);
588
+ notifyMode(ctx, mode);
589
+ };
590
+
591
+ // ── session boundaries: auto-activate ──────────────────────────────────
592
+ // pi reports lifecycle through session_start with a reason (startup|new|
593
+ // reload|resume|fork). oh-my-pi fires session_start only on initial load
594
+ // and reports mid-process switches as a separate session_switch event with
595
+ // a reason (new|resume|fork); pi never dispatches that event, so the extra
596
+ // registration is a no-op there. Its name is absent from ExtensionAPI's
597
+ // strict on() overloads, hence the loose typing.
598
+ const onSessionEvent = (pi as unknown as {
599
+ on: (event: string, handler: (event: unknown, ctx: UI) => Promise<void>) => unknown;
600
+ }).on;
601
+
602
+ const handleSessionBoundary = async (event: unknown, ctx: UI): Promise<void> => {
603
+ const e = event as Record<string, unknown> | undefined;
604
+ if (!isContinuationReason(e?.reason as string | undefined)) resetSessionState();
605
+ activateSession(ctx);
606
+ };
607
+
608
+ onSessionEvent("session_start", handleSessionBoundary);
609
+ onSessionEvent("session_switch", handleSessionBoundary);
610
+
611
+ // ── turn_end: accumulate token stats ─────────────────────────────────
612
+ pi.on("turn_end", (event) => {
613
+ const e = event as unknown as Record<string, unknown>;
614
+ const msg = e?.message as Record<string, unknown> | undefined;
615
+ const usage = msg?.usage as Record<string, number> | undefined;
616
+ if (usage) {
617
+ sessionStats.turns++;
618
+ sessionStats.outputTokens += usage.output ?? 0;
619
+ sessionStats.cacheReadTokens += usage.cacheRead ?? 0;
620
+ sessionStats.inputTokens += usage.input ?? 0;
621
+ }
622
+ });
623
+
624
+ // ── /caveman command ──────────────────────────────────────────────────
625
+ pi.registerCommand("caveman", {
626
+ description: "Switch and persist caveman mode (caveman|ultracave|megacave|status|off)",
627
+ getArgumentCompletions: (prefix) => getModeCompletions(prefix),
628
+ handler: async (args, ctx) => {
629
+ const rawArg = (args || "").trim();
630
+
631
+ // Bare /caveman -> activate default and persist
632
+ if (!rawArg) {
633
+ const def = resolveDefault();
634
+ const mode = def === "off" ? "caveman" : def;
635
+ sessionExplicitOff = false;
636
+ lastInjectedMode = null;
637
+ applyMode(mode);
638
+ saveUserConfigMode(mode);
639
+ notifyMode(ctx, mode);
640
+ return;
641
+ }
642
+
643
+ const res = resolveModeArg(rawArg, resolveDefault);
644
+
645
+ if (res.action === "status") {
646
+ displayStatus(pi, ctx);
647
+ return;
648
+ }
649
+
650
+ if (res.action === "set" && res.mode) {
651
+ sessionExplicitOff = false;
652
+ lastInjectedMode = null;
653
+ applyMode(res.mode);
654
+ saveUserConfigMode(res.mode);
655
+ notifyMode(ctx, res.mode);
656
+ return;
657
+ }
658
+
659
+ if (res.action === "clear") {
660
+ sessionExplicitOff = true;
661
+ lastInjectedMode = null;
662
+ applyMode("off");
663
+ saveUserConfigMode("off");
664
+ clearStatus(ctx);
665
+ return;
666
+ }
667
+
668
+ // Unknown
669
+ if (ctx.hasUI) {
670
+ ctx.ui.notify(
671
+ `unknown mode "${rawArg}". Use: caveman|ultracave|megacave|status|off`,
672
+ "warning",
673
+ );
674
+ }
675
+ },
676
+ });
677
+
678
+ // ── /caveman-status command ────────────────────────────────────────────
679
+ pi.registerCommand("caveman-status", {
680
+ description: "Show current caveman mode and config",
681
+ handler: async (_args, ctx) => {
682
+ displayStatus(pi, ctx);
683
+ },
684
+ });
685
+
686
+ // ── before_agent_start: per-turn reinforcement ────────────────────────
687
+ // Injects full SKILL.md content on activation / mode-switch.
688
+ // Subsequent continuing turns use a lightweight single-line reminder to preserve tokens & prompt cache.
689
+ pi.on("before_agent_start", async (_event, _ctx) => {
690
+ let active = readFlag();
691
+ if (!active && !sessionExplicitOff) {
692
+ const def = resolveDefault();
693
+ if (def !== "off") active = def;
694
+ }
695
+ if (!active || (active as string) === "off") {
696
+ lastInjectedMode = null;
697
+ return null;
698
+ }
699
+
700
+ const modeChanged = active !== lastInjectedMode;
701
+ lastInjectedMode = active;
702
+
703
+ let content: string;
704
+ if (modeChanged) {
705
+ const skillContent = loadSkillContent(active);
706
+ const header = `CAVEMAN MODE ACTIVE — mode: ${active}\n\n`;
707
+ content = skillContent
708
+ ? header + skillContent
709
+ : reinforcementLine(active);
710
+ } else {
711
+ content = reinforcementLine(active);
712
+ }
713
+
714
+ return {
715
+ message: {
716
+ customType: "caveman-reinforcement",
717
+ content,
718
+ display: false,
719
+ },
720
+ };
721
+ });
722
+
723
+ // ── input: intercept user prompts for mode changes ─────────────────────
724
+ pi.on("input", async (event, _ctx) => {
725
+ if (!event || typeof event !== "object" || !("text" in event)) return;
726
+ const text = event.text;
727
+ if (typeof text !== "string") return;
728
+ const change = parseModeChange(text);
729
+ if (change) {
730
+ if (change === "off") {
731
+ sessionExplicitOff = true;
732
+ lastInjectedMode = null;
733
+ } else {
734
+ sessionExplicitOff = false;
735
+ lastInjectedMode = null;
736
+ }
737
+ applyMode(change);
738
+ saveUserConfigMode(change);
739
+ }
740
+ });
741
+ }