@fabersep/cache 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,164 @@
1
- # Temporary Holding Version
1
+ # FaberSEP Cache
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Pay for your project's context once, not once per Claude Code session.**
4
+
5
+ ```
6
+ Without FaberSEP Cache: every session sends the project context again
7
+
8
+ session 1 [ system ][ project context ][ task 1 ]
9
+ session 2 [ system ][ project context ][ task 2 ]
10
+ session 3 [ system ][ project context ][ task 3 ]
11
+ cached written to cache again,
12
+ (cheap) every session (2x the input price)
13
+
14
+ With FaberSEP Cache: one base session holds the context, every task forks it
15
+
16
+ base [ system ][ project context ] written once an hour
17
+ ├── fork ──> [ task 1 ]
18
+ ├── fork ──> [ task 2 ]
19
+ └── fork ──> [ task 3 ]
20
+ every fork reads the context from cache (0.1x the input price)
21
+ ```
22
+
23
+ Your project context is the files Claude should know before it starts: `AGENTS.md`, `CLAUDE.md`, the PRD, the architecture notes. FaberSEP Cache sends them once into a **base session**. Every task, or every new interactive session, then starts as a **fork** of the base: a new session that begins with the base's history. Claude Code's prompt cache already holds that history, so the fork reads it at a tenth of the input price instead of writing it again at twice the price.
24
+
25
+ In our benchmark the same six tasks cost **63 to 72% less** than six fresh sessions with the same context ([bench/](bench/README.md)).
26
+
27
+ Works with **Claude Code**. Antigravity (`agy`) runs work but save nothing: agy cannot fork a session, and separate agy conversations do not share a cache ([why](docs/research/2026-11-28-engine-cache-facts.md)). Codex is planned.
28
+
29
+ ## Install
30
+
31
+ Needs Node 20+ and Claude Code, logged in.
32
+
33
+ ```bash
34
+ npm install -g @fabersep/cache
35
+ ```
36
+
37
+ Run every command from your project's folder (or point at it with `--project <dir>`). There is no setup step: the first command finds the context files by itself. `faber-cache init` is optional. It only shows which files it found and saves the list, so you can edit it in `~/.faber/cache/config.json`. Context files are scanned for secrets and machine paths before anything is sent.
38
+
39
+ ## 1. Start an interactive session from the warm base
40
+
41
+ This is the everyday use: you open Claude Code to work on a project several times a day.
42
+
43
+ ```bash
44
+ cd my-project
45
+ faber-cache open
46
+ ```
47
+
48
+ `open` builds the base if there is none from the last hour, then starts a normal interactive Claude Code session in your terminal, forked from it. The session starts already knowing your project files, with your own settings, hooks, skills and MCP servers. Measured: the first request of an interactive fork read 100% of the base from cache (research §1d).
49
+
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
+
52
+ Two things to know:
53
+
54
+ - 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.
55
+ - It uses Claude Code's own system prompt, so it needs `"excludeDynamicSystemPromptSections": true` in `~/.claude/settings.json`. Without it the folder, date and git status sit at the top of the prompt and no fork can match the base. `faber-cache doctor` tells you whether it is on.
56
+
57
+ ## 2. Run a task list from one base
58
+
59
+ The best case: many tasks on the same project, each starting from the same context.
60
+
61
+ ```bash
62
+ faber-cache run --tasks tasks.txt
63
+ ```
64
+
65
+ `tasks.txt` has one task per line. A task can span several lines if you separate tasks with a line of `---`, and a JSON array of strings also works. FaberSEP Cache builds one base, forks it for every task (four at a time) and prints each reply:
66
+
67
+ ```
68
+ ### In one sentence, what does the registry hold?
69
+ The registry (`registry.json`) holds, for each base key, the base and warm session IDs, ...
70
+ faber-cache: with-base, fixed/read-only, first request 11947 read, 998 written, read share 94.8%
71
+ ```
72
+
73
+ "11947 read" means 11,947 tokens came from cache at a tenth of the price. "998 written" is the task's own new text.
74
+
75
+ Each task is one headless Claude Code run (`claude -p`). It works until the task is done, using as many turns and tool calls as it needs, prints the answer and exits. A single task works the same way: `faber-cache run "Summarize the open questions in the PRD"`.
76
+
77
+ Tasks are **read-only** by default (`Read`, `Glob`, `Grep`): good for reviews, questions, checks and test prompts. For tasks that change files, use the `card` profile (`--profile card`: adds `Edit`, `Write` and `Bash`). Set `limits.parallel` to `1` in the config so two tasks never edit the same checkout at once.
78
+
79
+ ## 3. Let an agent fork the base (MCP)
80
+
81
+ Add FaberSEP Cache to Claude Code once:
82
+
83
+ ```bash
84
+ claude mcp add faber-cache -- faber-cache mcp
85
+ ```
86
+
87
+ Now any Claude Code session can hand work to forks of the base. Ask it in plain words, for example: *"Use faber-cache to check each of these five acceptance criteria against the code, in parallel."* The agent calls `cache_run` with the five tasks. Each one runs as a read-only fork that starts with the project context already loaded, and the replies come back to the session.
88
+
89
+ It works like a subagent that already knows the project, at cache-read prices. The tools:
90
+
91
+ | Tool | What it does |
92
+ |---|---|
93
+ | `cache_status` | Whether a warm base exists for the project |
94
+ | `cache_warm` | Build the base now, so the next forks are cheap |
95
+ | `cache_run` | Run up to 5 tasks as read-only forks and return the replies (at most 20 turns per task, 10 minutes per call) |
96
+ | `cache_open_command` | The command that opens an interactive fork in a terminal |
97
+
98
+ MCP forks are always read-only and cannot start further forks.
99
+
100
+ ## 4. Use it in your own scripts and skills
101
+
102
+ Anything that starts `claude -p` several times on the same project can start from the base instead. `--json` returns each task's reply and its record, including the fork's session ID:
103
+
104
+ ```bash
105
+ faber-cache run --json "Round 1: review the PRD in docs/features/01/prd.md"
106
+ # -> [{ "reply": "...", "record": { "session": "<id>", "readShare": 0.97, ... } }]
107
+ ```
108
+
109
+ A multi-round loop (a review discussion between two agents, for example) starts its first round as a fork and continues the same session with Claude Code's own resume:
110
+
111
+ ```bash
112
+ claude -p --resume <id> "Round 2: here are my answers to your findings ..."
113
+ ```
114
+
115
+ Later rounds of one session are already cached by Claude Code, so the saving is in the first round. It grows when you start several discussions or reviewers on the same project in the same hour, because they all fork one base. This only helps a Claude Code reviewer: an Antigravity reviewer cannot fork the base.
116
+
117
+ ## See what you saved
118
+
119
+ ```bash
120
+ faber-cache stats
121
+ ```
122
+
123
+ ```
124
+ ~/my-project (claude, fixed mode, read-only profile)
125
+ runs: 6, 6 of them started from the warm base; 1 base build, 0 warm-ups
126
+ cache: on average a run read 97% of its project context from cache
127
+ saved: at least $0.0071 (51%) against sending the context fresh to every run; paid $0.0067
128
+ ```
129
+
130
+ The saving shown is a floor. It prices the cached context as if a fresh session had sent it at the plain input price. A fresh Claude Code session actually writes it to cache at twice that price, so the real saving is larger: these same six runs saved 70% when measured directly.
131
+
132
+ If a run reads less than expected, `faber-cache doctor` says why (a changed tool set, model or Claude Code version, for example).
133
+
134
+ ## When it does not help
135
+
136
+ - **One task, once.** Building the base costs about one normal run, so a single task costs a little more (10 to 60% more in our runs). From the second task in the same hour it is cheaper.
137
+ - **Tiny context.** With a few hundred tokens of project files there is little to save.
138
+ - **More than an hour apart.** The cache lives one hour. A base older than about 55 minutes is rebuilt.
139
+
140
+ ## How it works
141
+
142
+ 1. **Base.** The context files go into one headless session. Claude Code caches its prompt for one hour.
143
+ 2. **Fork.** Each task resumes the base as a new session (`claude --resume <base> --fork-session`). Its first request starts with exactly the base's prompt, so the context is read from cache.
144
+ 3. **Key.** A base is reused only while nothing that changes the prompt has changed: the context files, model, tools, profile, mode or Claude Code version. Change a file and the next task builds a new base.
145
+ 4. **Warm-up.** In `default` mode the base is forked once with a short message before tasks fork that warm-up. Forks of the base itself would read only about 70% of it.
146
+
147
+ | Mode | System prompt | Used by |
148
+ |---|---|---|
149
+ | `fixed` | a short fixed prompt, no user settings | `run` (default), MCP |
150
+ | `default` | Claude Code's own prompt and your settings | `open` (default). Use it with `run --mode default` when tasks need your hooks, MCP servers or skills |
151
+
152
+ Details: [architecture](docs/architecture.md), [spec](docs/features/01-shared-base-sessions/prd.md).
153
+
154
+ ## Files
155
+
156
+ Everything lives in `~/.faber/cache` (or `$FABER_CACHE_HOME`): `config.json`, `registry.json`, `locks/`, `records/`. Nothing is written inside your project, and engine sessions are never deleted.
157
+
158
+ ## Status
159
+
160
+ v0.1, measured on Claude Code 2.1.330: headless forks and interactive forks within a few minutes of the build. Still to measure: forks 10 and 55 minutes after the build, and the cache's expiry. `faber-cache doctor` shows what is measured for your Claude Code version.
161
+
162
+ ## License
163
+
164
+ Apache-2.0
@@ -0,0 +1,94 @@
1
+ {
2
+ "claude": {
3
+ "fixed": {
4
+ "engineVersion": "2.1.330",
5
+ "date": "2026-11-28",
6
+ "model": "haiku",
7
+ "tools": "Read,Glob,Grep",
8
+ "complete": false,
9
+ "needsWarmup": false,
10
+ "build": {
11
+ "input": 0,
12
+ "cacheWrite": 13519,
13
+ "cacheRead": 0
14
+ },
15
+ "warmup": null,
16
+ "fork": {
17
+ "cacheRead": 12870,
18
+ "tailWrite": 650
19
+ },
20
+ "readShare": 0.952,
21
+ "note": "direct forks only, at about 1 minute; the 10 and 55 minute forks and the expiry check (FR-11.2) are still to run"
22
+ },
23
+ "default": {
24
+ "engineVersion": "2.1.330",
25
+ "date": "2026-11-28",
26
+ "model": "haiku",
27
+ "tools": "all",
28
+ "complete": false,
29
+ "needsWarmup": true,
30
+ "build": {
31
+ "input": 0,
32
+ "cacheWrite": 22082,
33
+ "cacheRead": 18681
34
+ },
35
+ "warmup": {
36
+ "input": 0,
37
+ "cacheWrite": 12578,
38
+ "cacheRead": 28543
39
+ },
40
+ "fork": {
41
+ "cacheRead": 40782,
42
+ "tailWrite": 0
43
+ },
44
+ "readShare": 0.98,
45
+ "note": "forks of the warm-up read 98%; the timed forks and the expiry check (FR-11.2) are still to run"
46
+ },
47
+ "open": {
48
+ "engineVersion": "2.1.330",
49
+ "date": "2026-11-29",
50
+ "model": "haiku",
51
+ "tools": "all",
52
+ "complete": false,
53
+ "needsWarmup": true,
54
+ "build": {
55
+ "input": 2,
56
+ "cacheWrite": 34074,
57
+ "cacheRead": 18681
58
+ },
59
+ "warmup": {
60
+ "input": 2,
61
+ "cacheWrite": 411,
62
+ "cacheRead": 52755
63
+ },
64
+ "fork": {
65
+ "cacheRead": 53166,
66
+ "tailWrite": 0
67
+ },
68
+ "readShare": 1.0,
69
+ "note": "interactive fork of the warm-up read 100% of its prefix and added about 5K of its own (OQ-04); the timed forks and the expiry check (FR-11.2) are still to run"
70
+ }
71
+ },
72
+ "agy": {
73
+ "prefix": {
74
+ "engineVersion": "1.5.20",
75
+ "date": "2026-11-29",
76
+ "model": "gemini-4-hydrogen-medium",
77
+ "tools": "read-only",
78
+ "complete": true,
79
+ "needsWarmup": false,
80
+ "build": {
81
+ "input": 32519,
82
+ "cacheWrite": 0,
83
+ "cacheRead": 0
84
+ },
85
+ "warmup": null,
86
+ "fork": {
87
+ "cacheRead": 0,
88
+ "tailWrite": 0
89
+ },
90
+ "readShare": 0,
91
+ "note": "no cache guarantee: three independent single-turn runs at 0, 1 and 10 minutes each read 0% from cache on turn 1 (OQ-02)"
92
+ }
93
+ }
94
+ }
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ /** A task file: a JSON array, or tasks separated by lines of `---`, else one task per line. */
3
+ export declare function parseTasks(content: string, file: string): string[];
@@ -0,0 +1,197 @@
1
+ #!/usr/bin/env node
2
+ import * as fs from 'node:fs';
3
+ import * as path from 'node:path';
4
+ import { parseArgs } from 'node:util';
5
+ import { DEFAULT_PACKET, expandHome, loadConfig, resolveProject, saveConfig, cacheHome } from './config.js';
6
+ import { CacheError, defaultContext, launchOpen, planOpen, runTask, runTasks, status, warm } from './core.js';
7
+ import { doctor } from './doctor.js';
8
+ import { agyStatus, UNVERIFIED_MESSAGE } from './engines/agy.js';
9
+ import { claudeStatus } from './engines/claude.js';
10
+ import { serveStdio } from './mcp.js';
11
+ import { PacketError } from './packet.js';
12
+ import { computeStats, formatStatsRow } from './stats.js';
13
+ import { getPackageVersion } from './version.js';
14
+ const HELP = `faber-cache ${getPackageVersion()}: start every agent task from a warm prompt cache
15
+
16
+ Usage (--project defaults to the current folder):
17
+ faber-cache init [--project <dir>]
18
+ faber-cache status [--project <dir>] [--profile p] [--mode fixed|default|prefix] [--engine claude|agy] [--json]
19
+ faber-cache warm [--project <dir>] [--profile p] [--mode fixed|default] [--model m]
20
+ faber-cache run [--project <dir>] [--profile p] [--mode fixed|default|prefix] [--engine claude|agy] [--model m]
21
+ [--uses n] [--json] ("<task>" | --task-file f | --tasks f)
22
+ faber-cache open [--project <dir>] [--engine e] [--model m] [--print]
23
+ faber-cache stats [--project <dir>] [--since YYYY-MM-DD] [--json]
24
+ faber-cache doctor [--json]
25
+ faber-cache mcp
26
+
27
+ Files live in ${'$'}FABER_CACHE_HOME (default ~/.faber/cache).`;
28
+ const OPTIONS = {
29
+ project: { type: 'string' },
30
+ profile: { type: 'string' },
31
+ mode: { type: 'string' },
32
+ engine: { type: 'string' },
33
+ model: { type: 'string' },
34
+ uses: { type: 'string' },
35
+ tasks: { type: 'string' },
36
+ 'task-file': { type: 'string' },
37
+ since: { type: 'string' },
38
+ print: { type: 'boolean' },
39
+ json: { type: 'boolean' },
40
+ help: { type: 'boolean', short: 'h' },
41
+ version: { type: 'boolean', short: 'v' },
42
+ };
43
+ /** A task file: a JSON array, or tasks separated by lines of `---`, else one task per line. */
44
+ export function parseTasks(content, file) {
45
+ if (file.endsWith('.json')) {
46
+ const raw = JSON.parse(content);
47
+ if (!Array.isArray(raw))
48
+ throw new CacheError(`${file}: expected a JSON array of task strings`);
49
+ return raw.map(String).filter((t) => t.trim());
50
+ }
51
+ if (/^---\s*$/m.test(content))
52
+ return content.split(/^---\s*$/m).map((t) => t.trim()).filter(Boolean);
53
+ return content.split('\n').map((t) => t.trim()).filter(Boolean);
54
+ }
55
+ function pct(x) {
56
+ return x === null ? '-' : `${Math.round(x * 1000) / 10}%`;
57
+ }
58
+ function summary(r) {
59
+ const rec = r.record;
60
+ const read = rec.first ? `${rec.first.cacheRead} read, ${rec.first.cacheWrite} written` : 'no usage';
61
+ const miss = rec.cacheMiss ? ', CACHE MISS' : '';
62
+ const unverified = rec.unverified ? `, ${rec.note ?? UNVERIFIED_MESSAGE}` : '';
63
+ return `${rec.base}, ${rec.mode}/${rec.profile}, first request ${read}, read share ${pct(rec.readShare)}${miss}${unverified}`;
64
+ }
65
+ async function main(argv) {
66
+ const [cmd, ...rest] = argv;
67
+ if (!cmd || cmd === '--help' || cmd === '-h' || cmd === 'help') {
68
+ console.log(HELP);
69
+ return 0;
70
+ }
71
+ if (cmd === '--version' || cmd === '-v') {
72
+ console.log(getPackageVersion());
73
+ return 0;
74
+ }
75
+ if (cmd === 'mcp') {
76
+ serveStdio();
77
+ return -1;
78
+ }
79
+ const { values, positionals } = parseArgs({ args: rest, options: OPTIONS, allowPositionals: true });
80
+ const ctx = defaultContext();
81
+ const req = {
82
+ project: values.project ?? process.cwd(),
83
+ profile: values.profile,
84
+ mode: values.mode,
85
+ engine: values.engine,
86
+ model: values.model,
87
+ uses: values.uses !== undefined ? Number(values.uses) : undefined,
88
+ };
89
+ if (req.uses !== undefined && (!Number.isInteger(req.uses) || req.uses < 1))
90
+ throw new CacheError('--uses must be a whole number of at least 1');
91
+ switch (cmd) {
92
+ case 'init': {
93
+ const config = loadConfig();
94
+ for (const st of [claudeStatus(), agyStatus()]) {
95
+ console.log(`${st.engine}: ${st.installed ? `${st.version}, ${st.message}` : st.message}`);
96
+ }
97
+ const dir = resolveProject(req.project);
98
+ const packet = DEFAULT_PACKET.filter((f) => fs.existsSync(path.resolve(dir, expandHome(f))));
99
+ config.projects[dir] = { ...config.projects[dir], packet: config.projects[dir]?.packet ?? packet };
100
+ console.log(`project ${dir}: packet ${config.projects[dir].packet?.join(', ') || '(none found)'}`);
101
+ saveConfig(config);
102
+ console.log(`config written: ${path.join(cacheHome(), 'config.json')}`);
103
+ return 0;
104
+ }
105
+ case 'status': {
106
+ const s = status(ctx, req);
107
+ if (values.json) {
108
+ console.log(JSON.stringify(s, null, 2));
109
+ return 0;
110
+ }
111
+ console.log(`${s.project}\ncurrent key: ${s.currentKey}`);
112
+ if (!s.rows.length)
113
+ console.log('no bases');
114
+ for (const r of s.rows) {
115
+ console.log(`${r.current ? '*' : ' '} ${r.key} ${r.mode}/${r.profile} ${r.model} ${r.engine} ${r.engineVersion} ${r.fresh ? 'fresh' : 'expired'} uses ${r.uses} read ${r.lastReadMinAgo} min ago${r.warm ? ' warm' : ''}`);
116
+ }
117
+ return 0;
118
+ }
119
+ case 'warm': {
120
+ const e = await warm(ctx, req);
121
+ console.log(`base ${e.baseSession}${e.warmSession ? `, warm ${e.warmSession}` : ''} (${e.mode}/${e.profile}, key ${e.key})`);
122
+ return 0;
123
+ }
124
+ case 'run': {
125
+ let results;
126
+ if (values.tasks) {
127
+ const file = values.tasks;
128
+ results = await runTasks(ctx, req, parseTasks(fs.readFileSync(file, 'utf8'), file));
129
+ }
130
+ else {
131
+ const task = values['task-file'] ? fs.readFileSync(values['task-file'], 'utf8') : positionals.join(' ');
132
+ if (!task.trim())
133
+ throw new CacheError('give a task: "<task>", --task-file or --tasks');
134
+ results = [await runTask(ctx, req, task)];
135
+ }
136
+ if (values.json) {
137
+ console.log(JSON.stringify(results.map((r) => ({ task: r.task, ok: r.ok, reply: r.reply, error: r.error, record: r.record })), null, 2));
138
+ }
139
+ else {
140
+ for (const r of results) {
141
+ if (results.length > 1)
142
+ console.log(`### ${r.task.split('\n')[0].slice(0, 80)}`);
143
+ console.log(r.ok ? r.reply : `error: ${r.error}`);
144
+ process.stderr.write(`faber-cache: ${summary(r)}\n`);
145
+ }
146
+ }
147
+ return results.every((r) => r.ok) ? 0 : 1;
148
+ }
149
+ case 'open': {
150
+ const plan = await planOpen(ctx, req);
151
+ if (values.print) {
152
+ console.log(plan.command);
153
+ return 0;
154
+ }
155
+ return launchOpen(ctx, plan);
156
+ }
157
+ case 'stats': {
158
+ const rows = computeStats(ctx.home, { project: values.project, since: values.since });
159
+ if (values.json) {
160
+ console.log(JSON.stringify(rows, null, 2));
161
+ return 0;
162
+ }
163
+ if (!rows.length)
164
+ console.log('no records');
165
+ console.log(rows.map(formatStatsRow).join('\n\n'));
166
+ return 0;
167
+ }
168
+ case 'doctor': {
169
+ const d = doctor(ctx.home);
170
+ if (values.json) {
171
+ console.log(JSON.stringify(d, null, 2));
172
+ return 0;
173
+ }
174
+ for (const e of d.engines)
175
+ console.log(`${e.engine}: ${e.installed ? e.version : 'not installed'}${e.installed ? `, ${e.message}` : ''}`);
176
+ console.log(`excludeDynamicSystemPromptSections: ${d.settings.excludeDynamicSystemPromptSections ? 'on' : 'off (default-prompt mode refused)'}`);
177
+ for (const m of d.modes) {
178
+ const flags = m.needsWarmup === null ? '' : `, needs warm-up: ${m.needsWarmup ? 'yes' : 'no'}, break-even: ${m.breakEven}`;
179
+ console.log(`mode ${m.engine}/${m.mode}: ${m.state}${flags}${m.measuredOn ? ` (${m.measuredOn})` : ''}; ${m.note}`);
180
+ }
181
+ for (const miss of d.misses)
182
+ console.log(`cache miss ${miss.at} ${miss.key} read ${pct(miss.readShare)}: ${miss.differs.join('; ')}`);
183
+ return 0;
184
+ }
185
+ default:
186
+ console.error(`unknown command "${cmd}"\n\n${HELP}`);
187
+ return 2;
188
+ }
189
+ }
190
+ main(process.argv.slice(2)).then((code) => {
191
+ if (code >= 0)
192
+ process.exitCode = code;
193
+ }, (err) => {
194
+ const known = err instanceof CacheError || err instanceof PacketError;
195
+ console.error(`faber-cache: ${known ? err.message : err.stack ?? String(err)}`);
196
+ process.exitCode = 1;
197
+ });