@izhimu/pi-caveman 0.2.1 → 0.4.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,9 +1,9 @@
1
- // pi-caveman — pi extension
1
+ // pi-caveman — pi & oh-my-pi extension
2
2
  //
3
- // Caveman mode for pi: auto-activates per session, /caveman commands,
4
- // per-turn reinforcement injection, status bar integration.
3
+ // Caveman mode for pi & oh-my-pi: auto-activates per session, /caveman commands,
4
+ // per-turn reinforcement injection.
5
5
  //
6
- // Flag file: ~/.pi/.caveman-active
6
+ // Flag file: ~/.pi/.caveman-active or ~/.omp/.caveman-active
7
7
  // Config: ~/.config/caveman/config.json or CAVEMAN_DEFAULT_MODE env
8
8
  // Upstream: https://github.com/JuliusBrussee/caveman
9
9
 
@@ -20,21 +20,27 @@ import { fileURLToPath } from "node:url";
20
20
  const __filename = fileURLToPath(import.meta.url);
21
21
  const __dirname = dirname(__filename);
22
22
 
23
- // ── Constants ───────────────────────────────────────────────────────────────
23
+ // ── Constants & Canonical Mode Mapping ─────────────────────────────────────
24
24
 
25
- const VALID_MODES = [
26
- "lite", "full", "ultra",
27
- "wenyan-lite", "wenyan", "wenyan-full", "wenyan-ultra",
28
- "compress",
29
- ] as const;
25
+ export const VALID_MODES = ["caveman", "ultracave", "megacave"] as const;
26
+ export type Mode = (typeof VALID_MODES)[number];
30
27
 
31
- type Mode = (typeof VALID_MODES)[number];
32
-
33
- // Modes with independent skills — not caveman intensity levels
34
- const INDEPENDENT: Record<string, true> = {
35
- compress: true,
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
36
  };
37
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
+
38
44
  // ── Session stats ───────────────────────────────────────────────────────────
39
45
 
