@fabersep/cache 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,15 @@
1
+ # Changelog
2
+
3
+ All notable changes to `@fabersep/cache`. Versions follow [Semantic Versioning](https://semver.org/).
4
+
5
+ ## 0.2.0 (2026-12-02)
6
+
7
+ ### Added
8
+ - `faber-cache model`: show, set and unset the global or per-project model (`faber-cache model opus`, `faber-cache model haiku --project .`, `--unset`). The README explains that every model has its own cache.
9
+
10
+ ### Fixed
11
+ - The activity of interactive sessions forked from a base now counts as a base read, so a base that such a session kept warm is no longer declared stale and rebuilt at full price. `status` reports `lastReadMinAgo` the same way.
12
+
13
+ ## 0.1.0 (2026-11-29)
14
+
15
+ - First public release.
package/README.md CHANGED
@@ -49,6 +49,25 @@ faber-cache open
49
49
 
50
50
  What it saves: a session that would otherwise load 34K tokens of project files pays for them at a twentieth of the price (a cache read at 0.1x instead of a cache write at 2x). The first `open` in an hour pays for the base. Every later one that hour is cheap.
51
51
 
52
+ ### Choosing the model
53
+
54
+ `open` starts the session on **Sonnet** unless you say otherwise. The model is picked in this order: the `--model` flag, then the project's `model` in `config.json`, then the global `model` in `config.json` (default `sonnet`).
55
+
56
+ ```bash
57
+ faber-cache open --model opus # this session only
58
+ ```
59
+
60
+ > **Warning: every model has its own cache.** The model is part of the base's key, so a base built for Sonnet is never reused by an Opus session. The first `open` with a new model builds a fresh base (the slow, full-price one); only the later ones that hour are cheap. Switching models inside the session with `/model` does the same: that session no longer reads the base from cache. Pick the model you work with most and make it the default.
61
+
62
+ Set the default with a command (it writes `~/.faber/cache/config.json` for you):
63
+
64
+ ```bash
65
+ faber-cache model # show the global, project and effective model
66
+ faber-cache model opus # default for every project
67
+ faber-cache model haiku --project . # this project only (wins over the global one)
68
+ faber-cache model --unset --project . # back to the global default
69
+ ```
70
+
52
71
  Two things to know:
53
72
 
54
73
  - It runs in a terminal. A session started with the **+** button in the Claude desktop app is a fresh session and does not start from the base.
package/dist/src/cli.js CHANGED
@@ -2,7 +2,7 @@
2
2
  import * as fs from 'node:fs';
3
3
  import * as path from 'node:path';
4
4
  import { parseArgs } from 'node:util';
5
- import { DEFAULT_PACKET, expandHome, loadConfig, resolveProject, saveConfig, cacheHome } from './config.js';
5
+ import { DEFAULT_PACKET, MODEL_NAME, projectConfig, expandHome, loadConfig, resolveProject, saveConfig, cacheHome } from './config.js';
6
6
  import { CacheError, defaultContext, launchOpen, planOpen, runTask, runTasks, status, warm } from './core.js';
7
7
  import { doctor } from './doctor.js';
8
8
  import { agyStatus, UNVERIFIED_MESSAGE } from './engines/agy.js';
@@ -22,6 +22,7 @@ Usage (--project defaults to the current folder):
22
22
  faber-cache open [--project <dir>] [--engine e] [--model m] [--print]
23
23
  faber-cache stats [--project <dir>] [--since YYYY-MM-DD] [--json]
24
24
  faber-cache doctor [--json]
25
+ faber-cache model [<name>] [--project <dir>] [--unset]
25
26
  faber-cache mcp
26
27
 
27
28
  Files live in ${'$'}FABER_CACHE_HOME (default ~/.faber/cache).`;
@@ -36,6 +37,7 @@ const OPTIONS = {
36
37
  'task-file': { type: 'string' },
37
38
  since: { type: 'string' },
38
39
  print: { type: 'boolean' },
40
+ unset: { type: 'boolean' },
39
41
  json: { type: 'boolean' },
40
42
  help: { type: 'boolean', short: 'h' },
41
43
  version: { type: 'boolean', short: 'v' },
@@ -165,6 +167,36 @@ async function main(argv) {
165
167
  console.log(rows.map(formatStatsRow).join('\n\n'));
166
168
  return 0;
167
169
  }
170
+ case 'model': {
171
+ const config = loadConfig();
172
+ const dir = resolveProject(values.project ?? process.cwd());
173
+ const name = positionals[0];
174
+ if (values.unset) {
175
+ if (!values.project)
176
+ throw new CacheError('--unset needs --project <dir>');
177
+ if (name)
178
+ throw new CacheError('--unset takes no model name');
179
+ if (config.projects[dir])
180
+ delete config.projects[dir].model;
181
+ saveConfig(config);
182
+ }
183
+ else if (name) {
184
+ if (!MODEL_NAME.test(name))
185
+ throw new CacheError(`"${name}" is not a model name (letters, digits, . - _ [ ] only)`);
186
+ if (values.project)
187
+ config.projects[dir] = { ...config.projects[dir], model: name };
188
+ else
189
+ config.model = name;
190
+ saveConfig(config);
191
+ }
192
+ const own = projectConfig(config, dir).model;
193
+ console.log(`global: ${config.model}`);
194
+ console.log(`project ${dir}: ${own ?? '(not set)'}`);
195
+ console.log(`in effect: ${own ?? config.model}`);
196
+ if (name || values.unset)
197
+ console.log('Each model has its own base: the first open or run with a new model builds a new base, at full price.');
198
+ return 0;
199
+ }
168
200
  case 'doctor': {
169
201
  const d = doctor(ctx.home);
170
202
  if (values.json) {
@@ -33,6 +33,8 @@ export interface Config {
33
33
  export declare const READ_ONLY = "read-only";
34
34
  export declare const BYPASS_MODE = "bypassPermissions";
35
35
  export declare const BUILTIN_PROFILES: Record<string, Profile>;
36
+ /** A model alias or full ID; nothing a shell or a config reader could misread. */
37
+ export declare const MODEL_NAME: RegExp;
36
38
  export declare const DEFAULTS: Config;
37
39
  /** Default packet: the memory index, the entry file, master PRD and architecture, when present. */
38
40
  export declare const DEFAULT_PACKET: string[];
@@ -8,6 +8,8 @@ export const BUILTIN_PROFILES = {
8
8
  card: { tools: ['Read', 'Glob', 'Grep', 'Edit', 'Write', 'Bash'], permissionMode: 'acceptEdits' },
9
9
  interactive: { tools: null, permissionMode: null },
10
10
  };
11
+ /** A model alias or full ID; nothing a shell or a config reader could misread. */
12
+ export const MODEL_NAME = /^[A-Za-z0-9._\-\[\]]{1,64}$/;
11
13
  export const DEFAULTS = {
12
14
  model: 'sonnet',
13
15
  lifetimeMin: 60,
@@ -13,6 +13,8 @@ export interface Context {
13
13
  now: () => number;
14
14
  runner: (opts: RunOptions) => Promise<EngineRun>;
15
15
  log: (msg: string) => void;
16
+ /** Latest activity of sessions forked from a base outside faber-cache's own runs (open sessions). */
17
+ forkActivity: (entry: BaseEntry) => number | null;
16
18
  }
17
19
  export declare function defaultContext(overrides?: Partial<Context>): Context;
18
20
  export interface TaskRequest {
package/dist/src/core.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import { READ_ONLY, cacheHome, loadConfig, projectConfig, resolveProfile, resolveProject } from './config.js';
3
- import { WARMUP_MESSAGE, claudeBin, claudeVersion, keyBits, modeRefusal, openArgs, runClaude, } from './engines/claude.js';
3
+ import { WARMUP_MESSAGE, claudeBin, claudeVersion, keyBits, modeRefusal, openArgs, lastForkActivity, runClaude, } from './engines/claude.js';
4
4
  import { agyKeyBits, agyVersion, runAgy, UNVERIFIED_MESSAGE } from './engines/agy.js';
5
5
  import { keyOf, keyParts } from './key.js';
6
6
  import { acquire, unlock } from './lock.js';
@@ -11,6 +11,12 @@ import { Registry } from './registry.js';
11
11
  export const ENGINES = ['claude', 'agy', 'codex'];
12
12
  export class CacheError extends Error {
13
13
  }
14
+ function defaultForkActivity(entry) {
15
+ if (entry.engine !== 'claude')
16
+ return null;
17
+ const sessions = [entry.warmSession, entry.baseSession].filter((s) => !!s);
18
+ return lastForkActivity(entry.project, sessions, entry.lastRead);
19
+ }
14
20
  function defaultRunner(opts) {
15
21
  return opts.engine === 'agy' ? runAgy(opts) : runClaude(opts);
16
22
  }
@@ -22,6 +28,7 @@ export function defaultContext(overrides = {}) {
22
28
  now: overrides.now ?? (() => Date.now()),
23
29
  runner: overrides.runner ?? defaultRunner,
24
30
  log: overrides.log ?? ((msg) => process.stderr.write(`faber-cache: ${msg}\n`)),
31
+ forkActivity: overrides.forkActivity ?? defaultForkActivity,
25
32
  };
26
33
  }
27
34
  function checkEngine(engine) {
@@ -108,10 +115,17 @@ export function prepare(ctx, req, defaultMode = 'fixed', defaultProfile) {
108
115
  breakEven: policy.breakEven,
109
116
  };
110
117
  }
118
+ function effectiveLastRead(ctx, entry) {
119
+ return Math.max(entry.lastRead, ctx.forkActivity(entry) ?? 0);
120
+ }
111
121
  export function isFresh(ctx, entry) {
112
122
  if (!entry)
113
123
  return false;
114
- return ctx.now() - entry.lastRead <= (ctx.config.lifetimeMin - ctx.config.marginMin) * 60_000;
124
+ const maxAge = (ctx.config.lifetimeMin - ctx.config.marginMin) * 60_000;
125
+ if (ctx.now() - entry.lastRead <= maxAge)
126
+ return true;
127
+ // An interactive fork reads the base on every request, so its last activity counts as a read.
128
+ return ctx.now() - effectiveLastRead(ctx, entry) <= maxAge;
115
129
  }
116
130
  function prefixOf(u) {
117
131
  return u ? u.input + u.cacheWrite + u.cacheRead : 0;
@@ -451,22 +465,28 @@ export async function launchOpen(ctx, plan) {
451
465
  export function status(ctx, req) {
452
466
  const p = prepare(ctx, req);
453
467
  const bases = new Registry(ctx.home).load().bases;
468
+ const maxAge = (ctx.config.lifetimeMin - ctx.config.marginMin) * 60_000;
454
469
  const rows = Object.values(bases)
455
470
  .filter((e) => e.project === p.projectDir)
456
- .sort((a, b) => b.lastRead - a.lastRead)
457
- .map((e) => ({
458
- key: e.key,
459
- engine: e.engine,
460
- profile: e.profile,
461
- mode: e.mode,
462
- model: e.model,
463
- engineVersion: e.engineVersion,
464
- fresh: isFresh(ctx, e),
465
- uses: e.uses,
466
- lastReadMinAgo: Math.round((ctx.now() - e.lastRead) / 6000) / 10,
467
- warm: e.warmSession !== null,
468
- current: e.key === p.key,
469
- }));
471
+ .map((e) => {
472
+ const lastRead = effectiveLastRead(ctx, e);
473
+ return {
474
+ key: e.key,
475
+ engine: e.engine,
476
+ profile: e.profile,
477
+ mode: e.mode,
478
+ model: e.model,
479
+ engineVersion: e.engineVersion,
480
+ fresh: ctx.now() - lastRead <= maxAge,
481
+ uses: e.uses,
482
+ lastReadMinAgo: Math.round((ctx.now() - lastRead) / 6000) / 10,
483
+ warm: e.warmSession !== null,
484
+ current: e.key === p.key,
485
+ _lastRead: lastRead,
486
+ };
487
+ })
488
+ .sort((a, b) => b._lastRead - a._lastRead)
489
+ .map(({ _lastRead: _, ...row }) => row);
470
490
  return { project: p.projectDir, currentKey: p.key, rows };
471
491
  }
472
492
  /** FR-11.5 / AC-57: three independent single-turn agy runs with the same packet at 0, 1 and 10 min. */
@@ -42,6 +42,13 @@ export declare function currentDepth(): number;
42
42
  export declare function claudeVersion(): string | null;
43
43
  export declare function resetVersionCache(): void;
44
44
  export declare function claudeStatus(): EngineStatus;
45
+ /**
46
+ * The latest activity (ms since epoch) of any Claude Code session forked from one of `sessions`
47
+ * in `projectDir`, or null. Every request of such a session reads the base's prefix and so keeps
48
+ * the engine's cache entry alive, though the registry never sees it. A fork's transcript names its
49
+ * ancestors in a `derived-from` record near the top; the file's mtime is its last request.
50
+ */
51
+ export declare function lastForkActivity(projectDir: string, sessions: string[], since?: number): number | null;
45
52
  /** Whether per-machine sections are moved out of the system prompt (FR-01.3, FR-01.6). */
46
53
  export declare function excludeDynamicOn(): boolean;
47
54
  /** A reason the mode cannot run, or null. */
@@ -53,6 +53,70 @@ export function claudeStatus() {
53
53
  function claudeConfigDir() {
54
54
  return process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude');
55
55
  }
56
+ /**
57
+ * The latest activity (ms since epoch) of any Claude Code session forked from one of `sessions`
58
+ * in `projectDir`, or null. Every request of such a session reads the base's prefix and so keeps
59
+ * the engine's cache entry alive, though the registry never sees it. A fork's transcript names its
60
+ * ancestors in a `derived-from` record near the top; the file's mtime is its last request.
61
+ */
62
+ export function lastForkActivity(projectDir, sessions, since = 0) {
63
+ if (sessions.length === 0)
64
+ return null;
65
+ const dir = path.join(claudeConfigDir(), 'projects', projectDir.replace(/[^a-zA-Z0-9]/g, '-'));
66
+ let names;
67
+ try {
68
+ names = fs.readdirSync(dir).filter((n) => n.endsWith('.jsonl'));
69
+ }
70
+ catch {
71
+ return null;
72
+ }
73
+ let latest = null;
74
+ for (const name of names) {
75
+ const file = path.join(dir, name);
76
+ let mtime;
77
+ try {
78
+ mtime = fs.statSync(file).mtimeMs;
79
+ }
80
+ catch {
81
+ continue;
82
+ }
83
+ if (mtime <= since || (latest !== null && mtime <= latest))
84
+ continue;
85
+ if (derivedFromAny(file, sessions))
86
+ latest = mtime;
87
+ }
88
+ return latest;
89
+ }
90
+ function derivedFromAny(file, sessions) {
91
+ let head;
92
+ try {
93
+ const fd = fs.openSync(file, 'r');
94
+ try {
95
+ const buf = Buffer.alloc(16 * 1024);
96
+ head = buf.toString('utf8', 0, fs.readSync(fd, buf, 0, buf.length, 0));
97
+ }
98
+ finally {
99
+ fs.closeSync(fd);
100
+ }
101
+ }
102
+ catch {
103
+ return false;
104
+ }
105
+ for (const line of head.split('\n')) {
106
+ if (!line.includes('"derived-from"'))
107
+ continue;
108
+ try {
109
+ const rec = JSON.parse(line);
110
+ if (rec.type !== 'derived-from')
111
+ continue;
112
+ return (rec.sessions ?? []).some((s) => s.id !== undefined && sessions.includes(s.id));
113
+ }
114
+ catch {
115
+ continue;
116
+ }
117
+ }
118
+ return false;
119
+ }
56
120
  /** Whether per-machine sections are moved out of the system prompt (FR-01.3, FR-01.6). */
57
121
  export function excludeDynamicOn() {
58
122
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabersep/cache",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "private": false,
5
5
  "description": "Pay for your project's context once, not once per Claude Code session: a warm base session and a fork per task.",
6
6
  "license": "Apache-2.0",
@@ -12,7 +12,14 @@
12
12
  "bugs": {
13
13
  "url": "https://github.com/fabersep/cache/issues"
14
14
  },
15
- "keywords": ["fabersep", "ai-agents", "prompt-caching", "claude-code", "mcp", "fork"],
15
+ "keywords": [
16
+ "fabersep",
17
+ "ai-agents",
18
+ "prompt-caching",
19
+ "claude-code",
20
+ "mcp",
21
+ "fork"
22
+ ],
16
23
  "type": "module",
17
24
  "bin": {
18
25
  "faber-cache": "dist/src/cli.js"
@@ -20,7 +27,13 @@
20
27
  "exports": {
21
28
  ".": "./dist/src/index.js"
22
29
  },
23
- "files": ["dist/src", "data", "LICENSE", "README.md"],
30
+ "files": [
31
+ "dist/src",
32
+ "data",
33
+ "LICENSE",
34
+ "README.md",
35
+ "CHANGELOG.md"
36
+ ],
24
37
  "engines": {
25
38
  "node": ">=20"
26
39
  },