@lornatang/dsh-caveman 0.1.1 → 0.1.3

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/CHANGELOG.md CHANGED
@@ -1,5 +1,19 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.3 - 2026-11-19
4
+
5
+ - Simplify the system-prompt and request-header hooks by dropping unused handler parameters; behavior is unchanged.
6
+ - Keep the verified analyzer binaries attached to this release under the new version.
7
+
8
+ ## 0.1.2 - 2026-11-18
9
+
10
+ - Settle the block hook promise on timeout or abort, so a hung analyzer cannot stall tool execution.
11
+ - Count only successful edits against the Cavecrew builder budget and match file identities with platform-aware case folding.
12
+ - Bound retained compression originals to 64 entries and 8 MiB, and drop an entry once it has been restored.
13
+ - Report inherited-event statistics from the current session's own events instead of replaying the whole log.
14
+ - Require a configured analyzer binary to be executable, and require the native bridge socket to be a socket owned by the service user on POSIX.
15
+ - Open input-state files non-blocking so a FIFO cannot stall the pre-execution check.
16
+
3
17
  ## 0.1.1 - 2026-11-18
4
18
 
5
19
  - Republish the DSH plugin with the verified analyzer binaries attached to the matching GitHub release.
package/README.md CHANGED
@@ -43,7 +43,7 @@ git clone https://github.com/Lornatang/dsh-caveman.git
43
43
  cd dsh-caveman
44
44
  npm ci
45
45
  npm pack
46
- dsh plugin --profile <name> add ./lornatang-dsh-caveman-0.1.1.tgz
46
+ dsh plugin --profile <name> add ./lornatang-dsh-caveman-0.1.3.tgz
47
47
  ```
48
48
 
49
49
  The `add` command composes the bundle into the profile. Its patches insert the `caveman` row, three Cavecrew presets, and their delegation tools. Restart DSH after `add` or `remove` so the profile reloads its composition.
package/README.zh.md CHANGED
@@ -43,7 +43,7 @@ git clone https://github.com/Lornatang/dsh-caveman.git
43
43
  cd dsh-caveman
44
44
  npm ci
45
45
  npm pack
46
- dsh plugin --profile <name> add ./lornatang-dsh-caveman-0.1.1.tgz
46
+ dsh plugin --profile <name> add ./lornatang-dsh-caveman-0.1.3.tgz
47
47
  ```
48
48
 
49
49
  `add` 命令把 bundle 组合进 profile。patch 会插入 `caveman` 行、三个 Cavecrew 预设及其委派工具。`add` 或 `remove` 后重启 DSH,使 profile 重新加载配置。
@@ -20,5 +20,5 @@ export function cavemanRequestHeaders(endpoint, request, headers) {
20
20
  return headers;
21
21
  }
22
22
  export function registerAttribution(ctx, endpoint) {
23
- ctx.on('llm-pi-ai/request-headers', (request, headers, next) => cavemanRequestHeaders(endpoint, request, next()));
23
+ ctx.on('llm-pi-ai/request-headers', (request, _headers, next) => cavemanRequestHeaders(endpoint, request, next()));
24
24
  }
package/lib/blocks.js CHANGED
@@ -18,7 +18,7 @@ async function callHook(binary, input, signal) {
18
18
  signal.removeEventListener('abort', abort);
19
19
  resolveHint(hint);
20
20
  };
21
- const abort = () => { child.kill('SIGKILL'); };
21
+ const abort = () => { child.kill('SIGKILL'); finish(); };
22
22
  const timer = setTimeout(abort, 2500);
23
23
  signal.addEventListener('abort', abort, { once: true });
24
24
  child.on('error', () => finish());
package/lib/cavecrew.js CHANGED
@@ -33,6 +33,10 @@ export async function apply(ctx, config) {
33
33
  }
34
34
  const permitted = new Set(allowed);
35
35
  const edited = new WeakMap();
36
+ const editKey = (value) => {
37
+ const normalized = normalize(value);
38
+ return process.platform === 'win32' ? normalized.toLowerCase() : normalized;
39
+ };
36
40
  ctx.tools.guard(exec => {
37
41
  if (!permitted.has(exec.name))
38
42
  return `Cavecrew ${config.role} does not permit ${exec.name}.`;
@@ -42,14 +46,28 @@ export async function apply(ctx, config) {
42
46
  !('file_path' in exec.arguments) || typeof exec.arguments.file_path !== 'string' || !exec.arguments.file_path.trim()) {
43
47
  return 'Cavecrew builder requires an existing file path.';
44
48
  }
45
- const path = normalize(exec.arguments.file_path);
49
+ const path = editKey(exec.arguments.file_path);
46
50
  const paths = edited.get(exec.agent) ?? new Set();
47
- if (!paths.has(path) && paths.size >= 2)
48
- return 'Cavecrew builder is limited to two file paths.';
49
- paths.add(path);
50
- edited.set(exec.agent, paths);
51
+ if (!paths.has(path)) {
52
+ if (paths.size >= 2)
53
+ return 'Cavecrew builder is limited to two file paths.';
54
+ paths.add(path);
55
+ edited.set(exec.agent, paths);
56
+ }
51
57
  return undefined;
52
58
  });