40
46
  interface SessionStats {
@@ -50,17 +56,23 @@ let sessionStats: SessionStats = {
50
56
 
51
57
  let sessionExplicitOff = false;
52
58
 
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,
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,
60
71
  };
61
72
 
62
- function estimateSavings(outputTokens: number, mode: string) {
63
- const ratio = COMPRESSION_RATIOS[mode];
73
+ export function estimateSavings(outputTokens: number, mode: string) {
74
+ const canon = canonicalMode(mode) || mode;
75
+ const ratio = COMPRESSION_RATIOS[canon] ?? COMPRESSION_RATIOS[mode];
64
76
  if (!ratio) return null;
65
77
  const estWithout = Math.round(outputTokens / (1 - ratio));
66
78
  const estSaved = estWithout - outputTokens;
@@ -74,16 +86,13 @@ const RST = `${ESC}0m`;
74
86
  const DIM = `${ESC}2m`;
75
87
  const BOLD = `${ESC}1m`;
76
88
  const GREEN = `${ESC}32m`;
77
- const YELLOW = `${ESC}33m`;
78
- const RED = `${ESC}31m`;
79
89
  const CYAN = `${ESC}36m`;
80
90
  const GRAY = `${ESC}90m`;
81
91
 
82
- function modeColor(mode: string): string {
92
+ export function modeColor(mode: string): string {
83
93
  if (mode === "off") return GRAY;
84
- if (mode.startsWith("wenyan")) return CYAN;
85
- if (mode === "lite") return YELLOW;
86
- return GREEN; // full, ultra
94
+ if (mode === "megacave" || mode.startsWith("wenyan")) return CYAN;
95
+ return GREEN; // caveman, ultracave, full, ultra
87
96
  }
88
97
 
89
98
  function bar(pct: number, width = 20): string {
@@ -98,15 +107,27 @@ function truncatePath(p: string, max = 40): string {
98
107
  return "…" + sep + tail;
99
108
  }
100
109
 
101
- // ── Paths ───────────────────────────────────────────────────────────────────
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
+ }
102
123
 
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");
124
+ export function getFlagPath(): string {
125
+ return join(resolveHostDir(), ".caveman-active");
126
+ }
106
127
 
107
128
  // ── Config resolution (mirrors caveman/src/hooks/caveman-config.js) ─────────
108
129
 
109
- function cavemanConfigDir(): string {
130
+ export function cavemanConfigDir(): string {
110
131
  const xdgHome = process.env.XDG_CONFIG_HOME;
111
132
  if (xdgHome) return join(xdgHome, "caveman");
112
133
  if (process.platform === "win32") {
@@ -118,7 +139,7 @@ function cavemanConfigDir(): string {
118
139
  return join(homedir(), ".config", "caveman");
119
140
  }
120
141
 
121
- function findRepoConfig(start: string): string | null {
142
+ export function findRepoConfig(start: string): string | null {
122
143
  let dir = start;
123
144
  for (let i = 0; i < 64; i++) {
124
145
  const a = join(dir, ".caveman", "config.json");
@@ -132,7 +153,7 @@ function findRepoConfig(start: string): string | null {
132
153
  return null;
133
154
  }
134
155
 
135
- function readConfigMode(configPath: string): string | null {
156
+ export function readConfigMode(configPath: string): string | null {
136
157
  try {
137
158
  const parsed = JSON.parse(readFileSync(configPath, "utf-8"));
138
159
  const m = parsed?.defaultMode;
@@ -142,16 +163,14 @@ function readConfigMode(configPath: string): string | null {
142
163
  }
143
164
  }
144
165
 
145
- function isValidMode(m: string): m is Mode {
146
- return (VALID_MODES as readonly string[]).includes(m);
147
- }
148
-
149
- function resolveDefault(): string {
166
+ export function resolveDefault(): Mode | "off" {
150
167
  // 1. Env var (short-circuits)
151
168
  const env = process.env.CAVEMAN_DEFAULT_MODE;
152
169
  if (env) {
153
170
  const lower = env.toLowerCase();
154
- if (isValidMode(lower) || lower === "off") return lower;
171
+ if (lower === "off") return "off";
172
+ const canon = canonicalMode(lower);
173
+ if (canon) return canon;
155
174
  }
156
175
  // 2. Repo-local config
157
176
  const repo = findRepoConfig(process.cwd());
@@ -159,7 +178,9 @@ function resolveDefault(): string {
159
178
  const m = readConfigMode(repo);
160
179
  if (m) {
161
180
  const lower = m.toLowerCase();
162
- if (isValidMode(lower) || lower === "off") return lower;
181
+ if (lower === "off") return "off";
182
+ const canon = canonicalMode(lower);
183
+ if (canon) return canon;
163
184
  }
164
185
  }
165
186
  // 3. User config
@@ -168,25 +189,44 @@ function resolveDefault(): string {
168
189
  const m = readConfigMode(user);
169
190
  if (m) {
170
191
  const lower = m.toLowerCase();
171
- if (isValidMode(lower) || lower === "off") return lower;
192
+ if (lower === "off") return "off";
193
+ const canon = canonicalMode(lower);
194
+ if (canon) return canon;
172
195
  }
173
196
  }
174
197
  // 4. Default
175
- return "full";
198
+ return "caveman";
176
199
  }
177
200
 
178
201
  // ── Flag I/O ────────────────────────────────────────────────────────────────
179
202
 
180
- function readFlag(): string | null {
203
+ export function readFlag(): Mode | null {
204
+ const flagPath = getFlagPath();
181
205
  try {
182
- const content = readFileSync(flagPath, "utf-8").trim();
183
- return isValidMode(content) ? content : null;
184
- } catch {
185
- return null;
186
- }
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;
187
226
  }
188
227
 
189
- function writeFlag(mode: string): void {
228
+ export function writeFlag(mode: Mode): void {
229
+ const flagPath = getFlagPath();
190
230
  try {
191
231
  const dir = dirname(flagPath);
192
232
  if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
@@ -198,15 +238,24 @@ function writeFlag(mode: string): void {
198
238
  }
199
239
  }
200
240
 
201
- function deleteFlag(): void {
241
+ export function deleteFlag(): void {
242
+ const flagPath = getFlagPath();
202
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 {}
203
252
  }
204
253
 
205
- function logModeChange(newMode: string | null): void {
254
+ function logModeChange(newMode: Mode | null): void {
206
255
  try {
207
256
  const prev = readFlag();
208
257
  if (prev === newMode) return;
209
- const dir = dirname(flagPath);
258
+ const dir = dirname(getFlagPath());
210
259
  if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
211
260
  const entry = JSON.stringify({
212
261
  ts: new Date().toISOString(), mode: newMode, prev,
@@ -215,9 +264,7 @@ function logModeChange(newMode: string | null): void {
215
264
  } catch {}
216
265
  }
217
266
 
218
- // ── Mode switching ──────────────────────────────────────────────────────────
219
-
220
- function saveUserConfigMode(mode: string): void {
267
+ export function saveUserConfigMode(mode: string): void {
221
268
  try {
222
269
  const configDir = cavemanConfigDir();
223
270
  const cfgPath = join(configDir, "config.json");
@@ -231,7 +278,7 @@ function saveUserConfigMode(mode: string): void {
231
278
  } catch {}
232
279
  }
233
280
 
234
- function applyMode(mode: string | "off"): void {
281
+ export function applyMode(mode: Mode | "off"): void {
235
282
  if (mode === "off") { logModeChange(null); deleteFlag(); }
236
283
  else { logModeChange(mode); writeFlag(mode); }
237
284
  }
@@ -239,50 +286,156 @@ function applyMode(mode: string | "off"): void {
239
286
  interface UI {
240
287
  hasUI: boolean;
241
288
  ui: {
242
- notify(msg: string, level: string): void;
289
+ notify(msg: string, level?: "info" | "warning" | "error"): void;
290
+ setStatus?(key: string, text: string | undefined): void;
243
291
  };
244
292
  }
245
293
 
246
294
  function notifyMode(ui: UI, mode: string): void {
247
295
  if (!ui.hasUI) return;
248
- const label = mode === "wenyan" ? "wenyan-full" : mode;
249
- ui.ui.notify(`caveman: ${label}`, "info");
296
+ ui.ui.notify(`caveman: ${mode}`, "info");
297
+ ui.ui.setStatus?.("caveman", undefined);
250
298
  }
251
299
 
252
300
  function clearStatus(ui: UI): void {
253
301
  if (!ui.hasUI) return;
302
+ ui.ui.setStatus?.("caveman", undefined);
254
303
  ui.ui.notify("caveman: off", "info");
255
304
  }
256
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
+
257
366
  // ── Mode parsing (mirrors caveman hooks/caveman-parse.js) ───────────────────
258
367
 
259
368
  const QUOTED_SPAN_REGEX = /(["`])(?:(?!\1).)*\1/g;
260
369
 
261
- function normalizeModeArg(arg: string): string {
370
+ export function normalizeModeArg(arg: string): string {
262
371
  return (arg || "").replace(/^[^a-z0-9]+/, "").replace(/[^a-z0-9-]+$/, "");
263
372
  }
264
373
 
265
- interface ModeResolution {
266
- action: "set" | "clear" | "unresolved";
267
- mode?: string;
268
- independentMode?: string;
374
+ export interface ModeResolution {
375
+ action: "set" | "clear" | "status" | "unresolved";
376
+ mode?: Mode;
269
377
  }
270
378
 
271
- function resolveModeArg(rawArg: string, getDefault: () => string): ModeResolution {
379
+ export function resolveModeArg(rawArg: string, getDefault: () => Mode | "off"): ModeResolution {
272
380
  const arg = normalizeModeArg(rawArg);
273
381
  if (!arg) {
274
382
  if (rawArg) return { action: "unresolved" };
275
- const mode = getDefault();
276
- return mode === "off" ? { action: "clear" } : { action: "set", mode };
383
+ const def = getDefault();
384
+ return def === "off" ? { action: "clear" } : { action: "set", mode: def };
277
385
  }
278
386
  if (arg === "off" || arg === "stop" || arg === "disable") return { action: "clear" };
279
- if (arg === "wenyan-full") return { action: "set", mode: "wenyan" };
280
- if (isValidMode(arg) && !INDEPENDENT[arg]) return { action: "set", mode: arg };
281
- if (INDEPENDENT[arg]) return { action: "unresolved", independentMode: arg };
387
+ if (arg === "status") return { action: "status" };
388
+ const canon = canonicalMode(arg);
389
+ if (canon) return { action: "set", mode: canon };
282
390
  return { action: "unresolved" };
283
391
  }
284
392
 
285
- function parseModeChange(promptRaw: string): string | "off" | null {
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 {
286
439
  let prompt = (promptRaw || "").trim();
287
440
  if (!prompt) return null;
288
441
 
@@ -301,32 +454,38 @@ function parseModeChange(promptRaw: string): string | "off" | null {
301
454
 
302
455
  if (wantsOff) return "off";
303
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
+
304
467
  // Natural-language activation (exclude questions)
305
468
  const isQuestion =
306
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);
307
470
 
308
- if (!isQuestion) {
309
- if (
310
- /\b(activate|enable|start|turn on|use|switch to|want|give me)\b[^.]{0,40}\bcaveman\b/.test(nlPrompt) ||
311
- /\btalk like\b[^.]{0,40}\bcaveman\b/.test(nlPrompt) ||
312
- /\bcaveman\s+mode\s+(on|please|now)\b/.test(nlPrompt) ||
313
- /^caveman(\s+mode)?\s*[.!]*$/.test(nlPrompt) ||
314
- /\b(less tokens|fewer tokens|be brief|be terse|shorter answers)\b(?!\s+(in|for|on|about|when|during|with)\b)/.test(nlPrompt)
315
- ) {
316
- const mode = resolveDefault();
317
- return mode !== "off" ? mode : null;
318
- }
471
+ if (!isQuestion && wantsActivation(nlPrompt)) {
472
+ const def = resolveDefault();
473
+ return def !== "off" ? def : null;
319
474
  }
320
475
  }
321
476
 
322
- // Slash-command (support bare and namespaced /caveman:<cmd>)
323
- if (prompt.startsWith("/caveman")) {
477
+ // Slash commands
478
+ if (prompt.startsWith("/")) {
324
479
  const parts = prompt.split(/\s+/);
325
480
  const cmd = parts[0].toLowerCase();
326
481
  const rawArg = parts[1] || "";
327
482
 
328
- if (cmd === "/caveman-compress" || cmd === "/caveman:caveman-compress") return "compress";
329
-
483
+ if (cmd === "/ultracave" || cmd === "/caveman:ultracave") {
484
+ return "ultracave";
485
+ }
486
+ if (cmd === "/megacave" || cmd === "/caveman:megacave") {
487
+ return "megacave";
488
+ }
330
489
  if (cmd === "/caveman" || cmd === "/caveman:caveman") {
331
490
  const res = resolveModeArg(rawArg, resolveDefault);
332
491
  if (res.action === "set" && res.mode) return res.mode;
@@ -338,83 +497,14 @@ function parseModeChange(promptRaw: string): string | "off" | null {
338
497
  return null;
339
498
  }
340
499
 
341
- // ── SKILL.md loading (mirrors caveman-activate.js) ──────────────────────────
342
-
343
- // Resolve SKILL.md path — try relative to this extension file first, then skills dir
344
- const SKILL_CANDIDATES = [
345
- join(__dirname, "..", "skills", "caveman", "SKILL.md"),
346
- join(__dirname, "skills", "caveman", "SKILL.md"),
347
- ];
348
-
349
- function findSkillPath(): string | null {
350
- for (const candidate of SKILL_CANDIDATES) {
351
- if (existsSync(candidate)) return candidate;
352
- }
353
- return null;
354
- }
355
-
356
- // Load and filter SKILL.md content for the active mode.
357
- // Mirrors caveman-activate.js: strips frontmatter, keeps only the active
358
- // level's table row and example lines.
359
- function loadFilteredSkillContent(mode: string): string | null {
360
- const skillPath = findSkillPath();
361
- if (!skillPath) return null;
362
-
363
- try {
364
- const raw = readFileSync(skillPath, "utf-8");
365
- // Strip YAML frontmatter
366
- const body = raw.replace(/^---[\s\S]*?---\s*/, "");
367
- const modeLabel = mode === "wenyan" ? "wenyan-full" : mode;
368
-
369
- // Filter: keep header rows + only the active level's row
370
- const filtered = body.split("\n").reduce<string[]>((acc, line) => {
371
- // Intensity table rows start with | **level** |
372
- const tableRowMatch = line.match(/^\|\s*\*\*(\S+?)\*\*\s*\|/);
373
- if (tableRowMatch) {
374
- if (tableRowMatch[1] === modeLabel) acc.push(line);
375
- return acc;
376
- }
377
- // Example lines start with "- level:"
378
- const exampleMatch = line.match(/^- (\S+?):\s/);
379
- if (exampleMatch) {
380
- if (exampleMatch[1] === modeLabel) acc.push(line);
381
- return acc;
382
- }
383
- acc.push(line);
384
- return acc;
385
- }, []);
386
-
387
- return filtered.join("\n");
388
- } catch {
389
- return null;
390
- }
391
- }
392
-
393
- // ── Reinforcement line ──────────────────────────────────────────────────────
394
-
395
- function reinforcementLine(mode: string): string {
396
- const label = mode === "wenyan" ? "wenyan-full" : mode;
397
- const wenyanHint = mode.startsWith("wenyan")
398
- ? " MUST respond in 文言文 (classical Chinese). Use classical particles (之/乃/為/其), omit subjects, verbs precede objects."
399
- : "";
400
- return (
401
- `[CAVEMAN ACTIVE — intensity: ${label}.${wenyanHint} ` +
402
- "Respond terse like smart caveman. All technical substance stay. " +
403
- "Only fluff die. Fragments OK. Short synonyms. " +
404
- "No filler/hedging/pleasantries. Code unchanged. Technical terms exact.]"
405
- );
406
- }
407
-
408
500
  // ── Argument completions ────────────────────────────────────────────────────
409
501
 
410
502
  const MODE_CHOICES = [
411
- { value: "lite", label: "lite", description: "no filler/hedging, keep articles" },
412
- { value: "full", label: "full", description: "drop articles, fragments OK (default)" },
413
- { value: "ultra", label: "ultra", description: "one word when one word enough" },
414
- { value: "wenyan-lite", label: "wenyan-lite", description: "semi-classical, keep grammar" },
415
- { value: "wenyan", label: "wenyan", description: "maximum classical terseness (文言文)" },
416
- { value: "wenyan-ultra",label: "wenyan-ultra", description: "extreme abbreviation, classical feel" },
417
- { value: "off", label: "off", description: "disabled" },
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" },
418
508
  ];
419
509
 
420
510
  function getModeCompletions(prefix: string) {
@@ -425,15 +515,80 @@ function getModeCompletions(prefix: string) {
425
515
  return matches.length > 0 ? matches : null;
426
516
  }
427
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
+
428
566
  // ── Extension factory ───────────────────────────────────────────────────────
429
567
 
430
568
  export default function cavemanExtension(pi: ExtensionAPI) {
569
+ let lastInjectedMode: Mode | null = null;
570
+
431
571
  // ── session_start: auto-activate ──────────────────────────────────────
432
- pi.on("session_start", async (_event, ctx) => {
433
- sessionStats = { turns: 0, outputTokens: 0, cacheReadTokens: 0, inputTokens: 0 };
434
- sessionExplicitOff = false;
435
- const mode = resolveDefault();
436
- if (mode === "off") { deleteFlag(); return; }
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
+ }
437
592
  applyMode(mode);
438
593
  notifyMode(ctx, mode);
439
594
  });
@@ -453,15 +608,17 @@ export default function cavemanExtension(pi: ExtensionAPI) {
453
608
 
454
609
  // ── /caveman command ──────────────────────────────────────────────────
455
610
  pi.registerCommand("caveman", {
456
- description: "Switch and persist caveman mode (lite|full|ultra|wenyan|off)",
611
+ description: "Switch and persist caveman mode (caveman|ultracave|megacave|status|off)",
457
612
  getArgumentCompletions: (prefix) => getModeCompletions(prefix),
458
613
  handler: async (args, ctx) => {
459
- const rawArg = (args || "").trim().toLowerCase();
614
+ const rawArg = (args || "").trim();
460
615
 
461
616
  // Bare /caveman -> activate default and persist
462
617
  if (!rawArg) {
463
618
  const def = resolveDefault();
464
- const mode = def === "off" ? "full" : def;
619
+ const mode = def === "off" ? "caveman" : def;
620
+ sessionExplicitOff = false;
621
+ lastInjectedMode = null;
465
622
  applyMode(mode);
466
623
  saveUserConfigMode(mode);
467
624
  notifyMode(ctx, mode);
@@ -470,7 +627,14 @@ export default function cavemanExtension(pi: ExtensionAPI) {
470
627
 
471
628
  const res = resolveModeArg(rawArg, resolveDefault);
472
629
 
630
+ if (res.action === "status") {
631
+ displayStatus(pi, ctx);
632
+ return;
633
+ }
634
+
473
635
  if (res.action === "set" && res.mode) {
636
+ sessionExplicitOff = false;
637
+ lastInjectedMode = null;
474
638
  applyMode(res.mode);
475
639
  saveUserConfigMode(res.mode);
476
640
  notifyMode(ctx, res.mode);
@@ -479,103 +643,88 @@ export default function cavemanExtension(pi: ExtensionAPI) {
479
643
 
480
644
  if (res.action === "clear") {
481
645
  sessionExplicitOff = true;
646
+ lastInjectedMode = null;
482
647
  applyMode("off");
483
648
  saveUserConfigMode("off");
484
649
  clearStatus(ctx);
485
650
  return;
486
651
  }
487
652
 
488
- if (res.independentMode && ctx.hasUI) {
489
- ctx.ui.notify(
490
- `"${res.independentMode}" is an independent skill. Use: /caveman-${res.independentMode}`,
491
- "warning",
492
- );
493
- return;
494
- }
495
-
496
653
  // Unknown
497
654
  if (ctx.hasUI) {
498
655
  ctx.ui.notify(
499
- `unknown mode "${rawArg}". Use: lite|full|ultra|wenyan-lite|wenyan|wenyan-ultra|off`,
656
+ `unknown mode "${rawArg}". Use: caveman|ultracave|megacave|status|off`,
500
657
  "warning",
501
658
  );
502
659
  }
503
660
  },
504
661
  });
505
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
+
506
687
  // ── /caveman-status command ────────────────────────────────────────────
507
688
  pi.registerCommand("caveman-status", {
508
689
  description: "Show current caveman mode and config",
509
690
  handler: async (_args, ctx) => {
510
- const active = readFlag();
511
- const def = resolveDefault();
512
- const configPath = join(cavemanConfigDir(), "config.json");
513
- const repoConfig = findRepoConfig(process.cwd());
514
- const mode = active || "off";
515
-
516
- const mc = modeColor(mode);
517
- const modeLabel = mode === "wenyan" ? "wenyan-full" : mode;
518
- const defLabel = def === "wenyan" ? "wenyan-full" : def;
519
-
520
- const lines: string[] = [
521
- `${BOLD}Caveman${RST}: ${mc}${modeLabel}${RST}${def !== mode ? ` ${DIM}(default: ${defLabel})${RST}` : ""}`,
522
- "",
523
- ` ${sessionStats.turns} turns ${DIM}│${RST} ${sessionStats.outputTokens.toLocaleString()} out ${DIM}│${RST} ${sessionStats.cacheReadTokens.toLocaleString()} cached ${DIM}│${RST} ${sessionStats.inputTokens.toLocaleString()} in`,
524
- ];
525
-
526
- const savings = estimateSavings(sessionStats.outputTokens, mode);
527
- if (savings && savings.estSaved > 0) {
528
- lines.push(
529
- "",
530
- ` saved ${GREEN}${savings.estSaved.toLocaleString()}${RST} tokens ${DIM}(~${savings.pct}%)${RST} ${GREEN}${bar(savings.pct)}${RST}`,
531
- );
532
- }
533
-
534
- const configLines: string[] = [];
535
- if (process.env.CAVEMAN_DEFAULT_MODE) {
536
- configLines.push(` env ${DIM}CAVEMAN_DEFAULT_MODE=${process.env.CAVEMAN_DEFAULT_MODE}${RST}`);
537
- }
538
- if (existsSync(configPath)) configLines.push(` user ${DIM}${truncatePath(configPath)}${RST}`);
539
- if (repoConfig) configLines.push(` repo ${DIM}${truncatePath(repoConfig)}${RST}`);
540
- configLines.push(` flag ${DIM}${truncatePath(flagPath)}${RST}`);
541
-
542
- if (configLines.length) {
543
- lines.push("", ...configLines);
544
- }
545
-
546
- const msg = lines.join("\n");
547
- if (ctx.hasUI) ctx.ui.notify(msg, "info");
548
- pi.sendMessage({
549
- content: msg,
550
- attribution: "user",
551
- }, { triggerTurn: false });
691
+ displayStatus(pi, ctx);
552
692
  },
553
693
  });
554
694
 
555
-
556
695
  // ── before_agent_start: per-turn reinforcement ────────────────────────
557
- // Injects full SKILL.md content (filtered to active mode) + reinforcement line.
558
- // Mirrors caveman-activate.js behavior: the model sees the complete ruleset
559
- // on every turn, not just a one-line reminder.
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.
560
698
  pi.on("before_agent_start", async (_event, _ctx) => {
561
699
  let active = readFlag();
562
- if (!active && !sessionExplicitOff) active = resolveDefault();
563
- if (!active || active === "off" || INDEPENDENT[active]) return null;
564
-
565
- const skillContent = loadFilteredSkillContent(active);
566
- const header = `CAVEMAN MODE ACTIVE — level: ${active === "wenyan" ? "wenyan-full" : active}\n\n`;
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
+ }
567
708
 
568
- // If SKILL.md found, inject full filtered content; fall back to reinforcement line
569
- const content = skillContent
570
- ? header + skillContent
571
- : reinforcementLine(active);
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
+ }
572
722
 
573
723
  return {
574
724
  message: {
575
725
  customType: "caveman-reinforcement",
576
726
  content,
577
727
  display: false,
578
- attribution: "system",
579
728
  },
580
729
  };
581
730
  });
@@ -587,10 +736,15 @@ export default function cavemanExtension(pi: ExtensionAPI) {
587
736
  if (typeof text !== "string") return;
588
737
  const change = parseModeChange(text);
589
738
  if (change) {
590
- if (change === "off") sessionExplicitOff = true;
739
+ if (change === "off") {
740
+ sessionExplicitOff = true;
741
+ lastInjectedMode = null;
742
+ } else {
743
+ sessionExplicitOff = false;
744
+ lastInjectedMode = null;
745
+ }
591
746
  applyMode(change);
592
747
  saveUserConfigMode(change);
593
748
  }
594
749
  });
595
-
596
750
  }