@fabersep/cache 0.0.0-stage → 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 +15 -0
- package/LICENSE +202 -0
- package/README.md +182 -2
- package/data/measured-modes.json +94 -0
- package/dist/src/cli.d.ts +3 -0
- package/dist/src/cli.js +229 -0
- package/dist/src/config.d.ts +56 -0
- package/dist/src/config.js +92 -0
- package/dist/src/core.d.ts +122 -0
- package/dist/src/core.js +538 -0
- package/dist/src/cost.d.ts +25 -0
- package/dist/src/cost.js +39 -0
- package/dist/src/doctor.d.ts +26 -0
- package/dist/src/doctor.js +84 -0
- package/dist/src/engines/agy.d.ts +17 -0
- package/dist/src/engines/agy.js +175 -0
- package/dist/src/engines/claude.d.ts +67 -0
- package/dist/src/engines/claude.js +275 -0
- package/dist/src/hygiene.d.ts +8 -0
- package/dist/src/hygiene.js +84 -0
- package/dist/src/index.d.ts +11 -0
- package/dist/src/index.js +8 -0
- package/dist/src/key.d.ts +16 -0
- package/dist/src/key.js +7 -0
- package/dist/src/lock.d.ts +9 -0
- package/dist/src/lock.js +92 -0
- package/dist/src/mcp.d.ts +126 -0
- package/dist/src/mcp.js +194 -0
- package/dist/src/measured.d.ts +48 -0
- package/dist/src/measured.js +50 -0
- package/dist/src/packet.d.ts +29 -0
- package/dist/src/packet.js +64 -0
- package/dist/src/records.d.ts +49 -0
- package/dist/src/records.js +35 -0
- package/dist/src/registry.d.ts +42 -0
- package/dist/src/registry.js +69 -0
- package/dist/src/stats.d.ts +31 -0
- package/dist/src/stats.js +91 -0
- package/dist/src/version.d.ts +2 -0
- package/dist/src/version.js +22 -0
- package/package.json +51 -4
package/dist/src/core.js
ADDED
|
@@ -0,0 +1,538 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { READ_ONLY, cacheHome, loadConfig, projectConfig, resolveProfile, resolveProject } from './config.js';
|
|
3
|
+
import { WARMUP_MESSAGE, claudeBin, claudeVersion, keyBits, modeRefusal, openArgs, lastForkActivity, runClaude, } from './engines/claude.js';
|
|
4
|
+
import { agyKeyBits, agyVersion, runAgy, UNVERIFIED_MESSAGE } from './engines/agy.js';
|
|
5
|
+
import { keyOf, keyParts } from './key.js';
|
|
6
|
+
import { acquire, unlock } from './lock.js';
|
|
7
|
+
import { isModeVerified, modePolicy } from './measured.js';
|
|
8
|
+
import { baseMessage, buildPacket, packetInFront } from './packet.js';
|
|
9
|
+
import { appendRecord } from './records.js';
|
|
10
|
+
import { Registry } from './registry.js';
|
|
11
|
+
export const ENGINES = ['claude', 'agy', 'codex'];
|
|
12
|
+
export class CacheError extends Error {
|
|
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
|
+
}
|
|
20
|
+
function defaultRunner(opts) {
|
|
21
|
+
return opts.engine === 'agy' ? runAgy(opts) : runClaude(opts);
|
|
22
|
+
}
|
|
23
|
+
export function defaultContext(overrides = {}) {
|
|
24
|
+
const home = overrides.home ?? cacheHome();
|
|
25
|
+
return {
|
|
26
|
+
home,
|
|
27
|
+
config: overrides.config ?? loadConfig(home),
|
|
28
|
+
now: overrides.now ?? (() => Date.now()),
|
|
29
|
+
runner: overrides.runner ?? defaultRunner,
|
|
30
|
+
log: overrides.log ?? ((msg) => process.stderr.write(`faber-cache: ${msg}\n`)),
|
|
31
|
+
forkActivity: overrides.forkActivity ?? defaultForkActivity,
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
function checkEngine(engine) {
|
|
35
|
+
const e = (engine ?? 'claude');
|
|
36
|
+
if (!ENGINES.includes(e))
|
|
37
|
+
throw new CacheError(`unknown engine "${engine}"; known: ${ENGINES.join(', ')}`);
|
|
38
|
+
if (e === 'codex') {
|
|
39
|
+
throw new CacheError('the codex adapter is not built yet (planned for a later release, unverified until measured); use --engine claude or --engine agy');
|
|
40
|
+
}
|
|
41
|
+
return e;
|
|
42
|
+
}
|
|
43
|
+
/** Packet, key and policy for a request; refuses before any engine starts (FR-01.5, FR-01.6). */
|
|
44
|
+
export function prepare(ctx, req, defaultMode = 'fixed', defaultProfile) {
|
|
45
|
+
const projectDir = resolveProject(req.project);
|
|
46
|
+
const engine = checkEngine(req.engine);
|
|
47
|
+
const { name: profileName, profile } = resolveProfile(ctx.config, projectDir, req.profile ?? defaultProfile, req.forceReadOnly);
|
|
48
|
+
const packet = buildPacket(ctx.config, projectDir);
|
|
49
|
+
if (engine === 'agy') {
|
|
50
|
+
const mode = req.mode ?? 'prefix';
|
|
51
|
+
if (mode !== 'prefix')
|
|
52
|
+
throw new CacheError(`unknown mode "${mode}" for agy; agy only supports prefix mode`);
|
|
53
|
+
const engineVersion = agyVersion();
|
|
54
|
+
if (!engineVersion)
|
|
55
|
+
throw new CacheError('Antigravity CLI is not installed or not on PATH (`agy --version` failed)');
|
|
56
|
+
const model = req.model ?? 'default';
|
|
57
|
+
const kp = {
|
|
58
|
+
engine,
|
|
59
|
+
engineVersion,
|
|
60
|
+
model,
|
|
61
|
+
mode,
|
|
62
|
+
profile: profileName,
|
|
63
|
+
tools: profile.tools,
|
|
64
|
+
permissionMode: profile.permissionMode,
|
|
65
|
+
...agyKeyBits(),
|
|
66
|
+
};
|
|
67
|
+
return {
|
|
68
|
+
projectDir,
|
|
69
|
+
engine,
|
|
70
|
+
engineVersion,
|
|
71
|
+
mode,
|
|
72
|
+
profileName,
|
|
73
|
+
profile,
|
|
74
|
+
model,
|
|
75
|
+
packet,
|
|
76
|
+
key: keyOf(kp, packet),
|
|
77
|
+
parts: keyParts(kp, packet),
|
|
78
|
+
needsWarmup: false,
|
|
79
|
+
breakEven: 1,
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
const mode = req.mode ?? defaultMode;
|
|
83
|
+
if (mode !== 'fixed' && mode !== 'default')
|
|
84
|
+
throw new CacheError(`unknown mode "${mode}"; use fixed or default`);
|
|
85
|
+
const refusal = modeRefusal(mode);
|
|
86
|
+
if (refusal)
|
|
87
|
+
throw new CacheError(refusal);
|
|
88
|
+
const model = req.model ?? projectConfig(ctx.config, projectDir).model ?? ctx.config.model;
|
|
89
|
+
const engineVersion = claudeVersion();
|
|
90
|
+
if (!engineVersion)
|
|
91
|
+
throw new CacheError('Claude Code is not installed or not on PATH (`claude --version` failed)');
|
|
92
|
+
const kp = {
|
|
93
|
+
engine,
|
|
94
|
+
engineVersion,
|
|
95
|
+
model,
|
|
96
|
+
mode,
|
|
97
|
+
profile: profileName,
|
|
98
|
+
tools: profile.tools,
|
|
99
|
+
permissionMode: profile.permissionMode,
|
|
100
|
+
...keyBits(mode),
|
|
101
|
+
};
|
|
102
|
+
const policy = modePolicy(engine, mode);
|
|
103
|
+
return {
|
|
104
|
+
projectDir,
|
|
105
|
+
engine,
|
|
106
|
+
engineVersion,
|
|
107
|
+
mode,
|
|
108
|
+
profileName,
|
|
109
|
+
profile,
|
|
110
|
+
model,
|
|
111
|
+
packet,
|
|
112
|
+
key: keyOf(kp, packet),
|
|
113
|
+
parts: keyParts(kp, packet),
|
|
114
|
+
needsWarmup: policy.needsWarmup,
|
|
115
|
+
breakEven: policy.breakEven,
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
function effectiveLastRead(ctx, entry) {
|
|
119
|
+
return Math.max(entry.lastRead, ctx.forkActivity(entry) ?? 0);
|
|
120
|
+
}
|
|
121
|
+
export function isFresh(ctx, entry) {
|
|
122
|
+
if (!entry)
|
|
123
|
+
return false;
|
|
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;
|
|
129
|
+
}
|
|
130
|
+
function prefixOf(u) {
|
|
131
|
+
return u ? u.input + u.cacheWrite + u.cacheRead : 0;
|
|
132
|
+
}
|
|
133
|
+
function record(ctx, p, fields) {
|
|
134
|
+
const rec = {
|
|
135
|
+
at: new Date(ctx.now()).toISOString(),
|
|
136
|
+
project: p.projectDir,
|
|
137
|
+
profile: p.profileName,
|
|
138
|
+
mode: p.mode,
|
|
139
|
+
engine: p.engine,
|
|
140
|
+
engineVersion: p.engineVersion,
|
|
141
|
+
model: p.model,
|
|
142
|
+
tools: p.profile.tools ? p.profile.tools.join(',') : 'all',
|
|
143
|
+
key: p.key,
|
|
144
|
+
fromSession: null,
|
|
145
|
+
session: null,
|
|
146
|
+
first: null,
|
|
147
|
+
total: null,
|
|
148
|
+
refPrefix: null,
|
|
149
|
+
readShare: null,
|
|
150
|
+
ownTokens: null,
|
|
151
|
+
cacheMiss: false,
|
|
152
|
+
...fields,
|
|
153
|
+
};
|
|
154
|
+
appendRecord(ctx.home, rec);
|
|
155
|
+
return rec;
|
|
156
|
+
}
|
|
157
|
+
/** Build (and warm) a key's base under its lock, or return the fresh one (FR-02, FR-03). */
|
|
158
|
+
async function ensureBase(ctx, p, req, force = false) {
|
|
159
|
+
const reg = new Registry(ctx.home);
|
|
160
|
+
const lockFile = reg.keyLock(p.key);
|
|
161
|
+
if (!(await acquire(lockFile, ctx.config.limits.lockWaitSec * 1000))) {
|
|
162
|
+
ctx.log(`lock wait for ${p.key} timed out; running with no base`);
|
|
163
|
+
return { fallback: 'lock-timeout' };
|
|
164
|
+
}
|
|
165
|
+
try {
|
|
166
|
+
const existing = reg.get(p.key);
|
|
167
|
+
if (!force && isFresh(ctx, existing))
|
|
168
|
+
return { entry: existing };
|
|
169
|
+
const common = { engine: p.engine, mode: p.mode, profile: p.profile, model: p.model, cwd: p.projectDir, signal: req.signal, onSpawn: req.onSpawn };
|
|
170
|
+
const built = await ctx.runner({ ...common, stdin: baseMessage(p.packet) });
|
|
171
|
+
record(ctx, p, {
|
|
172
|
+
kind: 'build',
|
|
173
|
+
base: 'with-base',
|
|
174
|
+
session: built.session,
|
|
175
|
+
first: built.first,
|
|
176
|
+
total: built.total,
|
|
177
|
+
costUsd: built.costUsd ?? null,
|
|
178
|
+
refPrefix: prefixOf(built.first),
|
|
179
|
+
outcome: built.ok ? 'ok' : built.stopped ? 'stopped' : 'error',
|
|
180
|
+
error: built.error,
|
|
181
|
+
});
|
|
182
|
+
if (!built.ok || !built.session)
|
|
183
|
+
throw new CacheError(`building the base failed: ${built.error ?? 'no session id'}`);
|
|
184
|
+
let warm = null;
|
|
185
|
+
let refPrefix = prefixOf(built.first);
|
|
186
|
+
if (p.needsWarmup) {
|
|
187
|
+
for (let attempt = 1; attempt <= 2 && !warm; attempt++) {
|
|
188
|
+
const w = await ctx.runner({ ...common, stdin: WARMUP_MESSAGE, resume: built.session });
|
|
189
|
+
record(ctx, p, {
|
|
190
|
+
kind: 'warmup',
|
|
191
|
+
base: 'with-base',
|
|
192
|
+
fromSession: built.session,
|
|
193
|
+
session: w.session,
|
|
194
|
+
first: w.first,
|
|
195
|
+
total: w.total,
|
|
196
|
+
refPrefix: prefixOf(w.first),
|
|
197
|
+
outcome: w.ok ? 'ok' : w.stopped ? 'stopped' : 'error',
|
|
198
|
+
error: w.error,
|
|
199
|
+
attempt,
|
|
200
|
+
});
|
|
201
|
+
if (w.ok && w.session) {
|
|
202
|
+
warm = w.session;
|
|
203
|
+
refPrefix = prefixOf(w.first);
|
|
204
|
+
}
|
|
205
|
+
else if (w.stopped) {
|
|
206
|
+
break;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
if (!warm) {
|
|
210
|
+
ctx.log(`warm-up failed twice on base ${built.session}; nothing registered, running with no base`);
|
|
211
|
+
return { fallback: 'warmup-failed' };
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
const now = ctx.now();
|
|
215
|
+
const entry = {
|
|
216
|
+
key: p.key,
|
|
217
|
+
project: p.projectDir,
|
|
218
|
+
profile: p.profileName,
|
|
219
|
+
mode: p.mode,
|
|
220
|
+
engine: p.engine,
|
|
221
|
+
engineVersion: p.engineVersion,
|
|
222
|
+
model: p.model,
|
|
223
|
+
baseSession: built.session,
|
|
224
|
+
warmSession: warm,
|
|
225
|
+
created: now,
|
|
226
|
+
lastRead: now,
|
|
227
|
+
uses: 0,
|
|
228
|
+
refPrefix,
|
|
229
|
+
parts: p.parts,
|
|
230
|
+
};
|
|
231
|
+
reg.put(entry);
|
|
232
|
+
return { entry };
|
|
233
|
+
}
|
|
234
|
+
finally {
|
|
235
|
+
unlock(lockFile);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
async function runNoBase(ctx, p, req, task, base) {
|
|
239
|
+
const out = await ctx.runner({
|
|
240
|
+
engine: p.engine,
|
|
241
|
+
mode: p.mode,
|
|
242
|
+
profile: p.profile,
|
|
243
|
+
model: p.model,
|
|
244
|
+
cwd: p.projectDir,
|
|
245
|
+
stdin: packetInFront(p.packet, task),
|
|
246
|
+
maxTurns: req.maxTurns,
|
|
247
|
+
signal: req.signal,
|
|
248
|
+
onSpawn: req.onSpawn,
|
|
249
|
+
});
|
|
250
|
+
const rec = record(ctx, p, {
|
|
251
|
+
kind: 'run',
|
|
252
|
+
base,
|
|
253
|
+
session: out.session,
|
|
254
|
+
first: out.first,
|
|
255
|
+
total: out.total,
|
|
256
|
+
costUsd: out.costUsd ?? null,
|
|
257
|
+
ownTokens: out.first ? out.first.input + out.first.cacheWrite : null,
|
|
258
|
+
outcome: out.ok ? 'ok' : out.stopped ? 'stopped' : 'error',
|
|
259
|
+
error: out.error,
|
|
260
|
+
task: task.slice(0, 120),
|
|
261
|
+
});
|
|
262
|
+
return { task, reply: out.reply, ok: out.ok, error: out.error, record: rec };
|
|
263
|
+
}
|
|
264
|
+
/** Prefix-mode run (FR-07.3, AC-26, AC-27): packet first, no base session stored. */
|
|
265
|
+
async function runPrefix(ctx, p, req, task) {
|
|
266
|
+
const verified = isModeVerified(p.engine, p.mode, ctx.config.bar);
|
|
267
|
+
const unverified = !verified;
|
|
268
|
+
if (unverified)
|
|
269
|
+
ctx.log(UNVERIFIED_MESSAGE);
|
|
270
|
+
const out = await ctx.runner({
|
|
271
|
+
engine: p.engine,
|
|
272
|
+
mode: p.mode,
|
|
273
|
+
profile: p.profile,
|
|
274
|
+
model: p.model,
|
|
275
|
+
cwd: p.projectDir,
|
|
276
|
+
stdin: packetInFront(p.packet, task),
|
|
277
|
+
maxTurns: req.maxTurns,
|
|
278
|
+
signal: req.signal,
|
|
279
|
+
onSpawn: req.onSpawn,
|
|
280
|
+
});
|
|
281
|
+
const refPrefix = prefixOf(out.first);
|
|
282
|
+
const share = out.first && refPrefix > 0 ? Math.round((out.first.cacheRead / refPrefix) * 1000) / 1000 : null;
|
|
283
|
+
const miss = out.ok && verified && share !== null && share < ctx.config.bar;
|
|
284
|
+
if (miss)
|
|
285
|
+
ctx.log(`cache miss: prefix run read ${out.first?.cacheRead} of ${refPrefix} tokens (${Math.round((share ?? 0) * 100)}%)`);
|
|
286
|
+
const rec = record(ctx, p, {
|
|
287
|
+
kind: 'run',
|
|
288
|
+
base: 'prefix',
|
|
289
|
+
fromSession: null,
|
|
290
|
+
session: out.session,
|
|
291
|
+
first: out.first,
|
|
292
|
+
total: out.total,
|
|
293
|
+
costUsd: out.costUsd ?? null,
|
|
294
|
+
refPrefix: refPrefix || null,
|
|
295
|
+
readShare: share,
|
|
296
|
+
ownTokens: out.first ? out.first.input + out.first.cacheWrite : null,
|
|
297
|
+
cacheMiss: miss,
|
|
298
|
+
outcome: out.ok ? 'ok' : out.stopped ? 'stopped' : 'error',
|
|
299
|
+
error: out.error,
|
|
300
|
+
task: task.slice(0, 120),
|
|
301
|
+
...(unverified ? { unverified: true, note: UNVERIFIED_MESSAGE } : {}),
|
|
302
|
+
});
|
|
303
|
+
return { task, reply: out.reply, ok: out.ok, error: out.error, record: rec };
|
|
304
|
+
}
|
|
305
|
+
async function runFork(ctx, p, req, task, entry, retried = false) {
|
|
306
|
+
const from = entry.warmSession ?? entry.baseSession;
|
|
307
|
+
const out = await ctx.runner({
|
|
308
|
+
engine: p.engine,
|
|
309
|
+
mode: p.mode,
|
|
310
|
+
profile: p.profile,
|
|
311
|
+
model: p.model,
|
|
312
|
+
cwd: p.projectDir,
|
|
313
|
+
stdin: task,
|
|
314
|
+
resume: from,
|
|
315
|
+
maxTurns: req.maxTurns,
|
|
316
|
+
signal: req.signal,
|
|
317
|
+
onSpawn: req.onSpawn,
|
|
318
|
+
});
|
|
319
|
+
const reg = new Registry(ctx.home);
|
|
320
|
+
if (out.resumeError && !retried) {
|
|
321
|
+
// FR-03.5: the engine cannot resume the session; replace the entry and fork the new base.
|
|
322
|
+
ctx.log(`session ${from} can no longer be resumed; rebuilding the base`);
|
|
323
|
+
reg.forget(p.key);
|
|
324
|
+
const rebuilt = await ensureBase(ctx, p, req, true);
|
|
325
|
+
if ('fallback' in rebuilt)
|
|
326
|
+
return runNoBase(ctx, p, req, task, rebuilt.fallback);
|
|
327
|
+
return runFork(ctx, p, req, task, rebuilt.entry, true);
|
|
328
|
+
}
|
|
329
|
+
if (out.ok)
|
|
330
|
+
reg.touch(p.key, ctx.now());
|
|
331
|
+
const share = out.first && entry.refPrefix ? Math.round((out.first.cacheRead / entry.refPrefix) * 1000) / 1000 : null;
|
|
332
|
+
const miss = out.ok && share !== null && share < ctx.config.bar;
|
|
333
|
+
if (miss)
|
|
334
|
+
ctx.log(`cache miss: the fork read ${out.first?.cacheRead} of ${entry.refPrefix} prefix tokens (${Math.round((share ?? 0) * 100)}%)`);
|
|
335
|
+
const rec = record(ctx, p, {
|
|
336
|
+
kind: 'run',
|
|
337
|
+
base: 'with-base',
|
|
338
|
+
fromSession: from,
|
|
339
|
+
session: out.session,
|
|
340
|
+
first: out.first,
|
|
341
|
+
total: out.total,
|
|
342
|
+
refPrefix: entry.refPrefix,
|
|
343
|
+
readShare: share,
|
|
344
|
+
ownTokens: out.first ? out.first.input + out.first.cacheWrite : null,
|
|
345
|
+
cacheMiss: miss,
|
|
346
|
+
outcome: out.ok ? 'ok' : out.stopped ? 'stopped' : 'error',
|
|
347
|
+
error: out.error,
|
|
348
|
+
task: task.slice(0, 120),
|
|
349
|
+
});
|
|
350
|
+
return { task, reply: out.reply, ok: out.ok, error: out.error, record: rec };
|
|
351
|
+
}
|
|
352
|
+
/** One task (FR-05.1): fork a fresh base, build one when it pays, or run with the packet in front. */
|
|
353
|
+
export async function runTask(ctx, req, task) {
|
|
354
|
+
const p = prepare(ctx, req);
|
|
355
|
+
if (p.mode === 'prefix')
|
|
356
|
+
return runPrefix(ctx, p, req, task);
|
|
357
|
+
const reg = new Registry(ctx.home);
|
|
358
|
+
const entry = reg.get(p.key);
|
|
359
|
+
if (isFresh(ctx, entry))
|
|
360
|
+
return runFork(ctx, p, req, task, entry);
|
|
361
|
+
let build;
|
|
362
|
+
if (req.uses !== undefined) {
|
|
363
|
+
build = req.uses >= p.breakEven;
|
|
364
|
+
}
|
|
365
|
+
else if (p.breakEven <= 1) {
|
|
366
|
+
build = true;
|
|
367
|
+
}
|
|
368
|
+
else {
|
|
369
|
+
const seen = reg.seenAt(p.key);
|
|
370
|
+
build = seen !== undefined && ctx.now() - seen <= ctx.config.lifetimeMin * 60_000;
|
|
371
|
+
if (!build)
|
|
372
|
+
reg.markSeen(p.key, ctx.now());
|
|
373
|
+
}
|
|
374
|
+
if (!build)
|
|
375
|
+
return runNoBase(ctx, p, req, task, 'no-base');
|
|
376
|
+
const got = await ensureBase(ctx, p, req);
|
|
377
|
+
if ('fallback' in got)
|
|
378
|
+
return runNoBase(ctx, p, req, task, got.fallback);
|
|
379
|
+
return runFork(ctx, p, req, task, got.entry);
|
|
380
|
+
}
|
|
381
|
+
/** A fan-out (FR-05.3): build and warm once, then fork every task with a parallel limit. */
|
|
382
|
+
export async function runTasks(ctx, req, tasks) {
|
|
383
|
+
if (tasks.length === 0)
|
|
384
|
+
return [];
|
|
385
|
+
const p = prepare(ctx, req);
|
|
386
|
+
if (p.mode === 'prefix') {
|
|
387
|
+
const results = new Array(tasks.length);
|
|
388
|
+
let next = 0;
|
|
389
|
+
const worker = async () => {
|
|
390
|
+
while (next < tasks.length) {
|
|
391
|
+
const i = next++;
|
|
392
|
+
results[i] = await runPrefix(ctx, p, req, tasks[i]);
|
|
393
|
+
}
|
|
394
|
+
};
|
|
395
|
+
const width = Math.max(1, Math.min(ctx.config.limits.parallel, tasks.length));
|
|
396
|
+
await Promise.all(Array.from({ length: width }, worker));
|
|
397
|
+
return results;
|
|
398
|
+
}
|
|
399
|
+
const got = await ensureBase(ctx, p, req);
|
|
400
|
+
const results = new Array(tasks.length);
|
|
401
|
+
let next = 0;
|
|
402
|
+
const worker = async () => {
|
|
403
|
+
while (next < tasks.length) {
|
|
404
|
+
const i = next++;
|
|
405
|
+
results[i] = 'fallback' in got
|
|
406
|
+
? await runNoBase(ctx, p, req, tasks[i], got.fallback)
|
|
407
|
+
: await runFork(ctx, p, req, tasks[i], got.entry);
|
|
408
|
+
}
|
|
409
|
+
};
|
|
410
|
+
const width = Math.max(1, Math.min(ctx.config.limits.parallel, tasks.length));
|
|
411
|
+
await Promise.all(Array.from({ length: width }, worker));
|
|
412
|
+
return results;
|
|
413
|
+
}
|
|
414
|
+
/** `faber-cache warm` (FR-04.5): one build ahead of a batch, never a schedule. */
|
|
415
|
+
export async function warm(ctx, req) {
|
|
416
|
+
if (req.engine === 'agy') {
|
|
417
|
+
throw new CacheError('agy runs in prefix mode and has no base session to warm; run tasks directly with --engine agy');
|
|
418
|
+
}
|
|
419
|
+
const p = prepare(ctx, req, 'fixed');
|
|
420
|
+
const got = await ensureBase(ctx, p, req);
|
|
421
|
+
if ('fallback' in got)
|
|
422
|
+
throw new CacheError(`no base built: ${got.fallback}`);
|
|
423
|
+
return got.entry;
|
|
424
|
+
}
|
|
425
|
+
function shellQuote(s) {
|
|
426
|
+
return /^[A-Za-z0-9_./:=,@+-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`;
|
|
427
|
+
}
|
|
428
|
+
function refuseNoFork(engine) {
|
|
429
|
+
if (engine === 'agy')
|
|
430
|
+
throw new CacheError('agy has no fork, so there is no interactive open for it (FR-06.4)');
|
|
431
|
+
if (engine === 'codex')
|
|
432
|
+
throw new CacheError('the Codex adapter is not in v0.1; interactive open needs its fork, unverified until measured');
|
|
433
|
+
}
|
|
434
|
+
/** The interactive fork of the warm default-prompt base, built first if needed (FR-06.1). */
|
|
435
|
+
export async function planOpen(ctx, req) {
|
|
436
|
+
refuseNoFork(req.engine);
|
|
437
|
+
const p = prepare(ctx, req, 'default', 'interactive');
|
|
438
|
+
const got = await ensureBase(ctx, p, req);
|
|
439
|
+
if ('fallback' in got)
|
|
440
|
+
throw new CacheError(`no base to open: ${got.fallback}`);
|
|
441
|
+
const session = got.entry.warmSession ?? got.entry.baseSession;
|
|
442
|
+
const bin = claudeBin();
|
|
443
|
+
const args = openArgs(p.mode, p.profile, p.model, session);
|
|
444
|
+
const command = `cd ${shellQuote(p.projectDir)} && ${[bin, ...args].map(shellQuote).join(' ')}`;
|
|
445
|
+
return { cwd: p.projectDir, bin, args, command, entry: got.entry, prepared: p };
|
|
446
|
+
}
|
|
447
|
+
/** Launch the interactive fork in this terminal (FR-06.3): last read updated, one open record. */
|
|
448
|
+
export async function launchOpen(ctx, plan) {
|
|
449
|
+
const reg = new Registry(ctx.home);
|
|
450
|
+
reg.touch(plan.entry.key, ctx.now());
|
|
451
|
+
record(ctx, plan.prepared, {
|
|
452
|
+
kind: 'open',
|
|
453
|
+
base: 'with-base',
|
|
454
|
+
fromSession: plan.entry.warmSession ?? plan.entry.baseSession,
|
|
455
|
+
refPrefix: plan.entry.refPrefix,
|
|
456
|
+
outcome: 'ok',
|
|
457
|
+
});
|
|
458
|
+
return new Promise((resolve) => {
|
|
459
|
+
const child = spawn(plan.bin, plan.args, { cwd: plan.cwd, stdio: 'inherit' });
|
|
460
|
+
child.on('error', () => resolve(1));
|
|
461
|
+
child.on('close', (code) => resolve(code ?? 0));
|
|
462
|
+
});
|
|
463
|
+
}
|
|
464
|
+
/** `faber-cache status` (FR-12.2): the current key and every registered base of the project. */
|
|
465
|
+
export function status(ctx, req) {
|
|
466
|
+
const p = prepare(ctx, req);
|
|
467
|
+
const bases = new Registry(ctx.home).load().bases;
|
|
468
|
+
const maxAge = (ctx.config.lifetimeMin - ctx.config.marginMin) * 60_000;
|
|
469
|
+
const rows = Object.values(bases)
|
|
470
|
+
.filter((e) => e.project === p.projectDir)
|
|
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);
|
|
490
|
+
return { project: p.projectDir, currentKey: p.key, rows };
|
|
491
|
+
}
|
|
492
|
+
/** FR-11.5 / AC-57: three independent single-turn agy runs with the same packet at 0, 1 and 10 min. */
|
|
493
|
+
export async function measureAgy(ctx, req, opts = {}) {
|
|
494
|
+
const delaysMin = opts.delaysMin ?? [0, 1, 10];
|
|
495
|
+
const sleep = opts.sleep ?? ((ms) => new Promise((res) => setTimeout(res, ms)));
|
|
496
|
+
const fullReq = { ...req, engine: 'agy', mode: 'prefix' };
|
|
497
|
+
const p = prepare(ctx, fullReq);
|
|
498
|
+
const prompts = [
|
|
499
|
+
'Reply with the single word: ready',
|
|
500
|
+
'Reply with the single word: check-one',
|
|
501
|
+
'Reply with the single word: check-two',
|
|
502
|
+
];
|
|
503
|
+
const runs = [];
|
|
504
|
+
for (let i = 0; i < delaysMin.length; i++) {
|
|
505
|
+
const waitMin = i === 0 ? delaysMin[0] : Math.max(0, delaysMin[i] - delaysMin[i - 1]);
|
|
506
|
+
if (waitMin > 0)
|
|
507
|
+
await sleep(waitMin * 60_000);
|
|
508
|
+
const res = await runPrefix(ctx, p, fullReq, prompts[i] ?? `Reply with the single word: check-${i}`);
|
|
509
|
+
runs.push({
|
|
510
|
+
index: i + 1,
|
|
511
|
+
delayMin: delaysMin[i],
|
|
512
|
+
at: res.record.at,
|
|
513
|
+
ok: res.ok,
|
|
514
|
+
session: res.record.session,
|
|
515
|
+
first: res.record.first,
|
|
516
|
+
total: res.record.total,
|
|
517
|
+
refPrefix: res.record.refPrefix,
|
|
518
|
+
readShare: res.record.readShare,
|
|
519
|
+
error: res.error,
|
|
520
|
+
});
|
|
521
|
+
}
|
|
522
|
+
const later = runs.slice(1).filter((r) => r.ok && r.readShare !== null);
|
|
523
|
+
const meanReadShare = later.length
|
|
524
|
+
? Math.round((later.reduce((sum, r) => sum + (r.readShare ?? 0), 0) / later.length) * 1000) / 1000
|
|
525
|
+
: null;
|
|
526
|
+
const passed = runs.length >= 3 && later.length === runs.length - 1 && later.every((r) => (r.readShare ?? 0) >= ctx.config.bar);
|
|
527
|
+
return {
|
|
528
|
+
engine: 'agy',
|
|
529
|
+
mode: 'prefix',
|
|
530
|
+
engineVersion: p.engineVersion,
|
|
531
|
+
model: p.model,
|
|
532
|
+
date: new Date(ctx.now()).toISOString().slice(0, 10),
|
|
533
|
+
runs,
|
|
534
|
+
passed,
|
|
535
|
+
meanReadShare,
|
|
536
|
+
};
|
|
537
|
+
}
|
|
538
|
+
export { READ_ONLY };
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { RunRecord, Usage } from './records.js';
|
|
2
|
+
/**
|
|
3
|
+
* Price weights relative to one fresh input token, the same for every current Claude model:
|
|
4
|
+
* a cache write costs 1.25x (five-minute lifetime) or 2x (one hour), a cache read 0.1x, output 5x.
|
|
5
|
+
*/
|
|
6
|
+
export declare const WEIGHTS: {
|
|
7
|
+
readonly input: 1;
|
|
8
|
+
readonly write5m: 1.25;
|
|
9
|
+
readonly write1h: 2;
|
|
10
|
+
readonly read: 0.1;
|
|
11
|
+
readonly output: 5;
|
|
12
|
+
};
|
|
13
|
+
/** A usage's cost in input-token equivalents. */
|
|
14
|
+
export declare function inputEquivalents(u: Usage | null | undefined): number;
|
|
15
|
+
/**
|
|
16
|
+
* Dollars per input-token equivalent, from the records whose engine-reported cost is their own
|
|
17
|
+
* (builds and runs that resume nothing), or null when there are none.
|
|
18
|
+
*/
|
|
19
|
+
export declare function usdPerEquivalent(records: RunRecord[]): number | null;
|
|
20
|
+
/**
|
|
21
|
+
* A conservative estimate of what a fork saved against sending the packet fresh: the tokens its
|
|
22
|
+
* first request read from cache, priced as plain input instead of a cache read. It leaves out the
|
|
23
|
+
* cache-write premium a fresh session would also pay, so the real saving is larger (see bench/).
|
|
24
|
+
*/
|
|
25
|
+
export declare function forkSaving(r: RunRecord): number;
|
package/dist/src/cost.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Price weights relative to one fresh input token, the same for every current Claude model:
|
|
3
|
+
* a cache write costs 1.25x (five-minute lifetime) or 2x (one hour), a cache read 0.1x, output 5x.
|
|
4
|
+
*/
|
|
5
|
+
export const WEIGHTS = { input: 1, write5m: 1.25, write1h: 2, read: 0.1, output: 5 };
|
|
6
|
+
/** A usage's cost in input-token equivalents. */
|
|
7
|
+
export function inputEquivalents(u) {
|
|
8
|
+
if (!u)
|
|
9
|
+
return 0;
|
|
10
|
+
const w1h = Math.min(u.cacheWrite1h ?? 0, u.cacheWrite);
|
|
11
|
+
return (u.input * WEIGHTS.input +
|
|
12
|
+
(u.cacheWrite - w1h) * WEIGHTS.write5m +
|
|
13
|
+
w1h * WEIGHTS.write1h +
|
|
14
|
+
u.cacheRead * WEIGHTS.read +
|
|
15
|
+
u.output * WEIGHTS.output);
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Dollars per input-token equivalent, from the records whose engine-reported cost is their own
|
|
19
|
+
* (builds and runs that resume nothing), or null when there are none.
|
|
20
|
+
*/
|
|
21
|
+
export function usdPerEquivalent(records) {
|
|
22
|
+
let usd = 0;
|
|
23
|
+
let eq = 0;
|
|
24
|
+
for (const r of records) {
|
|
25
|
+
if (typeof r.costUsd !== 'number' || !r.total)
|
|
26
|
+
continue;
|
|
27
|
+
usd += r.costUsd;
|
|
28
|
+
eq += inputEquivalents(r.total);
|
|
29
|
+
}
|
|
30
|
+
return usd > 0 && eq > 0 ? usd / eq : null;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* A conservative estimate of what a fork saved against sending the packet fresh: the tokens its
|
|
34
|
+
* first request read from cache, priced as plain input instead of a cache read. It leaves out the
|
|
35
|
+
* cache-write premium a fresh session would also pay, so the real saving is larger (see bench/).
|
|
36
|
+
*/
|
|
37
|
+
export function forkSaving(r) {
|
|
38
|
+
return (r.first?.cacheRead ?? 0) * (WEIGHTS.input - WEIGHTS.read);
|
|
39
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { EngineStatus } from './engines/claude.js';
|
|
2
|
+
export interface ModeReport {
|
|
3
|
+
engine: string;
|
|
4
|
+
mode: string;
|
|
5
|
+
state: 'measured' | 'partly measured' | 'unmeasured' | 're-check' | 'no cache guarantee';
|
|
6
|
+
needsWarmup: boolean | null;
|
|
7
|
+
breakEven: number | null;
|
|
8
|
+
measuredOn: string | null;
|
|
9
|
+
note: string;
|
|
10
|
+
}
|
|
11
|
+
export interface MissReport {
|
|
12
|
+
at: string;
|
|
13
|
+
project: string;
|
|
14
|
+
key: string;
|
|
15
|
+
readShare: number | null;
|
|
16
|
+
differs: string[];
|
|
17
|
+
}
|
|
18
|
+
export interface DoctorReport {
|
|
19
|
+
engines: EngineStatus[];
|
|
20
|
+
settings: {
|
|
21
|
+
excludeDynamicSystemPromptSections: boolean;
|
|
22
|
+
};
|
|
23
|
+
modes: ModeReport[];
|
|
24
|
+
misses: MissReport[];
|
|
25
|
+
}
|
|
26
|
+
export declare function doctor(home: string, bar?: number): DoctorReport;
|