59
+ if (config.role === 'builder') {
60
+ // The guard runs before the edit body, so refund the budget when the edit fails.
61
+ ctx.on('tools/execute', async (exec, next) => {
62
+ const result = await next();
63
+ if (exec.name !== 'edit' || !exec.agent || !result.isError ||
64
+ typeof exec.arguments !== 'object' || exec.arguments === null ||
65
+ !('file_path' in exec.arguments) || typeof exec.arguments.file_path !== 'string')
66
+ return result;
67
+ edited.get(exec.agent)?.delete(editKey(exec.arguments.file_path));
68
+ return result;
69
+ });
70
+ }
53
71
  ctx.on('agent/created', async ({ agent }) => {
54
72
  const available = allowed.filter(tool => ctx.tools.get(tool, agent) !== undefined);
55
73
  agent.ctx.tools.restrict({ allow: available });
@@ -39,6 +39,21 @@ export function isManagedTool(name) {
39
39
  return name === 'caveman_retrieve' || name === 'cavemem_recover' || name.startsWith('mcp__caveman__') || name.startsWith('mcp__caveman_browse__') || name.startsWith('mcp__cavemem__') ||
40
40
  /^mcp__.+__(?:caveman_retrieve|browser_recover)$/u.test(name);
41
41
  }
42
+ const MAX_ORIGINAL_ENTRIES = 64;
43
+ const MAX_ORIGINAL_BYTES = 8 * 1024 * 1024;
44
+ /** Keep recovery pages bounded; otherwise every compressed block is retained forever. */
45
+ function rememberOriginal(state, handle, value) {
46
+ state.originals.set(handle, value);
47
+ state.originalBytes += Buffer.byteLength(value.text, 'utf8');
48
+ while (state.originals.size > 1 && (state.originals.size > MAX_ORIGINAL_ENTRIES || state.originalBytes > MAX_ORIGINAL_BYTES)) {
49
+ const oldest = state.originals.keys().next().value;
50
+ if (oldest === undefined)
51
+ break;
52
+ const removed = state.originals.get(oldest);
53
+ state.originalBytes -= removed ? Buffer.byteLength(removed.text, 'utf8') : 0;
54
+ state.originals.delete(oldest);
55
+ }
56
+ }
42
57
  /** Index immutable history once per session instead of rescanning it on every step. */
43
58
  export class CompressionHistoryIndex {
44
59
  states = new WeakMap();
@@ -47,6 +62,7 @@ export class CompressionHistoryIndex {
47
62
  const previous = this.states.get(session);
48
63
  const state = previous && previous.seq <= end ? previous : {
49
64
  seq: 0, toolNames: new Map(), managedCalls: new Set(), hasMarker: false, originals: new Map(),
65
+ originalBytes: 0,
50
66
  };
51
67
  for (const event of session.snapshotEvents(state.seq, end)) {
52
68
  const dispatch = event;
@@ -69,7 +85,7 @@ export class CompressionHistoryIndex {
69
85
  const source = session.eventAt(event.sourceEventSeqs[0]);
70
86
  const original = source && textBlocks(source).find(candidate => candidate.index === block.index);
71
87
  if (source?.type === 'tool/result' && original) {
72
- state.originals.set(handle, { text: original.text, sourceId: `seq-${resolveOriginalResult(session, source).seq}` });
88
+ rememberOriginal(state, handle, { text: original.text, sourceId: `seq-${resolveOriginalResult(session, source).seq}` });
73
89
  }
74
90
  }
75
91
  }
@@ -305,7 +321,7 @@ export function registerCompression(ctx, endpoint, automatic) {
305
321
  yield* next();
306
322
  })());
307
323
  const selections = new WeakMap();
308
- ctx.on('system-prompt/assemble', async (assembly, context, next) => {
324
+ ctx.on('system-prompt/assemble', async (_assembly, context, next) => {
309
325
  const result = await next();
310
326
  if (context.agent && context.toolSet)
311
327
  selections.set(context.agent, context.toolSet);
package/lib/native.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { createHash } from 'node:crypto';
2
- import { readFileSync } from 'node:fs';
3
- import { open, realpath, stat } from 'node:fs/promises';
2
+ import { constants, readFileSync } from 'node:fs';
3
+ import { lstat, open, realpath, stat } from 'node:fs/promises';
4
4
  import { connect } from 'node:net';
5
5
  import { homedir } from 'node:os';
6
6
  import { join, resolve, win32 } from 'node:path';
@@ -76,9 +76,25 @@ function validResponse(value) {
76
76
  }
77
77
  return true;
78
78
  }
79
+ /** Refuse a replaced socket path before sending prompt terms or tool data over it. */
80
+ async function trustedSocket(path) {
81
+ if (process.platform === 'win32')
82
+ return true;
83
+ try {
84
+ const info = await lstat(path);
85
+ if (!info.isSocket())
86
+ return false;
87
+ return typeof process.getuid === 'function' ? info.uid === process.getuid() : true;
88
+ }
89
+ catch {
90
+ return false;
91
+ }
92
+ }
79
93
  export async function nativeCall(home, request, signal) {
80
94
  if (signal?.aborted)
81
95
  return undefined;
96
+ if (!await trustedSocket(nativeSocketPath(home)))
97
+ return undefined;
82
98
  const payload = Buffer.from(JSON.stringify(request) + '\n');
83
99
  if (payload.length > 2 * 1024 * 1024)
84
100
  return undefined;
@@ -158,7 +174,8 @@ async function inputState(ctx, cwd, input, signal) {
158
174
  const target = await filesystem.resolve(path, { cwd, signal });
159
175
  if (filesystem.processPathFromHostPath(resolved) !== filesystem.processPath(target))
160
176
  return undefined;
161
- const file = await open(resolved, 'r');
177
+ // A FIFO would otherwise block this pre-execute hook; O_NONBLOCK fails fast and fstat rejects it.
178
+ const file = await open(resolved, process.platform === 'win32' ? 'r' : constants.O_RDONLY | constants.O_NONBLOCK);
162
179
  try {
163
180
  const before = await file.stat();
164
181
  if (!before.isFile() || before.size > 8 * 1024 * 1024)
@@ -199,7 +216,7 @@ export function registerNative(ctx, endpoint, policy) {
199
216
  const selections = new WeakMap();
200
217
  const pending = new Set();
201
218
  const home = process.env.CAVEMAN_HOME ?? join(homedir(), '.caveman');
202
- ctx.on('system-prompt/assemble', async (assembly, context, next) => {
219
+ ctx.on('system-prompt/assemble', async (_assembly, context, next) => {
203
220
  const result = await next();
204
221
  if (context.agent && context.toolSet)
205
222
  selections.set(context.agent, context.toolSet);
package/lib/runtime.js CHANGED
@@ -28,6 +28,8 @@ export function findCavemanBinary(kind, configured, env = process.env) {
28
28
  if (configured !== undefined) {
29
29
  if (!isAbsolute(configured))
30
30
  throw new Error(`dsh-caveman: ${kind}Binary must be an absolute path`);
31
+ if (!executable(configured))
32
+ throw new Error(`dsh-caveman: ${kind}Binary is not an executable file: ${configured}`);
31
33
  return configured;
32
34
  }
33
35
  const override = env[{ blocks: 'CAVEMAN_BLOCKS_BIN', browse: 'CAVEMAN_BROWSE_BIN', mcp: 'CAVEMAN_MCP_BIN', memory: 'CAVEMEM_BIN' }[kind]];
package/lib/stats.js CHANGED
@@ -117,7 +117,7 @@ export async function statsReport(ctx, current, flags, signal) {
117
117
  return error.message;
118
118
  }
119
119
  if (!options.all && !options.since)
120
- return sessionStats(current.snapshotEvents(), flags);
120
+ return sessionStats(current.snapshotEvents(current.inheritedEventCount), flags);
121
121
  const totals = countsFor([]);
122
122
  const live = ctx.get('sessions')?.list() ?? [current];
123
123
  const known = new Set(live.map(session => String(session.id)));
@@ -10,6 +10,7 @@ interface CompressionHistory {
10
10
  text: string;
11
11
  sourceId: string;
12
12
  }>;
13
+ originalBytes: number;
13
14
  }
14
15
  /** Index immutable history once per session instead of rescanning it on every step. */
15
16
  export declare class CompressionHistoryIndex {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lornatang/dsh-caveman",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "Caveman integration for DeepSeek Harness.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -78,7 +78,7 @@
78
78
  "@caveman-ai/cli": "4.1.0",
79
79
  "@caveman-ai/sdk": "1.2.0",
80
80
  "@deepseek-ai/schemastery": "~3.19.0",
81
- "undici": "^7.30.2",
81
+ "undici": "^8.12.4",
82
82
  "yaml": "^2.8.1"
83
83
  },
84
84
  "peerDependencies": {
@@ -111,8 +111,8 @@
111
111
  "@deepseek-ai/dsh-tool-subagent": "0.2.2-rc.3",
112
112
  "@deepseek-ai/dsh-tools": "^0.2.2-rc.3",
113
113
  "@deepseek-ai/dsh-working-directory": "0.2.2-rc.3",
114
- "@types/node": "^22.18.0",
115
- "typescript": "^5.9.3"
114
+ "@types/node": "^26.6.6",
115
+ "typescript": "^7.0.2"
116
116
  },
117
117
  "repository": {
118
118
  "type": "git",
@@ -1,30 +1,30 @@
1
- #!/usr/bin/env node
2
- import { spawn } from 'node:child_process'
3
- import { constants } from 'node:os'
4
- import { createRequire } from 'node:module'
5
- import { dirname, join } from 'node:path'
6
-
7
- const require = createRequire(import.meta.url)
8
- const cli = join(dirname(require.resolve('@caveman-ai/cli/package.json')), 'dist', 'index.js')
9
- const args = process.argv.slice(2)
10
- let learnBinary
11
- if (args[0] === 'learn' && !['--help', '-h', 'help'].includes(args[1])) {
12
- try { learnBinary = await (await import('./learn-binary.mjs')).resolveLearnBinary() }
13
- catch (error) { console.error(`dsh-caveman: ${error.message}`); process.exit(1) }
14
- }
15
- const direct = learnBinary && args[1] === 'locate'
16
- const child = spawn(direct ? learnBinary : process.execPath, direct ? args : [cli, ...args], {
17
- stdio: 'inherit', windowsHide: true,
18
- env: learnBinary ? { ...process.env, CAVEMAN_PROXY_BIN: learnBinary } : process.env,
19
- })
20
-
21
- for (const signal of ['SIGINT', 'SIGTERM']) {
22
- process.on(signal, () => { if (child.exitCode === null && child.signalCode === null) child.kill(signal) })
23
- }
24
- child.once('error', error => {
25
- console.error(`dsh-caveman: could not start the CLI: ${error.message}`)
26
- process.exitCode = 1
27
- })
28
- child.once('exit', (code, signal) => {
29
- process.exitCode = code ?? (signal ? 128 + (constants.signals[signal] ?? 0) : 1)
30
- })
1
+ #!/usr/bin/env node
2
+ import { spawn } from 'node:child_process'
3
+ import { constants } from 'node:os'
4
+ import { createRequire } from 'node:module'
5
+ import { dirname, join } from 'node:path'
6
+
7
+ const require = createRequire(import.meta.url)
8
+ const cli = join(dirname(require.resolve('@caveman-ai/cli/package.json')), 'dist', 'index.js')
9
+ const args = process.argv.slice(2)
10
+ let learnBinary
11
+ if (args[0] === 'learn' && !['--help', '-h', 'help'].includes(args[1])) {
12
+ try { learnBinary = await (await import('./learn-binary.mjs')).resolveLearnBinary() }
13
+ catch (error) { console.error(`dsh-caveman: ${error.message}`); process.exit(1) }
14
+ }
15
+ const direct = learnBinary && args[1] === 'locate'
16
+ const child = spawn(direct ? learnBinary : process.execPath, direct ? args : [cli, ...args], {
17
+ stdio: 'inherit', windowsHide: true,
18
+ env: learnBinary ? { ...process.env, CAVEMAN_PROXY_BIN: learnBinary } : process.env,
19
+ })
20
+
21
+ for (const signal of ['SIGINT', 'SIGTERM']) {
22
+ process.on(signal, () => { if (child.exitCode === null && child.signalCode === null) child.kill(signal) })
23
+ }
24
+ child.once('error', error => {
25
+ console.error(`dsh-caveman: could not start the CLI: ${error.message}`)
26
+ process.exitCode = 1
27
+ })
28
+ child.once('exit', (code, signal) => {
29
+ process.exitCode = code ?? (signal ? 128 + (constants.signals[signal] ?? 0) : 1)
30
+ })
@@ -1,82 +1,82 @@
1
- import { createHash, randomBytes } from 'node:crypto'
2
- import { createReadStream } from 'node:fs'
3
- import { chmod, mkdir, open, readFile, rename, rm } from 'node:fs/promises'
4
- import { homedir } from 'node:os'
5
- import { join } from 'node:path'
6
-
7
- const MAX_BINARY_BYTES = 120 * 1024 * 1024
8
- const manifestUrl = new URL('./learn-checksums.json', import.meta.url)
9
- const packageUrl = new URL('../package.json', import.meta.url)
10
-
11
- async function fileDigest(path) {
12
- try {
13
- const hash = createHash('sha256')
14
- for await (const chunk of createReadStream(path)) hash.update(chunk)
15
- return hash.digest('hex')
16
- } catch (error) {
17
- if (error?.code === 'ENOENT') return undefined
18
- throw error
19
- }
20
- }
21
-
22
- /** Download and verify the executable once for the current platform and version. */
23
- export async function resolveLearnBinary(options = {}) {
24
- const { env = process.env, platform = process.platform, arch = process.arch } = options
25
- if (env.DSH_CAVEMAN_LEARN_BINARY) return env.DSH_CAVEMAN_LEARN_BINARY
26
- const manifest = options.manifest ?? JSON.parse(await readFile(manifestUrl, 'utf8'))
27
- const version = JSON.parse(await readFile(packageUrl, 'utf8')).version
28
- if (manifest.version !== version || !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u.test(version)) throw new Error('Invalid analyzer version manifest')
29
- const os = { linux: 'linux', darwin: 'darwin', win32: 'win32' }[platform]
30
- const cpu = { x64: 'amd64', arm64: 'arm64' }[arch]
31
- const entry = manifest.binaries?.[`${platform}-${arch}`]
32
- const expectedName = os && cpu ? `dsh-caveman-learn_${os}_${cpu}` : undefined
33
- if (!expectedName || entry?.name !== expectedName || !/^[a-f0-9]{64}$/u.test(entry.sha256 ?? '')) {
34
- throw new Error(`No verified analyzer is available for ${platform}/${arch}`)
35
- }
36
- const directory = join(options.cacheRoot ?? join(homedir(), '.dsh', 'cache', 'dsh-caveman', 'learn'), version)
37
- const target = join(directory, `${expectedName}${platform === 'win32' ? '.exe' : ''}`)
38
- if (await fileDigest(target) === entry.sha256) return target
39
- await mkdir(directory, { recursive: true, mode: 0o700 })
40
- const temporary = join(directory, `.${expectedName}.${randomBytes(12).toString('hex')}.tmp`)
41
- let handle
42
- let dispatcher
43
- try {
44
- const url = `https://github.com/Lornatang/dsh-caveman/releases/download/v${version}/${expectedName}`
45
- let fetcher = options.fetcher ?? fetch
46
- if (!options.fetcher && (env.https_proxy || env.HTTPS_PROXY || env.http_proxy || env.HTTP_PROXY)) {
47
- const { EnvHttpProxyAgent, fetch: proxyFetch } = await import('undici')
48
- dispatcher = new EnvHttpProxyAgent({
49
- httpProxy: env.http_proxy ?? env.HTTP_PROXY ?? '',
50
- httpsProxy: env.https_proxy ?? env.HTTPS_PROXY ?? '',
51
- noProxy: env.no_proxy ?? env.NO_PROXY ?? '',
52
- })
53
- fetcher = (input, init) => proxyFetch(input, { ...init, dispatcher })
54
- }
55
- const response = await fetcher(url, { signal: AbortSignal.timeout(120_000) })
56
- if (!response.ok || !response.body) throw new Error(`Analyzer download failed (HTTP ${response.status})`)
57
- const advertised = Number(response.headers.get('content-length'))
58
- if (advertised > MAX_BINARY_BYTES) throw new Error('Analyzer download exceeds the size limit')
59
- handle = await open(temporary, 'wx', 0o700)
60
- const hash = createHash('sha256')
61
- let size = 0
62
- for await (const chunk of response.body) {
63
- size += chunk.length
64
- if (size > MAX_BINARY_BYTES) throw new Error('Analyzer download exceeds the size limit')
65
- hash.update(chunk)
66
- await handle.writeFile(chunk)
67
- }
68
- await handle.close()
69
- handle = undefined
70
- if (hash.digest('hex') !== entry.sha256) throw new Error('Analyzer checksum mismatch')
71
- await chmod(temporary, 0o700)
72
- try { await rename(temporary, target) } catch (error) {
73
- // Another invocation may have finished the same verified download.
74
- if (await fileDigest(target) !== entry.sha256) throw error
75
- }
76
- return target
77
- } finally {
78
- await handle?.close().catch(() => {})
79
- await rm(temporary, { force: true }).catch(() => {})
80
- await dispatcher?.destroy().catch(() => {})
81
- }
82
- }
1
+ import { createHash, randomBytes } from 'node:crypto'
2
+ import { createReadStream } from 'node:fs'
3
+ import { chmod, mkdir, open, readFile, rename, rm } from 'node:fs/promises'
4
+ import { homedir } from 'node:os'
5
+ import { join } from 'node:path'
6
+
7
+ const MAX_BINARY_BYTES = 120 * 1024 * 1024
8
+ const manifestUrl = new URL('./learn-checksums.json', import.meta.url)
9
+ const packageUrl = new URL('../package.json', import.meta.url)
10
+
11
+ async function fileDigest(path) {
12
+ try {
13
+ const hash = createHash('sha256')
14
+ for await (const chunk of createReadStream(path)) hash.update(chunk)
15
+ return hash.digest('hex')
16
+ } catch (error) {
17
+ if (error?.code === 'ENOENT') return undefined
18
+ throw error
19
+ }
20
+ }
21
+
22
+ /** Download and verify the executable once for the current platform and version. */
23
+ export async function resolveLearnBinary(options = {}) {
24
+ const { env = process.env, platform = process.platform, arch = process.arch } = options
25
+ if (env.DSH_CAVEMAN_LEARN_BINARY) return env.DSH_CAVEMAN_LEARN_BINARY
26
+ const manifest = options.manifest ?? JSON.parse(await readFile(manifestUrl, 'utf8'))
27
+ const version = JSON.parse(await readFile(packageUrl, 'utf8')).version
28
+ if (manifest.version !== version || !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u.test(version)) throw new Error('Invalid analyzer version manifest')
29
+ const os = { linux: 'linux', darwin: 'darwin', win32: 'win32' }[platform]
30
+ const cpu = { x64: 'amd64', arm64: 'arm64' }[arch]
31
+ const entry = manifest.binaries?.[`${platform}-${arch}`]
32
+ const expectedName = os && cpu ? `dsh-caveman-learn_${os}_${cpu}` : undefined
33
+ if (!expectedName || entry?.name !== expectedName || !/^[a-f0-9]{64}$/u.test(entry.sha256 ?? '')) {
34
+ throw new Error(`No verified analyzer is available for ${platform}/${arch}`)
35
+ }
36
+ const directory = join(options.cacheRoot ?? join(homedir(), '.dsh', 'cache', 'dsh-caveman', 'learn'), version)
37
+ const target = join(directory, `${expectedName}${platform === 'win32' ? '.exe' : ''}`)
38
+ if (await fileDigest(target) === entry.sha256) return target
39
+ await mkdir(directory, { recursive: true, mode: 0o700 })
40
+ const temporary = join(directory, `.${expectedName}.${randomBytes(12).toString('hex')}.tmp`)
41
+ let handle
42
+ let dispatcher
43
+ try {
44
+ const url = `https://github.com/Lornatang/dsh-caveman/releases/download/v${version}/${expectedName}`
45
+ let fetcher = options.fetcher ?? fetch
46
+ if (!options.fetcher && (env.https_proxy || env.HTTPS_PROXY || env.http_proxy || env.HTTP_PROXY)) {
47
+ const { EnvHttpProxyAgent, fetch: proxyFetch } = await import('undici')
48
+ dispatcher = new EnvHttpProxyAgent({
49
+ httpProxy: env.http_proxy ?? env.HTTP_PROXY ?? '',
50
+ httpsProxy: env.https_proxy ?? env.HTTPS_PROXY ?? '',
51
+ noProxy: env.no_proxy ?? env.NO_PROXY ?? '',
52
+ })
53
+ fetcher = (input, init) => proxyFetch(input, { ...init, dispatcher })
54
+ }
55
+ const response = await fetcher(url, { signal: AbortSignal.timeout(120_000) })
56
+ if (!response.ok || !response.body) throw new Error(`Analyzer download failed (HTTP ${response.status})`)
57
+ const advertised = Number(response.headers.get('content-length'))
58
+ if (advertised > MAX_BINARY_BYTES) throw new Error('Analyzer download exceeds the size limit')
59
+ handle = await open(temporary, 'wx', 0o700)
60
+ const hash = createHash('sha256')
61
+ let size = 0
62
+ for await (const chunk of response.body) {
63
+ size += chunk.length
64
+ if (size > MAX_BINARY_BYTES) throw new Error('Analyzer download exceeds the size limit')
65
+ hash.update(chunk)
66
+ await handle.writeFile(chunk)
67
+ }
68
+ await handle.close()
69
+ handle = undefined
70
+ if (hash.digest('hex') !== entry.sha256) throw new Error('Analyzer checksum mismatch')
71
+ await chmod(temporary, 0o700)
72
+ try { await rename(temporary, target) } catch (error) {
73
+ // Another invocation may have finished the same verified download.
74
+ if (await fileDigest(target) !== entry.sha256) throw error
75
+ }
76
+ return target
77
+ } finally {
78
+ await handle?.close().catch(() => {})
79
+ await rm(temporary, { force: true }).catch(() => {})
80
+ await dispatcher?.destroy().catch(() => {})
81
+ }
82
+ }
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "0.1.1",
2
+ "version": "0.1.3",
3
3
  "binaries": {
4
4
  "linux-x64": {
5
5
  "name": "dsh-caveman-learn_linux_amd64",
@@ -1,383 +0,0 @@
1
- <div align="center">
2
-
3
- ## New: Caveman Code. Free.
4
-
5
- **The most efficient coding agent.** Same model, same work, smaller bill.
6
-
7
- <table>
8
- <tr>
9
- <td align="center"><h3>21% cheaper</h3>than Codex<br><sub>Terminal-Bench 4, per solved task</sub></td>
10
- <td align="center"><h3>14% cheaper</h3>than Claude Code<br><sub>Terminal-Bench 4, 97 vs 83 solved</sub></td>
11
- <td align="center"><h3>76% cheaper</h3>than Claude Code<br><sub>full workday, 4 connected apps</sub></td>
12
- </tr>
13
- </table>
14
-
15
- <sub>Same model on both sides: GPT-6.1 Sol against Codex, Opus 5.5 against Claude Code. Our own runs, November 2026, at list prices. <a href="https://caveman.so/code">How we measured</a></sub>
16
-
17
- Every coding agent in one window. Free on the subscriptions and keys you already have.
18
-
19
- **[Download Caveman Code for Mac](https://caveman.so/download) · [Read the launch post](https://caveman.so/news/introducing-caveman-code)**
20
-
21
- ---
22
-
23
- <img src="docs/assets/caveman-logo-banner.png" alt="Caveman" width="720">
24
-
25
- # why many token when few do trick
26
-
27
- **Caveman make your AI agent say less and read less. Code stay exact. Brain still big.**
28
-
29
- <a href="https://github.com/JuliusBrussee/caveman/stargazers"><img src="https://img.shields.io/github/stars/JuliusBrussee/caveman?style=flat-square&color=F0A63C&label=stars" alt="GitHub stars"></a>
30
- <a href="https://www.npmjs.com/package/@caveman-ai/cli"><img src="https://img.shields.io/npm/dm/@caveman-ai/cli?style=flat-square&color=F0A63C&label=cli%20downloads" alt="npm downloads"></a>
31
- <a href="./INSTALL.md"><img src="https://img.shields.io/badge/works_with-30%2B_agents-orange?style=flat-square" alt="30+ agents"></a>
32
- <a href="#license"><img src="https://img.shields.io/badge/license-Apache--2.0-green?style=flat-square" alt="License"></a>
33
-
34
- <table>
35
- <tr>
36
- <td align="center" width="25%"><h3>33.2% fewer</h3>input tokens, whole sessions<br><sub><a href="#read-less-332-fewer-input-tokens">54 Claude Code runs</a>, 18 of 18 answers right</sub></td>
37
- <td align="center" width="25%"><h3>54% cheaper</h3>with Auto, same score<br><sub><a href="#auto-54-cheaper-same-score">85 coding tasks</a> vs Opus 5.5 at xhigh, interim</sub></td>
38
- <td align="center" width="25%"><h3>397 → 76</h3>tokens for one test run<br><sub><a href="#blocks-code-mode-script-written-once">Blocks</a> vs <code>| tail -20</code></sub></td>
39
- <td align="center" width="25%"><h3>1.4 to 2.4× cheaper</h3>with caveman-style output<br><sub><a href="https://arxiv.org/abs/2606.24083">Adobe Research</a>, eight models</sub></td>
40
- </tr>
41
- </table>
42
-
43
- Cited by **[Adobe Research](https://arxiv.org/abs/2606.24083)** · A/B tested by **[JetBrains](https://blog.jetbrains.com/ai/2026/07/speak-to-ai-agents-like-cavemen-tosave-tokens/)** · Remade for Elasticsearch on **[Elasticsearch Labs](https://www.elastic.co/search-labs/blog/elastic-caveman-ai-token-reduction)**<br>
44
- **#1** on [Hacker News](https://news.ycombinator.com/item?id=47647455) · **#1** on GitHub Trending · *"No way this actually works."* [ThePrimeagen](https://www.youtube.com/watch?v=L29q2LRiMRc)
45
-
46
- **[Install](#install) · [Six rocks](#six-rocks-one-install) · [Proof](#proof) · [Say less](#say-less-the-caveman-voice) · [Read less](#read-less-332-fewer-input-tokens) · [Auto](#auto-54-cheaper-same-score) · [Blocks](#blocks-code-mode-script-written-once) · [Commands](#commands) · [Caveman Cloud](#caveman-cloud)**
47
-
48
- </div>
49
-
50
- ---
51
-
52
- <table>
53
- <tr>
54
- <th width="50%">Normal agent · 63 tokens</th>
55
- <th width="50%"><img src="docs/assets/dancing-rock.svg" width="18" height="18" alt=""> Caveman agent · 20 tokens</th>
56
- </tr>
57
- <tr>
58
- <td valign="top">
59
-
60
- > The reason your React component is re-rendering is likely because you're creating a new object reference on each render cycle. When you pass an inline object as a prop, React's shallow comparison sees it as a different object every time, which triggers a re-render. I'd recommend using useMemo to memoize the object.
61
-
62
- </td>
63
- <td valign="top">
64
-
65
- > New object ref each render, so React re-renders. Wrap the prop in `useMemo`.
66
-
67
- </td>
68
- </tr>
69
- </table>
70
-
71
- **Same fix. 63 token become 20. Brain still big.**
72
-
73
- Pick your club:
74
-
75
- | Skill | Same answer | Tokens |
76
- |---|---|---:|
77
- | `/caveman` | New object ref each render, so React re-renders. Wrap the prop in `useMemo`. | 20 |
78
- | `/ultracave` | Inline object prop, new ref, re-render. `useMemo`. | 14 |
79
- | `/megacave` | 新參照致重繪。`useMemo`。 | **13** |
80
-
81
- <sub>Token counts: tiktoken o200k.</sub>
82
-
83
- ## Install
84
-
85
- ```bash
86
- npx @caveman-ai/cli@latest
87
- ```
88
-
89
- One command. Mac, Linux, Windows. Caveman find your agents and your logins, show what it change. Press Enter. Done. Needs Node.js 22.13+.
90
-
91
- After that, plain `claude` stays caveman'd. So do Codex, Gemini CLI, OpenCode, and [30+ more](./INSTALL.md). It runs on your machine, with your keys and your Claude Pro/Max login. One rock. That it.
92
-
93
- <sub>Had caveman before 4.0? Say <code>@latest</code>, or the old copy on your machine wins. Already set up? <code>caveman setup</code> opens the screen again. Only want shorter answers? <a href="#say-less-the-caveman-voice">Get just the skill</a>.</sub>
94
-
95
- ## Six rocks, one install
96
-
97
- New in 4.0: caveman is six parts. All on after install. Each has its own switch.
98
-
99
- | Rock | What it does | Measured |
100
- |---|---|---|
101
- | **[Say less](#say-less-the-caveman-voice)** | Agent answers short. Code stays exact | 63 → 20 tokens, same fix |
102
- | **[Read less](#read-less-332-fewer-input-tokens)** | Logs, JSON, CSV, test output shrink before the model reads them | **33.2%** fewer input tokens per session |
103
- | **[Auto](#auto-54-cheaper-same-score)** · new | Picks the model and the effort for each ask | **54%** cheaper than Opus at xhigh, same score |
104
- | **[Blocks](#blocks-code-mode-script-written-once)** · new | Code mode: agent keeps the scripts it writes and runs them again | **397 → 76** tokens for one test run |
105
- | **[Waste fixes](#smaller-rocks)** | Finds where your tokens go and fixes it. New: keeps the prompt cache warm while you pause | Not measured yet |
106
- | **[Browse](#smaller-rocks)** | Web pages come back compressed | **129.8×** smaller page |
107
-
108
- `caveman status` shows what is on. `caveman off browse` turns one off. Only Auto needs an account, and it is free. [4.0.0 release notes](https://github.com/JuliusBrussee/caveman/releases/tag/v4.0.0)
109
-
110
- ## Proof
111
-
112
- Outside labs first. Ours come with each rock below. Nothing rounded up. Red rows stay red.
113
-
114
- | Who | Setup | Result |
115
- |---|---|---|
116
- | **[Adobe Research](https://arxiv.org/abs/2606.24083)**, CAVEWOMAN paper (cites this repo) | Caveman-style output, eight models, five datasets | **Cost cut 1.4 to 2.4× per model, up to 3×** |
117
- | **[Elastic](https://www.elastic.co/search-labs/blog/elastic-caveman-ai-token-reduction)**, Elasticsearch Labs | Caveman mode remade for Elasticsearch, eight live MCP scenarios | **63.6% fewer response tokens.** *"Zero information loss."* |
118
- | **[JetBrains](https://blog.jetbrains.com/ai/2026/07/speak-to-ai-agents-like-cavemen-tosave-tokens/)** | 86 real coding tasks, paired A/B | **No measurable quality loss** (p = 0.82). 8.5% fewer output tokens |
119
-
120
- Two findings shaped caveman. Adobe: cavemanning *your* prompt makes answers worse, so caveman never touches your prompt. JetBrains: agent sessions are mostly code and tool calls, which the voice leaves alone. So caveman grew rocks that shrink what the agent *reads* and what it *runs on*.
121
-
122
- ## Say less: the caveman voice
123
-
124
- **A voice, not broken grammar. Every reply follows the same structure.**
125
-
126
- | Rule | What it means |
127
- |---|---|
128
- | **Answer first** | `[thing] [action] [reason]. [next step].` No greeting, no "let me", no recap |
129
- | **One idea per sentence** | Built on [ASD-STE100](https://www.asd-ste100.org/), the controlled English of aircraft maintenance manuals: 20 words max, active voice, one term per thing |
130
- | **Meaning never dropped** | Articles can go. *not*, *never*, *no*, *only* never go. Numbers and units stay exact |
131
- | **Payload verbatim** | Code, commands, paths, and error messages untouched, character for character |
132
- | **No theater** | No "me think". No chatter between tool calls. If caveman phrasing isn't shorter, plain wins |
133
- | **Knows when to stop** | Security warnings, irreversible actions, and confused users get full sentences. Then grunt resumes |
134
- | **Your prompts stay yours** | Never rewritten. [Research say that backfire](#proof) |
135
-
136
- Ten dev questions on claude-opus-5-5:
137
-
138
- | Instruction | Output tokens |
139
- |---|---:|
140
- | None | 6,983 |
141
- | `Answer concisely.` | 4,334 |
142
- | `/caveman` | 4,119 |
143
- | `/ultracave` | **2,693** |
144
-
145
- "Be concise" is the real baseline; new models already know it. On top of it, `/caveman` cuts 3% more at the median and `/ultracave` 35% more. Measured on the 3.1.0 rules, not yet re-run. The rules cost about 1,160 tokens of input, and if you pay per request (GitHub Copilot), shorter answers save nothing. [Harness](./evals/README.md) · [Every case where caveman loses](./docs/HONEST-NUMBERS.md)
146
-
147
- <!-- BENCHMARK-TABLE-START -->
148
- <!-- BENCHMARK-TABLE-END -->
149
-
150
- **Only want this rock?** The skill alone, no proxy:
151
-
152
- ```bash
153
- npx skills add JuliusBrussee/caveman -g
154
- ```
155
-
156
- <a href="https://skills.sh/JuliusBrussee/caveman"><img src="https://skills.sh/b/JuliusBrussee/caveman" alt="skills.sh"></a>
157
-
158
- Type `/caveman` (`$caveman` in Codex) if it doesn't start on its own. Say `stop caveman` to go back.
159
-
160
- <details>
161
- <summary><strong>Other ways in</strong>: Claude app and phone, Claude Code plugin, Gemini, every agent at once, Windows, uninstall</summary>
162
-
163
- <br>
164
-
165
- Claude on the web, the phone app, or Cowork? No terminal. Add caveman to your Claude account once, in Customize > Plugins: [steps](./INSTALL.md#claude-apps-claudeai-desktop-mobile-cowork). Not tested end to end yet.
166
-
167
- ```bash
168
- # Claude Code plugin, auto-starts every interactive session, subagents too
169
- claude plugin marketplace add JuliusBrussee/caveman && claude plugin install caveman@caveman
170
-
171
- # Gemini CLI
172
- gemini extensions install https://github.com/JuliusBrussee/caveman
173
-
174
- # Every agent on your machine at once, plus the Claude Code statusline badge (Node.js 22.13+)
175
- curl -fsSL https://raw.githubusercontent.com/JuliusBrussee/caveman/v4.1.0/install.sh | bash
176
- ```
177
-
178
- Already inside Claude Code? Same rock, slash form. Type these where you talk to Claude:
179
-
180
- ```text
181
- /plugin marketplace add JuliusBrussee/caveman
182
- /plugin install caveman@caveman
183
- ```
184
-
185
- Windows, PowerShell 5.1+:
186
-
187
- ```powershell
188
- irm https://raw.githubusercontent.com/JuliusBrussee/caveman/v4.1.0/install.ps1 | iex
189
- ```
190
-
191
- On npm 12 or newer, new npm block git install. One-liners above handle it themselves from v3.2.0 on. Old one-liner pinned to v3.1.0 or older still fail there: use one above, or this:
192
- `npx --allow-git=root -y github:JuliusBrussee/caveman#v4.1.0`
193
-
194
- Changed your mind: `npx -y github:JuliusBrussee/caveman -- --uninstall` (on npm 12+, add `--allow-git=root` too)
195
-
196
- Only grabbed the skill? `npx skills remove JuliusBrussee/caveman -g` take it back out.
197
-
198
- Install broke? Open your agent in this repo and say *"Read CLAUDE.md and INSTALL.md, install caveman for me."* Agent fix own brain.
199
-
200
- </details>
201
-
202
- ## Read less: 33.2% fewer input tokens
203
-
204
- **The voice shrinks what the agent says. This shrinks what it reads. Same answers: 18 of 18 right.**
205
-
206
- | File type | The file, through caveman | File saved | Whole Claude Code session, 3 runs | Session saved |
207
- |---|---:|---:|---:|---:|
208
- | CSV | 28,041 → **314** | **98.9%** | 165,823 → 74,484 | **55.1%** |
209
- | Logs | 22,810 → **348** | **98.5%** | 148,807 → 74,068 | **50.2%** |
210
- | YAML | 20,447 → **178** | **99.1%** | 132,124 → 71,027 | **46.2%** |
211
- | Test output | 18,806 → **203** | **98.9%** | 150,377 → 108,514 | **27.8%** |
212
- | JSON | 18,837 → **281** | **98.5%** | 147,975 → 108,939 | **26.4%** |
213
- | HTML | 21,670 → 21,670 | none yet | 140,687 → 154,641 | 9.9% worse |
214
- | **All six** | 130,611 → 22,994 | 82.4% | **885,793 → 591,673** | **33.2%** |
215
-
216
- *The file* is each test file through today's compressor alone. *The session* is the whole agent run, which also carries the system prompt and tools, so it moves less. Honest part: the session run is from August 2026 on an older engine, HTML has no compressor yet so it lost, and each test file hides one record in 61 to 72 KB of noise. Yours will vary. Headroom on the same suite: 15 of 18 right, 6.7% fewer tokens. [Method](./docs/WRAP-BENCHMARK.md#per-file-compression)
217
-
218
- Every original stays on your disk. The agent can pull it back any time.
219
-
220
- ## Auto: 54% cheaper, same score
221
-
222
- **New model in your agent's picker. Pick Auto and caveman chooses the model and the effort for each ask. Hard ask, big brain. Easy ask, save rocks.**
223
-
224
- | Setup | Tasks solved | Cost per try | Median time |
225
- |---|---:|---:|---:|
226
- | Opus 5.5, xhigh effort, every ask | 44.3% | $7.83 | 35.2 min |
227
- | **Auto**, Claude models only | **43.7%** | **$3.59** | **15.9 min** |
228
- | **Auto**, plus OpenAI and open models | 42.9% | $3.47 | 16.7 min |
229
-
230
- Auto costs 0.46× what Opus 5.5 at xhigh costs. That is 54% saved, in under half the time. 85 real coding tasks from SWE-Interact and SWE-Together, one try each. Honest part: the run is half done, the 0.5-point score gap is too small to tell apart at this size (±7), and most of the saving is Auto lowering effort on easy asks. Already on Opus at medium? Expect less; not measured yet. [Full table and limits](./docs/AUTO-BENCHMARK.md)
231
-
232
- ```bash
233
- caveman login # free account. Auto shows up in the model picker
234
- caveman providers add openai # optional: give Auto more models, on your own key
235
- ```
236
-
237
- Works in Claude Code, OpenCode, and Codex on a ChatGPT login, with API keys, Claude Pro/Max, or ChatGPT. Any other model you pick runs as picked. Not signed in: no Auto, nothing sent. [What Auto sends](#privacy)
238
-
239
- ## Blocks: code mode, script written once
240
-
241
- **skills.sh for code mode.** Code mode is the agent writing a script instead of making tool call after tool call ([Cloudflare](https://blog.cloudflare.com/code-mode/), [Anthropic](https://www.anthropic.com/engineering/code-execution-with-mcp)). Problem: agent write same script every session, throw it away, write it again. Blocks keep it in your repo, check it every pull request, hand it back.
242
-
243
- | Input | Raw | What agents type now | Block |
244
- |---|---:|---:|---:|
245
- | `go test -v ./...`, 326 tests | 10,561 | 397 · `\| tail -20` | **76** · `test-summary` |
246
- | 1.4 MB JSON file | 251,893 | 236 · their own heredoc | **227** · `json-peek` |
247
- | 366-line Go file | 3,111 | **250** · `grep -n` | 489 · `grep-defs` |
248
-
249
- Tokens the agent reads back. In one week, agents on one machine wrote the same script [394 times](https://github.com/caveman-ai/blocks#one-script-written-394-times-in-a-week). [Purdue](https://arxiv.org/abs/2609.30725) measured the habit at up to 9.57% of task cost. `grep-defs` loses to a bare grep; row stays. [Method](https://github.com/caveman-ai/blocks#blocks-against-what-agents-type-now)
250
-
251
- Comes with caveman. Eight blocks ready: `json-peek` · `jsonl-stats` · `test-summary` · `first-error` · `wait-for` · `grep-defs` · `http-json` · `replace-in-file`. When the agent starts typing a script a block already covers, it gets one line: use the block. Never denies or rewrites a command.
252
-
253
- ```bash
254
- caveman-blocks scan # what your agents retyped this month. Script text never leaves your machine
255
- caveman-blocks init # rules and block index into this repo's AGENTS.md
256
- ```
257
-
258
- Pre-release (v0.1.0-rc.5). Python only, no sandbox yet. Own repo, own stars: **[caveman-ai/blocks](https://github.com/caveman-ai/blocks)**
259
-
260
- ## Smaller rocks
261
-
262
- | Rock | What it does | Measured |
263
- |---|---|---|
264
- | `caveman learn` | Ranks where your tokens go, from agent history already on disk. `caveman learn implement` applies fixes one diff at a time, only on your yes | Not yet |
265
- | Warm cache · new | Step away and the provider forgets your session, so the next ask pays full price. Caveman keeps Anthropic's prompt cache warm while you pause, only when your own history says you come back in time. Every warm is listed in `caveman stats` | Not yet |
266
- | `caveman browse <url>` | A compressed web page for the agent | **121 tokens instead of 15,704** for a Playwright snapshot of a 200-row table. Tiny forms lose 2.3×. [Bench](./browse/BENCHMARK.md) |
267
- | `/caveman-compress <file>` | Shrinks memory files like `CLAUDE.md`, keeps a backup | **4,138 tokens instead of 6,198** across five files, 22.8% to 49.1% each, every heading, code block, and path intact. [Bench](./skills/caveman-compress/README.md#benchmarks) |
268
- | Middleware | Same shrinking inside the Vercel AI SDK, LangChain, OpenAI, or Anthropic call you already make. [TypeScript](./packages/middleware/typescript/README.md) · [Python](./packages/middleware/python/README.md) · [Every framework](https://docs.caveman.so/caveman/middleware) · [One container for the team](docs/technical/deploy.md) | Not yet |
269
-
270
- <p align="center">
271
- <img src="docs/assets/learn-report.png" alt="Caveman Learn report: a summary and savings cards on the left; the biggest places tokens go, with one fix opened, and a chart of how full sessions get on the right" width="900">
272
- </p>
273
-
274
- ## Commands
275
-
276
- In your terminal:
277
-
278
- ```bash
279
- caveman claude # start an agent on caveman: codex · gemini · opencode · aider · kilo · qwen · hermes · openclaw · pi
280
- caveman status # what is on, which agents it reaches, one next step
281
- caveman on browse # switch one rock on or off: output · input · waste-fixes · routing · scripts · browse
282
- caveman login # free account, turns on Auto
283
- caveman learn # where your tokens go
284
- caveman trial -- claude # A/B a real session on your own work
285
- caveman shrink -- pnpm test # compress noisy command output
286
- caveman convert --dry-run # pixel mode: skills the model reads as images
287
- caveman stats # your token history
288
- caveman doctor # one problem per line, with its fix
289
- ```
290
-
291
- In your agent:
292
-
293
- | Command | What it does |
294
- |---|---|
295
- | `/caveman` · `/ultracave` · `/megacave` | The voice, the grunt, the 文言文. `/caveman status` shows the mode, `/caveman off` stops it |
296
- | `/caveman-commit` | One-line Conventional Commit |
297
- | `/caveman-review` | One finding per line: `L42: 🔴 null deref. Guard it.` |
298
- | `/caveman-compress <file>` | Shrinks memory files and backs up the original |
299
- | `/caveman-stats` | Real token usage for this Claude Code session |
300
- | `/caveman-help` | Every mode and command on one screen |
301
- | `cavecrew` | Subagents that find, edit, and review code, then report back in caveman |
302
- | `investigate-first` · `lean-build` · `surgical-patch` · `safe-refactor` · `migration` · `verify-and-stop` | Work patterns that write less code. Your agent picks them up when a task fits |
303
- | `caveman-setup` · `caveman-discover` · `caveman-learn` · `caveman-manage` · `caveman-optimize` · `caveman-explore` · `caveman-evidence-review` | Drive the proxy from inside your agent |
304
-
305
- ## Caveman Cloud
306
-
307
- **Everything above is for the coding agent you use. Caveman Cloud is for the agents you build.**
308
-
309
- You ship an agent. Every run costs money. Is it good? Is it cheap? Which change made it worse? Cloud answers.
310
-
311
- | Cloud does | What you get |
312
- |---|---|
313
- | **Observability** | Every run traced to the work and what it cost. Sets itself up from your repo, your keys, and the logs or OpenTelemetry you already have |
314
- | **Evals** | Grades how good the answers are, on your own tasks, from your real traffic |
315
- | **Autopilot** | Proposes a cheaper change, tests it on your recorded work, ships only when the evals say answers are still as good. You approve the pull request |
316
- | **Proof** | Every number says if it is measured, inferred, or verified. A saving counts only after real traffic shows it |
317
-
318
- <p align="center">
319
- <a href="https://app.caveman.so/signup"><b>Sign up free</b></a> &nbsp;·&nbsp; <a href="https://caveman.so/demo">Try the demo</a> &nbsp;·&nbsp; <a href="https://cal.com/caveman/chat">Book a call</a> &nbsp;·&nbsp; <a href="https://docs.caveman.so">Docs</a>
320
- </p>
321
-
322
- ## In the wild
323
-
324
- <a href="https://www.youtube.com/watch?v=L29q2LRiMRc"><img src="https://img.youtube.com/vi/L29q2LRiMRc/hqdefault.jpg" alt="ThePrimeagen reacts to Caveman: No way this actually works" width="340" align="right"></a>
325
-
326
- **ThePrimeagen**: *"No way this actually works."* [Watch](https://www.youtube.com/watch?v=L29q2LRiMRc)
327
-
328
- **Adobe Research**: [CAVEWOMAN](https://arxiv.org/abs/2606.24083), arXiv, June 2026
329
-
330
- **JetBrains**: *"It is fun, and it costs you nothing measurable in quality."* [Read](https://blog.jetbrains.com/ai/2026/07/speak-to-ai-agents-like-cavemen-tosave-tokens/)
331
-
332
- **Elastic**: [elastic-caveman](https://www.elastic.co/search-labs/blog/elastic-caveman-ai-token-reduction) on Elasticsearch Labs, April 2026
333
-
334
- **Hacker News**: [#1, 904 points](https://news.ycombinator.com/item?id=47647455)
335
-
336
- **GitHub Trending** #1 overall, July 2026 · **[Trendshift](https://trendshift.io/repositories/25391)** #1 repo of the day, April 2026 · **[Product Hunt](https://www.producthunt.com/products/caveman)** #8 of the day
337
-
338
- Started as a joke in April 2026. Now past 100,000 stars. Joke got serious. Voice did not.
339
-
340
- <br clear="right">
341
-
342
- [![Star History Chart](./docs/assets/star-history.png)](https://star-history.com/#JuliusBrussee/caveman&Date)
343
-
344
- ## Privacy
345
-
346
- - **The skill** runs on your machine and sends nothing. One exception: `/caveman-compress` sends the file you compress to your configured model provider.
347
- - **The CLI** sends usage stats by default: commands run, token counts, caveman-blocks commands and usage counts, a random install ID, OS, and IP. Never your prompts, code, file paths, or scripts you wrote. One person maintains this for free, and those stats show what to build next. Off for good, Blocks included: `caveman telemetry off` or `DO_NOT_TRACK=1`.
348
- - **Auto**, only once you sign in and pick it: each ask sends Caveman Cloud your latest ask (with whatever your agent attaches to it, such as CLAUDE.md, memory or @-mentioned files), the one before it, and the end of the agent's last reply, plus each request's tool names, effort, a few agent headers, and the previous request's token counts. On the Free plan Caveman may keep it to improve routing. `caveman off routing` stops it.
349
- - **Where requests go:** from your machine to your provider, or to another provider you added with `caveman providers add`, on your own key. Only a request routed to a Caveman Cloud model passes through Caveman Cloud, whole (system prompt, tool results, code), on your Caveman project's stored key, billed to that project. `caveman providers cloud off` stops that.
350
-
351
- The full list, and how to delete sent telemetry: [SECURITY.md](./SECURITY.md).
352
-
353
- ## License
354
-
355
- [Apache-2.0](./LICENSE), whole repo. Read it, fork it, ship it, host it. Free like mammoth on open plain. Older releases and third-party notices: [LICENSING.md](./LICENSING.md). "Caveman" and the rock logo are trademarks of Julius Brussee.
356
-
357
- ## Cite
358
-
359
- ```bibtex
360
- @software{brussee2026caveman,
361
- author = {Brussee, Julius},
362
- title = {Caveman: why many token when few do trick},
363
- year = {2026},
364
- url = {https://github.com/JuliusBrussee/caveman}
365
- }
366
- ```
367
-
368
- ---
369
-
370
- <div align="center">
371
-
372
- 🪨 **Caveman save you token. Star cost zero. Fair trade.**
373
-
374
- <sub>
375
- <a href="./docs/README.md">Docs</a> ·
376
- <a href="./INSTALL.md">Install matrix</a> ·
377
- <a href="./docs/HONEST-NUMBERS.md">Honest numbers</a> ·
378
- <a href="./CONTRIBUTING.md">Contributing</a> ·
379
- <a href="https://app.caveman.so/signup">Caveman Cloud</a> ·
380
- <a href="https://github.com/JuliusBrussee/caveman/issues">Issues</a>
381
- </sub>
382
-
383
- </div>
@@ -1,211 +0,0 @@
1
- # Caveman Hooks
2
-
3
- These hooks are **bundled with the caveman plugin** and activate automatically when the plugin is installed. No manual setup required.
4
-
5
- If you installed caveman standalone (without the plugin), the unified Node installer at `installer/install.js` wires them into your `settings.json` for you — run `node installer/install.js --only claude` from a clone, or `npx -y github:JuliusBrussee/caveman -- --only claude` for the curl-pipe path.
6
-
7
- ## What's Included
8
-
9
- ### Where the mode lives
10
-
11
- The mode is **per session**. Each Claude Code window stores its own mode in
12
- `$CLAUDE_CONFIG_DIR/.caveman-sessions/<session_id>.mode` (default
13
- `~/.claude/.caveman-sessions/`), keyed by the `session_id` that Claude Code puts
14
- in every hook payload and in the statusline's stdin JSON.
15
-
16
- `$CLAUDE_CONFIG_DIR/.caveman-active` still exists as a **last-write-wins
17
- mirror** of whichever session wrote most recently. It is kept so `cat` still
18
- answers "is caveman on", and so third-party statusline snippets keep working.
19
-
20
- Two things worth knowing about the mirror:
21
-
22
- - It **never** contains the literal string `off`. Deactivation deletes it, just
23
- as before. `off` is a valid mode name, so an older hook or statusline reading
24
- `off` from that path would treat it as an active mode and render
25
- `[CAVEMAN:OFF]` or inject "CAVEMAN MODE ACTIVE (off)".
26
- - With two windows open it shows the other window's mode half the time. Read the
27
- per-session file if you need the truth for a specific window.
28
-
29
- Readers accept both spellings of "off": a missing file (the old meaning) and a
30
- literal `off` in a session file (the new, durable one).
31
-
32
- ### `caveman-activate.js` — SessionStart hook
33
-
34
- - Runs on every SessionStart — `source` is `startup`, `resume`, `clear`, `compact` or `fork`
35
- - Resolves this session's mode and persists it via the symlink-safe `safeWriteFlag` helper
36
- - Emits the active mode's skill (`skills/caveman`, `skills/ultracave` or `skills/megacave`) as hidden SessionStart context
37
- - Sweeps session files older than 14 days (`CAVEMAN_SESSION_TTL_MS` overrides), on new sessions only
38
- - Detects missing statusline config and emits setup nudge (Claude will offer to help)
39
-
40
- **Why `source` matters.** The hook is registered with no matcher, so it fires
41
- for every source — deliberately, because compaction is what prunes the ruleset
42
- out of context and lets the model drift back to verbose prose, so the rules must
43
- be re-injected afterwards. What it must *not* do on a continuation (`compact`,
44
- `resume`, `fork`) is re-derive the configured default and overwrite the
45
- session's mode. Doing that is how an explicit "stop caveman" used to get
46
- silently undone by the next auto-compaction. `clear` counts as a fresh start,
47
- since it is an explicit user reset.
48
-
49
- **Headless sessions start off.** `claude -p` and Agent SDK sessions
50
- (`CLAUDE_CODE_ENTRYPOINT=sdk-cli`, `sdk-ts`, `sdk-py`) are often tools that
51
- probe Claude and parse the reply, so they start under the `manual` policy:
52
- nothing injected until an explicit `/caveman`. Interactive surfaces (terminal,
53
- VS Code, desktop) are unaffected. Set `CAVEMAN_DEFAULT_MODE=<mode>` in the
54
- environment to opt a headless run back in.
55
-
56
- ### `caveman-activate.js --subagent` — SubagentStart hook
57
-
58
- - SessionStart context reaches only the main conversation, so subagents never saw caveman. This hook hands each new subagent **this session's** active skill
59
- - Injects nothing once the session has stored `off`, so "stop caveman" never leaks into subagents, even if another window turns caveman on
60
- - A session with no stored mode at all (its SessionStart hook never ran or failed) falls back to the shared mirror, the same as the per-turn reminder its main conversation gets
61
- - Skips the cavecrew agents (they already talk ultracave), one-shot modes (`commit`/`review`/`compress`), and projects whose repo config says `defaultMode: "off"`
62
- - Read-only: it never writes mode state, logs, or marker files
63
-
64
- ### `caveman-mode-tracker.js` — UserPromptSubmit hook
65
-
66
- - Fires on every user prompt, checks for `/caveman`, `/ultracave`, `/megacave` commands and natural-language activation/deactivation phrases ("talk like caveman", "stop caveman", "normal mode")
67
- - Writes the active mode for **this session** when a caveman command is detected; on deactivation it stores a durable `off` and clears the legacy mirror
68
- - Emits a small per-turn reinforcement reminder when the session's mode is a prose one (`caveman`/`ultracave`/`megacave`), built from that skill's first line
69
- - Remembers the displaced prose mode per session, so two windows each running `/caveman-commit` return to their own mode
70
- - Stores: `caveman`, `ultracave`, `megacave`, `commit`, `review`, `compress`, `off`. Older level names still read correctly: `lite`/`full` → `caveman`, `ultra` → `ultracave`, `wenyan*` → `megacave`
71
-
72
- ### `caveman-statusline.sh` / `caveman-statusline.ps1` — Statusline badge script
73
-
74
- - Reads the session JSON Claude Code sends on stdin, takes `session_id`, and renders **that window's** mode; falls back to the legacy mirror when there is no usable id
75
- - Shows `[CAVEMAN]`, `[ULTRACAVE]`, `[MEGACAVE]`, `[CAVEMAN:COMMIT]`, etc. A deactivated session renders nothing at all — never `[CAVEMAN:OFF]`
76
- - Never blocks: an interactive terminal is not read from, and the stdin read has a 1s ceiling (integer, because macOS ships bash 3.2 and it rejects fractional `read -t`)
77
- - Shows mode only. The old `⛏` savings suffix is gone: `.caveman-statusline-suffix` is ignored, because a transcript cannot show what caveman saved
78
-
79
- ### `caveman-stats.js --record` — SessionEnd hook
80
-
81
- - Runs when Claude Code ends a session
82
- - Reads `session_id` and `transcript_path` from the hook payload on stdin (first complete JSON object, 2s watchdog) and appends one snapshot to `$CLAUDE_CONFIG_DIR/.caveman-history.jsonl`: recorded output and cache-read tokens, turns, and per-mode attribution. No savings figures
83
- - Writes no stdout and always exits 0, so it never interrupts shutdown
84
- - Duplicate snapshots are safe: lifetime views (`--all`, `--since`) count only the newest row per `session_id`
85
-
86
- ## Statusline Badge
87
-
88
- The statusline badge shows which caveman mode is active directly in your Claude Code status bar.
89
-
90
- **Plugin users:** If you do not already have a `statusLine` configured, Claude will detect that on your first session after install and offer to set it up for you. Accept and you're done.
91
-
92
- If you already have a custom statusline, caveman does not overwrite it and Claude stays quiet. Add the badge snippet to your existing script instead.
93
-
94
- **Standalone users:** the unified installer (`installer/install.js`, invoked by the `install.sh` / `install.ps1` shims at the repo root) wires the statusline automatically if you do not already have a custom statusline. If you do, the installer leaves it alone and prints the merge note.
95
-
96
- **Manual setup:** If you need to configure it yourself, add one of these to `~/.claude/settings.json`:
97
-
98
- ```json
99
- {
100
- "statusLine": {
101
- "type": "command",
102
- "command": "bash /path/to/caveman-statusline.sh"
103
- }
104
- }
105
- ```
106
-
107
- ```json
108
- {
109
- "statusLine": {
110
- "type": "command",
111
- "command": "powershell -ExecutionPolicy Bypass -File C:\\path\\to\\caveman-statusline.ps1"
112
- }
113
- }
114
- ```
115
-
116
- Replace the path with the actual script location (e.g. `~/.claude/hooks/` for standalone installs, or the plugin install directory for plugin installs).
117
-
118
- **Custom statusline:** If you already have a statusline script, add this snippet
119
- to it. It reads the session id from the JSON Claude Code gives your script on
120
- stdin, so the badge tracks the window it belongs to. If your script already
121
- consumed stdin, pass what you read in as `$caveman_payload` instead of
122
- re-reading it — stdin can only be drained once.
123
-
124
- ```bash
125
- caveman_cfg="${CLAUDE_CONFIG_DIR:-$HOME/.claude}"
126
- caveman_payload="${caveman_payload:-}"
127
- if [ -z "$caveman_payload" ] && [ ! -t 0 ]; then
128
- IFS= read -r -d '' -t 1 caveman_payload
129
- fi
130
- caveman_sid=$(printf '%s' "$caveman_payload" \
131
- | grep -o '"session_id"[[:space:]]*:[[:space:]]*"[^"]*"' \
132
- | head -1 | sed -e 's/.*:[[:space:]]*"//' -e 's/"$//')
133
- case "$caveman_sid" in ''|*[!A-Za-z0-9_-]*) caveman_sid="" ;; esac
134
-
135
- caveman_flag="$caveman_cfg/.caveman-active"
136
- if [ -n "$caveman_sid" ] && [ -f "$caveman_cfg/.caveman-sessions/$caveman_sid.mode" ]; then
137
- caveman_flag="$caveman_cfg/.caveman-sessions/$caveman_sid.mode"
138
- fi
139
-
140
- caveman_text=""
141
- if [ -f "$caveman_flag" ]; then
142
- caveman_mode=$(cat "$caveman_flag" 2>/dev/null)
143
- case "$caveman_mode" in
144
- caveman|lite|full) caveman_badge="CAVEMAN" ;;
145
- ultracave|ultra) caveman_badge="ULTRACAVE" ;;
146
- megacave|wenyan*) caveman_badge="MEGACAVE" ;;
147
- commit|review|compress) caveman_badge="CAVEMAN:$(echo "$caveman_mode" | tr '[:lower:]' '[:upper:]')" ;;
148
- *) caveman_badge="" ;; # off or unknown — render nothing
149
- esac
150
- [ -n "$caveman_badge" ] && caveman_text=$'\033[38;5;172m['"${caveman_badge}"$']\033[0m'
151
- fi
152
- ```
153
-
154
- The older one-file version of this snippet reads the legacy mirror, so it shows
155
- whichever window wrote last and renders the new ids as `[CAVEMAN:CAVEMAN]` or
156
- `[CAVEMAN:ULTRACAVE]`; re-run the installer to pick up the badge map above. It
157
- never sees a literal `off` because the legacy mirror is deleted on deactivation.
158
-
159
- Badge examples:
160
- - `/caveman` → `[CAVEMAN]`
161
- - `/ultracave` → `[ULTRACAVE]`
162
- - `/megacave` → `[MEGACAVE]`
163
- - `/caveman-commit` → `[CAVEMAN:COMMIT]`
164
- - `/caveman-review` → `[CAVEMAN:REVIEW]`
165
-
166
- ## How It Works
167
-
168
- ```
169
- SessionStart hook ──┐ ┌── UserPromptSubmit hook
170
- (session_id, │ │ (session_id, prompt)
171
- source) ▼ ▼
172
- $CLAUDE_CONFIG_DIR/.caveman-sessions/<session_id>.mode
173
- │ │
174
- mirrors reads
175
- ▼ ▼
176
- .caveman-active Statusline script ◀── session JSON on stdin
177
- (last-write-wins, [CAVEMAN] / [ULTRACAVE] / [MEGACAVE]
178
- compat only)
179
-
180
- SessionEnd hook ──(session_id, transcript_path)──▶ caveman-stats.js --record
181
- ──appends──▶ .caveman-history.jsonl
182
- ```
183
-
184
- SessionStart stdout is injected as hidden system context — Claude sees it, users
185
- don't. The statusline runs as a separate process. All three surfaces get
186
- `session_id` from Claude Code, which is what lets each window keep its own mode.
187
-
188
- Every path here honors `CLAUDE_CONFIG_DIR`. All state writes go through
189
- `safeWriteFlag()` (symlink-refusing, atomic, `0600`), and every read is
190
- whitelist-validated — a session id is never interpolated into a path without
191
- passing `^[A-Za-z0-9_-]{1,128}$` first.
192
-
193
- ## Uninstall
194
-
195
- If installed via plugin: disable the plugin — hooks deactivate automatically.
196
-
197
- If installed via the standalone Node installer:
198
- ```bash
199
- npx -y github:JuliusBrussee/caveman -- --uninstall
200
- # or, from a clone:
201
- node installer/install.js --uninstall
202
- ```
203
-
204
- Or manually:
205
- 1. Remove the caveman hook files from `$CLAUDE_CONFIG_DIR/hooks/` (default `~/.claude/hooks/`): `caveman-activate.js`, `caveman-mode-tracker.js`, `caveman-parse.js`, `caveman-stats.js`, `caveman-config.js`, `cavecrew-model-overrides.js`, and `caveman-statusline.{sh,ps1}`.
206
- 2. Remove the SessionStart, SubagentStart, UserPromptSubmit, SessionEnd, and statusLine entries from `$CLAUDE_CONFIG_DIR/settings.json`.
207
- 3. Delete the mode state from `$CLAUDE_CONFIG_DIR`: the `.caveman-sessions/` directory, `.caveman-active`, `.caveman-active.prev`, `.caveman-mode-log.jsonl`, `.caveman-statusline-suffix`, and `.caveman-nudge-shown`.
208
-
209
- The uninstaller does all of step 3 for you, but deliberately leaves
210
- `.caveman-history.jsonl` alone — that is your accumulated lifetime savings
211
- record, not caveman plumbing. Delete it by hand if you want it gone.