@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 +202 -0
- package/README.md +163 -2
- package/data/measured-modes.json +94 -0
- package/dist/src/cli.d.ts +3 -0
- package/dist/src/cli.js +197 -0
- package/dist/src/config.d.ts +54 -0
- package/dist/src/config.js +90 -0
- package/dist/src/core.d.ts +120 -0
- package/dist/src/core.js +518 -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 +60 -0
- package/dist/src/engines/claude.js +211 -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 +38 -4
package/dist/src/lock.js
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import * as fs from 'node:fs';
|
|
2
|
+
import * as path from 'node:path';
|
|
3
|
+
const sleeper = new Int32Array(new SharedArrayBuffer(4));
|
|
4
|
+
export function sleepSync(ms) {
|
|
5
|
+
Atomics.wait(sleeper, 0, 0, ms);
|
|
6
|
+
}
|
|
7
|
+
export function pidAlive(pid) {
|
|
8
|
+
if (!Number.isInteger(pid) || pid <= 0)
|
|
9
|
+
return false;
|
|
10
|
+
try {
|
|
11
|
+
process.kill(pid, 0);
|
|
12
|
+
return true;
|
|
13
|
+
}
|
|
14
|
+
catch (err) {
|
|
15
|
+
return err.code === 'EPERM';
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
/** Try once to take a lock file; a lock whose process is gone is taken over (FR-03.5). */
|
|
19
|
+
export function tryLock(file) {
|
|
20
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
21
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
22
|
+
try {
|
|
23
|
+
const fd = fs.openSync(file, 'wx');
|
|
24
|
+
fs.writeSync(fd, JSON.stringify({ pid: process.pid, at: Date.now() }));
|
|
25
|
+
fs.closeSync(fd);
|
|
26
|
+
return true;
|
|
27
|
+
}
|
|
28
|
+
catch (err) {
|
|
29
|
+
if (err.code !== 'EEXIST')
|
|
30
|
+
throw err;
|
|
31
|
+
}
|
|
32
|
+
let holder = 0;
|
|
33
|
+
try {
|
|
34
|
+
holder = Number(JSON.parse(fs.readFileSync(file, 'utf8')).pid);
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
// A lock file being written right now, or garbage: treat a garbage file older than 10 s as dead.
|
|
38
|
+
try {
|
|
39
|
+
if (Date.now() - fs.statSync(file).mtimeMs < 10_000)
|
|
40
|
+
return false;
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
if (holder && pidAlive(holder))
|
|
47
|
+
return false;
|
|
48
|
+
try {
|
|
49
|
+
fs.unlinkSync(file);
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
// Someone else took it over first.
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return false;
|
|
56
|
+
}
|
|
57
|
+
export function unlock(file) {
|
|
58
|
+
try {
|
|
59
|
+
const holder = Number(JSON.parse(fs.readFileSync(file, 'utf8')).pid);
|
|
60
|
+
if (holder === process.pid)
|
|
61
|
+
fs.unlinkSync(file);
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
// Already gone.
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
/** Wait for a lock up to `waitMs`; false on timeout. */
|
|
68
|
+
export async function acquire(file, waitMs, pollMs = 200) {
|
|
69
|
+
const until = Date.now() + waitMs;
|
|
70
|
+
for (;;) {
|
|
71
|
+
if (tryLock(file))
|
|
72
|
+
return true;
|
|
73
|
+
if (Date.now() >= until)
|
|
74
|
+
return false;
|
|
75
|
+
await new Promise((r) => setTimeout(r, Math.min(pollMs, Math.max(1, until - Date.now()))));
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
/** A short, synchronous critical section (registry writes). */
|
|
79
|
+
export function withLockSync(file, fn, waitMs = 10_000) {
|
|
80
|
+
const until = Date.now() + waitMs;
|
|
81
|
+
while (!tryLock(file)) {
|
|
82
|
+
if (Date.now() >= until)
|
|
83
|
+
throw new Error(`timed out waiting for ${path.basename(file)}`);
|
|
84
|
+
sleepSync(20);
|
|
85
|
+
}
|
|
86
|
+
try {
|
|
87
|
+
return fn();
|
|
88
|
+
}
|
|
89
|
+
finally {
|
|
90
|
+
unlock(file);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { Context } from './core.js';
|
|
2
|
+
interface JsonRpcRequest {
|
|
3
|
+
jsonrpc: '2.0';
|
|
4
|
+
id?: string | number | null;
|
|
5
|
+
method: string;
|
|
6
|
+
params?: Record<string, unknown>;
|
|
7
|
+
}
|
|
8
|
+
export declare const MCP_TOOLS: ({
|
|
9
|
+
name: string;
|
|
10
|
+
description: string;
|
|
11
|
+
inputSchema: {
|
|
12
|
+
type: string;
|
|
13
|
+
properties: {
|
|
14
|
+
project: {
|
|
15
|
+
type: string;
|
|
16
|
+
description: string;
|
|
17
|
+
};
|
|
18
|
+
mode: {
|
|
19
|
+
type: string;
|
|
20
|
+
enum: string[];
|
|
21
|
+
description: string;
|
|
22
|
+
};
|
|
23
|
+
engine: {
|
|
24
|
+
type: string;
|
|
25
|
+
enum: string[];
|
|
26
|
+
description: string;
|
|
27
|
+
};
|
|
28
|
+
tasks?: undefined;
|
|
29
|
+
model?: undefined;
|
|
30
|
+
};
|
|
31
|
+
required: string[];
|
|
32
|
+
};
|
|
33
|
+
} | {
|
|
34
|
+
name: string;
|
|
35
|
+
description: string;
|
|
36
|
+
inputSchema: {
|
|
37
|
+
type: string;
|
|
38
|
+
properties: {
|
|
39
|
+
project: {
|
|
40
|
+
type: string;
|
|
41
|
+
description: string;
|
|
42
|
+
};
|
|
43
|
+
mode: {
|
|
44
|
+
type: string;
|
|
45
|
+
enum: string[];
|
|
46
|
+
description: string;
|
|
47
|
+
};
|
|
48
|
+
engine?: undefined;
|
|
49
|
+
tasks?: undefined;
|
|
50
|
+
model?: undefined;
|
|
51
|
+
};
|
|
52
|
+
required: string[];
|
|
53
|
+
};
|
|
54
|
+
} | {
|
|
55
|
+
name: string;
|
|
56
|
+
description: string;
|
|
57
|
+
inputSchema: {
|
|
58
|
+
type: string;
|
|
59
|
+
properties: {
|
|
60
|
+
project: {
|
|
61
|
+
type: string;
|
|
62
|
+
description: string;
|
|
63
|
+
};
|
|
64
|
+
mode: {
|
|
65
|
+
type: string;
|
|
66
|
+
enum: string[];
|
|
67
|
+
description: string;
|
|
68
|
+
};
|
|
69
|
+
engine: {
|
|
70
|
+
type: string;
|
|
71
|
+
enum: string[];
|
|
72
|
+
description: string;
|
|
73
|
+
};
|
|
74
|
+
tasks: {
|
|
75
|
+
type: string;
|
|
76
|
+
items: {
|
|
77
|
+
type: string;
|
|
78
|
+
};
|
|
79
|
+
description: string;
|
|
80
|
+
};
|
|
81
|
+
model: {
|
|
82
|
+
type: string;
|
|
83
|
+
};
|
|
84
|
+
};
|
|
85
|
+
required: string[];
|
|
86
|
+
};
|
|
87
|
+
} | {
|
|
88
|
+
name: string;
|
|
89
|
+
description: string;
|
|
90
|
+
inputSchema: {
|
|
91
|
+
type: string;
|
|
92
|
+
properties: {
|
|
93
|
+
project: {
|
|
94
|
+
type: string;
|
|
95
|
+
description: string;
|
|
96
|
+
};
|
|
97
|
+
mode?: undefined;
|
|
98
|
+
engine?: undefined;
|
|
99
|
+
tasks?: undefined;
|
|
100
|
+
model?: undefined;
|
|
101
|
+
};
|
|
102
|
+
required: string[];
|
|
103
|
+
};
|
|
104
|
+
})[];
|
|
105
|
+
type ToolResult = {
|
|
106
|
+
content: Array<{
|
|
107
|
+
type: 'text';
|
|
108
|
+
text: string;
|
|
109
|
+
}>;
|
|
110
|
+
isError?: boolean;
|
|
111
|
+
};
|
|
112
|
+
export declare class McpServer {
|
|
113
|
+
private readonly ctx;
|
|
114
|
+
private readonly controllers;
|
|
115
|
+
private readonly children;
|
|
116
|
+
constructor(ctx: Context);
|
|
117
|
+
/** Stop every engine process this server started (cancel, disconnect, timeout). */
|
|
118
|
+
stopAll(): void;
|
|
119
|
+
activeChildren(): number[];
|
|
120
|
+
callTool(name: string, args: Record<string, unknown>): Promise<ToolResult>;
|
|
121
|
+
private cacheRun;
|
|
122
|
+
handle(req: JsonRpcRequest): Promise<Record<string, unknown> | null>;
|
|
123
|
+
}
|
|
124
|
+
/** `faber-cache mcp`: stdio JSON-RPC, one message per line (FR-08.1). */
|
|
125
|
+
export declare function serveStdio(ctx?: Context): void;
|
|
126
|
+
export {};
|
package/dist/src/mcp.js
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
import * as readline from 'node:readline';
|
|
2
|
+
import { CacheError, defaultContext, planOpen, runTask, runTasks, status, warm } from './core.js';
|
|
3
|
+
import { currentDepth } from './engines/claude.js';
|
|
4
|
+
import { getPackageVersion } from './version.js';
|
|
5
|
+
const project = { type: 'string', description: 'The project folder (absolute, or relative to the server working folder).' };
|
|
6
|
+
const mode = { type: 'string', enum: ['fixed', 'default', 'prefix'], description: 'fixed (default for claude), default, or prefix (for agy).' };
|
|
7
|
+
const engine = { type: 'string', enum: ['claude', 'agy'], description: 'claude (default) or agy (prefix mode).' };
|
|
8
|
+
export const MCP_TOOLS = [
|
|
9
|
+
{
|
|
10
|
+
name: 'cache_status',
|
|
11
|
+
description: "A project's base sessions: current key, fresh or not, uses, last read.",
|
|
12
|
+
inputSchema: { type: 'object', properties: { project, mode, engine }, required: ['project'] },
|
|
13
|
+
},
|
|
14
|
+
{
|
|
15
|
+
name: 'cache_warm',
|
|
16
|
+
description: "Build and warm a project's read-only base ahead of a batch (one build, no schedule).",
|
|
17
|
+
inputSchema: { type: 'object', properties: { project, mode }, required: ['project'] },
|
|
18
|
+
},
|
|
19
|
+
{
|
|
20
|
+
name: 'cache_run',
|
|
21
|
+
description: 'Run one task, or a short list, on read-only forks of the project base (or prefix mode for agy); returns each reply and its run record (read share, cache read). Refused inside a fork.',
|
|
22
|
+
inputSchema: {
|
|
23
|
+
type: 'object',
|
|
24
|
+
properties: {
|
|
25
|
+
project,
|
|
26
|
+
mode,
|
|
27
|
+
engine,
|
|
28
|
+
tasks: { type: 'array', items: { type: 'string' }, description: 'The tasks; each runs in its own fork.' },
|
|
29
|
+
model: { type: 'string' },
|
|
30
|
+
},
|
|
31
|
+
required: ['project', 'tasks'],
|
|
32
|
+
},
|
|
33
|
+
},
|
|
34
|
+
{
|
|
35
|
+
name: 'cache_open_command',
|
|
36
|
+
description: 'The shell command that opens an interactive session as a fork of the warm default-prompt base.',
|
|
37
|
+
inputSchema: { type: 'object', properties: { project }, required: ['project'] },
|
|
38
|
+
},
|
|
39
|
+
];
|
|
40
|
+
function text(value, isError = false) {
|
|
41
|
+
return { content: [{ type: 'text', text: typeof value === 'string' ? value : JSON.stringify(value, null, 2) }], ...(isError ? { isError } : {}) };
|
|
42
|
+
}
|
|
43
|
+
export class McpServer {
|
|
44
|
+
ctx;
|
|
45
|
+
controllers = new Set();
|
|
46
|
+
children = new Set();
|
|
47
|
+
constructor(ctx) {
|
|
48
|
+
this.ctx = ctx;
|
|
49
|
+
}
|
|
50
|
+
/** Stop every engine process this server started (cancel, disconnect, timeout). */
|
|
51
|
+
stopAll() {
|
|
52
|
+
for (const c of this.controllers)
|
|
53
|
+
c.abort();
|
|
54
|
+
}
|
|
55
|
+
activeChildren() {
|
|
56
|
+
return [...this.children];
|
|
57
|
+
}
|
|
58
|
+
async callTool(name, args) {
|
|
59
|
+
const req = {
|
|
60
|
+
project: String(args.project ?? ''),
|
|
61
|
+
mode: args.mode,
|
|
62
|
+
engine: typeof args.engine === 'string' ? args.engine : undefined,
|
|
63
|
+
};
|
|
64
|
+
if (!req.project)
|
|
65
|
+
return text('project is required', true);
|
|
66
|
+
try {
|
|
67
|
+
switch (name) {
|
|
68
|
+
case 'cache_status':
|
|
69
|
+
return text(status(this.ctx, { ...req, forceReadOnly: true }));
|
|
70
|
+
case 'cache_warm': {
|
|
71
|
+
const e = await warm(this.ctx, { ...req, forceReadOnly: true });
|
|
72
|
+
return text({ key: e.key, baseSession: e.baseSession, warmSession: e.warmSession, profile: e.profile, mode: e.mode });
|
|
73
|
+
}
|
|
74
|
+
case 'cache_run':
|
|
75
|
+
return await this.cacheRun(req, args);
|
|
76
|
+
case 'cache_open_command': {
|
|
77
|
+
const plan = await planOpen(this.ctx, { project: req.project });
|
|
78
|
+
return text({ command: plan.command });
|
|
79
|
+
}
|
|
80
|
+
default:
|
|
81
|
+
return text(`unknown tool ${name}`, true);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
catch (err) {
|
|
85
|
+
return text(err instanceof Error ? err.message : String(err), true);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
async cacheRun(req, args) {
|
|
89
|
+
// FR-08.3: a fork must not start forks of its own.
|
|
90
|
+
if (currentDepth() >= 1)
|
|
91
|
+
return text('cache_run is refused inside a fork started by FaberSEP Cache (no nested forks)', true);
|
|
92
|
+
const tasks = Array.isArray(args.tasks) ? args.tasks.map(String) : typeof args.task === 'string' ? [args.task] : [];
|
|
93
|
+
if (!tasks.length)
|
|
94
|
+
return text('tasks is required: a list of task texts', true);
|
|
95
|
+
const limits = this.ctx.config.limits;
|
|
96
|
+
if (tasks.length > limits.mcpMaxTasks) {
|
|
97
|
+
return text(`cache_run takes at most ${limits.mcpMaxTasks} tasks per call; got ${tasks.length}, nothing started`, true);
|
|
98
|
+
}
|
|
99
|
+
const controller = new AbortController();
|
|
100
|
+
this.controllers.add(controller);
|
|
101
|
+
const timer = setTimeout(() => controller.abort(), limits.mcpTimeoutSec * 1000);
|
|
102
|
+
const pids = [];
|
|
103
|
+
const full = {
|
|
104
|
+
...req,
|
|
105
|
+
model: typeof args.model === 'string' ? args.model : undefined,
|
|
106
|
+
forceReadOnly: true,
|
|
107
|
+
maxTurns: limits.mcpMaxTurns,
|
|
108
|
+
signal: controller.signal,
|
|
109
|
+
onSpawn: (pid) => {
|
|
110
|
+
pids.push(pid);
|
|
111
|
+
this.children.add(pid);
|
|
112
|
+
},
|
|
113
|
+
};
|
|
114
|
+
try {
|
|
115
|
+
const results = tasks.length === 1 ? [await runTask(this.ctx, full, tasks[0])] : await runTasks(this.ctx, full, tasks);
|
|
116
|
+
const stopped = results.filter((r) => r.record.outcome === 'stopped').map((r) => r.task);
|
|
117
|
+
return text({
|
|
118
|
+
results: results.map((r) => ({ task: r.task, ok: r.ok, reply: r.reply, error: r.error, record: r.record })),
|
|
119
|
+
...(stopped.length ? { stopped, reason: controller.signal.aborted ? `timed out after ${limits.mcpTimeoutSec} s or cancelled` : 'turn limit' } : {}),
|
|
120
|
+
}, results.some((r) => !r.ok) && results.every((r) => !r.ok));
|
|
121
|
+
}
|
|
122
|
+
catch (err) {
|
|
123
|
+
if (controller.signal.aborted)
|
|
124
|
+
return text({ stopped: tasks, reason: `timed out after ${limits.mcpTimeoutSec} s or cancelled` }, true);
|
|
125
|
+
throw err;
|
|
126
|
+
}
|
|
127
|
+
finally {
|
|
128
|
+
clearTimeout(timer);
|
|
129
|
+
this.controllers.delete(controller);
|
|
130
|
+
for (const pid of pids)
|
|
131
|
+
this.children.delete(pid);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
async handle(req) {
|
|
135
|
+
const id = req.id ?? null;
|
|
136
|
+
switch (req.method) {
|
|
137
|
+
case 'initialize':
|
|
138
|
+
return {
|
|
139
|
+
jsonrpc: '2.0',
|
|
140
|
+
id,
|
|
141
|
+
result: {
|
|
142
|
+
protocolVersion: '2024-11-05',
|
|
143
|
+
capabilities: { tools: {} },
|
|
144
|
+
serverInfo: { name: 'faber-cache', version: getPackageVersion() },
|
|
145
|
+
},
|
|
146
|
+
};
|
|
147
|
+
case 'notifications/initialized':
|
|
148
|
+
case 'notifications/cancelled':
|
|
149
|
+
if (req.method === 'notifications/cancelled')
|
|
150
|
+
this.stopAll();
|
|
151
|
+
return null;
|
|
152
|
+
case 'ping':
|
|
153
|
+
return { jsonrpc: '2.0', id, result: {} };
|
|
154
|
+
case 'tools/list':
|
|
155
|
+
return { jsonrpc: '2.0', id, result: { tools: MCP_TOOLS } };
|
|
156
|
+
case 'tools/call': {
|
|
157
|
+
const params = req.params ?? {};
|
|
158
|
+
const result = await this.callTool(String(params.name ?? ''), params.arguments ?? {});
|
|
159
|
+
return { jsonrpc: '2.0', id, result };
|
|
160
|
+
}
|
|
161
|
+
default:
|
|
162
|
+
if (req.id === undefined)
|
|
163
|
+
return null;
|
|
164
|
+
return { jsonrpc: '2.0', id, error: { code: -32601, message: `method not found: ${req.method}` } };
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
/** `faber-cache mcp`: stdio JSON-RPC, one message per line (FR-08.1). */
|
|
169
|
+
export function serveStdio(ctx = defaultContext({ log: () => undefined })) {
|
|
170
|
+
const server = new McpServer(ctx);
|
|
171
|
+
const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });
|
|
172
|
+
const write = (msg) => process.stdout.write(JSON.stringify(msg) + '\n');
|
|
173
|
+
rl.on('line', (line) => {
|
|
174
|
+
if (!line.trim())
|
|
175
|
+
return;
|
|
176
|
+
let req;
|
|
177
|
+
try {
|
|
178
|
+
req = JSON.parse(line);
|
|
179
|
+
}
|
|
180
|
+
catch {
|
|
181
|
+
write({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'parse error' } });
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
server
|
|
185
|
+
.handle(req)
|
|
186
|
+
.then((res) => res && write(res))
|
|
187
|
+
.catch((err) => write({ jsonrpc: '2.0', id: req.id ?? null, error: { code: -32603, message: err instanceof CacheError || err instanceof Error ? err.message : String(err) } }));
|
|
188
|
+
});
|
|
189
|
+
// FR-08.5: the client went away; stop the children it started.
|
|
190
|
+
rl.on('close', () => {
|
|
191
|
+
server.stopAll();
|
|
192
|
+
setTimeout(() => process.exit(0), 2500).unref();
|
|
193
|
+
});
|
|
194
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
export interface CostUsage {
|
|
2
|
+
input: number;
|
|
3
|
+
cacheWrite: number;
|
|
4
|
+
cacheRead: number;
|
|
5
|
+
}
|
|
6
|
+
/** One measured mode, shipped as package data (FR-11.3). */
|
|
7
|
+
export interface MeasuredMode {
|
|
8
|
+
engineVersion: string;
|
|
9
|
+
date: string;
|
|
10
|
+
model: string;
|
|
11
|
+
tools: string;
|
|
12
|
+
/** All of FR-11.2 done (timed forks and the expiry check). */
|
|
13
|
+
complete: boolean;
|
|
14
|
+
needsWarmup: boolean;
|
|
15
|
+
/** The base's first request: also what one run with the packet in front costs. */
|
|
16
|
+
build: CostUsage;
|
|
17
|
+
warmup: CostUsage | null;
|
|
18
|
+
/** A task fork's first request: what it reads, and the base tail it rewrites. */
|
|
19
|
+
fork: {
|
|
20
|
+
cacheRead: number;
|
|
21
|
+
tailWrite: number;
|
|
22
|
+
};
|
|
23
|
+
readShare: number;
|
|
24
|
+
note?: string;
|
|
25
|
+
}
|
|
26
|
+
export type MeasuredData = Record<string, Record<string, MeasuredMode>>;
|
|
27
|
+
/** Token-unit weights: input 1, 1-hour cache write 2, cache read 0.1. */
|
|
28
|
+
export declare const WEIGHTS: {
|
|
29
|
+
input: number;
|
|
30
|
+
cacheWrite: number;
|
|
31
|
+
cacheRead: number;
|
|
32
|
+
};
|
|
33
|
+
/** A base pays when its path costs at most this much more than running without one. */
|
|
34
|
+
export declare const BREAK_EVEN_TOLERANCE = 0.1;
|
|
35
|
+
export declare function cost(u: CostUsage): number;
|
|
36
|
+
/** The smallest number of uses for which a base pays (FR-04.3; architecture §6). */
|
|
37
|
+
export declare function breakEven(m: MeasuredMode, max?: number): number;
|
|
38
|
+
export declare function loadMeasured(): MeasuredData;
|
|
39
|
+
export declare function measuredMode(engine: string, mode: string): MeasuredMode | undefined;
|
|
40
|
+
/** Defaults for an unmeasured mode: assume a warm-up is needed and a base pays from 2 uses. */
|
|
41
|
+
export declare function modePolicy(engine: string, mode: string): {
|
|
42
|
+
needsWarmup: boolean;
|
|
43
|
+
breakEven: number;
|
|
44
|
+
measured: boolean;
|
|
45
|
+
};
|
|
46
|
+
export declare function major(version: string): string;
|
|
47
|
+
/** Whether a mode has a completed measurement that passed the read-share bar (FR-11.3, FR-07.3). */
|
|
48
|
+
export declare function isModeVerified(engine: string, mode: string, bar?: number): boolean;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import * as fs from 'node:fs';
|
|
2
|
+
import * as path from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
/** Token-unit weights: input 1, 1-hour cache write 2, cache read 0.1. */
|
|
5
|
+
export const WEIGHTS = { input: 1, cacheWrite: 2, cacheRead: 0.1 };
|
|
6
|
+
/** A base pays when its path costs at most this much more than running without one. */
|
|
7
|
+
export const BREAK_EVEN_TOLERANCE = 0.1;
|
|
8
|
+
export function cost(u) {
|
|
9
|
+
return u.input * WEIGHTS.input + u.cacheWrite * WEIGHTS.cacheWrite + u.cacheRead * WEIGHTS.cacheRead;
|
|
10
|
+
}
|
|
11
|
+
/** The smallest number of uses for which a base pays (FR-04.3; architecture §6). */
|
|
12
|
+
export function breakEven(m, max = 100) {
|
|
13
|
+
const noBase = cost(m.build);
|
|
14
|
+
const fixed = cost(m.build) + (m.warmup ? cost(m.warmup) : 0);
|
|
15
|
+
const perFork = m.fork.cacheRead * WEIGHTS.cacheRead + m.fork.tailWrite * WEIGHTS.cacheWrite;
|
|
16
|
+
for (let n = 1; n <= max; n++) {
|
|
17
|
+
if (fixed + n * perFork <= (1 + BREAK_EVEN_TOLERANCE) * n * noBase)
|
|
18
|
+
return n;
|
|
19
|
+
}
|
|
20
|
+
return max;
|
|
21
|
+
}
|
|
22
|
+
let cached;
|
|
23
|
+
export function loadMeasured() {
|
|
24
|
+
if (process.env.FABER_CACHE_MEASURED) {
|
|
25
|
+
return JSON.parse(fs.readFileSync(process.env.FABER_CACHE_MEASURED, 'utf8'));
|
|
26
|
+
}
|
|
27
|
+
if (cached)
|
|
28
|
+
return cached;
|
|
29
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
30
|
+
cached = JSON.parse(fs.readFileSync(path.resolve(here, '../../data/measured-modes.json'), 'utf8'));
|
|
31
|
+
return cached;
|
|
32
|
+
}
|
|
33
|
+
export function measuredMode(engine, mode) {
|
|
34
|
+
return loadMeasured()[engine]?.[mode];
|
|
35
|
+
}
|
|
36
|
+
/** Defaults for an unmeasured mode: assume a warm-up is needed and a base pays from 2 uses. */
|
|
37
|
+
export function modePolicy(engine, mode) {
|
|
38
|
+
const m = measuredMode(engine, mode);
|
|
39
|
+
if (!m)
|
|
40
|
+
return { needsWarmup: true, breakEven: 2, measured: false };
|
|
41
|
+
return { needsWarmup: m.needsWarmup, breakEven: breakEven(m), measured: true };
|
|
42
|
+
}
|
|
43
|
+
export function major(version) {
|
|
44
|
+
return version.split('.')[0] ?? version;
|
|
45
|
+
}
|
|
46
|
+
/** Whether a mode has a completed measurement that passed the read-share bar (FR-11.3, FR-07.3). */
|
|
47
|
+
export function isModeVerified(engine, mode, bar = 0.9) {
|
|
48
|
+
const m = measuredMode(engine, mode);
|
|
49
|
+
return Boolean(m && m.complete && m.readShare >= bar);
|
|
50
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { Config } from './config.js';
|
|
2
|
+
export declare const READY_LINE = "Reply with the single word: ready";
|
|
3
|
+
export interface PacketFile {
|
|
4
|
+
/** The name as configured (relative or `~/`), never an absolute machine path. */
|
|
5
|
+
label: string;
|
|
6
|
+
bytes: number;
|
|
7
|
+
sha: string;
|
|
8
|
+
content: string;
|
|
9
|
+
}
|
|
10
|
+
export interface Packet {
|
|
11
|
+
files: PacketFile[];
|
|
12
|
+
/** The packet as the first message, without the ready line or a task. */
|
|
13
|
+
text: string;
|
|
14
|
+
bytes: number;
|
|
15
|
+
}
|
|
16
|
+
export declare class PacketError extends Error {
|
|
17
|
+
readonly details: string[];
|
|
18
|
+
constructor(message: string, details?: string[]);
|
|
19
|
+
}
|
|
20
|
+
export declare function sha256(text: string): string;
|
|
21
|
+
/**
|
|
22
|
+
* The project's packet: its files in order (FR-01.1), refused when over the size limit or when a
|
|
23
|
+
* file holds a secret or a machine path (FR-01.5, FR-10.1). Nothing is sent before this passes.
|
|
24
|
+
*/
|
|
25
|
+
export declare function buildPacket(config: Config, projectDir: string): Packet;
|
|
26
|
+
/** The base's first message: the packet, then the fixed ready line. */
|
|
27
|
+
export declare function baseMessage(packet: Packet): string;
|
|
28
|
+
/** A run with no base: the packet in front of the task, in one message. */
|
|
29
|
+
export declare function packetInFront(packet: Packet, task: string): string;
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import * as crypto from 'node:crypto';
|
|
2
|
+
import * as fs from 'node:fs';
|
|
3
|
+
import * as path from 'node:path';
|
|
4
|
+
import { DEFAULT_PACKET, expandHome, projectConfig } from './config.js';
|
|
5
|
+
import { scanHygiene } from './hygiene.js';
|
|
6
|
+
export const READY_LINE = 'Reply with the single word: ready';
|
|
7
|
+
export class PacketError extends Error {
|
|
8
|
+
details;
|
|
9
|
+
constructor(message, details = []) {
|
|
10
|
+
super(details.length ? `${message}\n${details.map((d) => ` ${d}`).join('\n')}` : message);
|
|
11
|
+
this.details = details;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
export function sha256(text) {
|
|
15
|
+
return crypto.createHash('sha256').update(text).digest('hex');
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* The project's packet: its files in order (FR-01.1), refused when over the size limit or when a
|
|
19
|
+
* file holds a secret or a machine path (FR-01.5, FR-10.1). Nothing is sent before this passes.
|
|
20
|
+
*/
|
|
21
|
+
export function buildPacket(config, projectDir) {
|
|
22
|
+
const configured = projectConfig(config, projectDir).packet;
|
|
23
|
+
const names = configured ?? DEFAULT_PACKET;
|
|
24
|
+
const files = [];
|
|
25
|
+
for (const label of names) {
|
|
26
|
+
const full = path.resolve(projectDir, expandHome(label));
|
|
27
|
+
let content;
|
|
28
|
+
try {
|
|
29
|
+
content = fs.readFileSync(full, 'utf8');
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
if (configured)
|
|
33
|
+
throw new PacketError(`packet file not found: ${label}`);
|
|
34
|
+
continue;
|
|
35
|
+
}
|
|
36
|
+
files.push({ label, bytes: Buffer.byteLength(content), sha: sha256(content), content });
|
|
37
|
+
}
|
|
38
|
+
if (files.length === 0)
|
|
39
|
+
throw new PacketError('the packet is empty: no packet file was found');
|
|
40
|
+
const bytes = files.reduce((n, f) => n + f.bytes, 0);
|
|
41
|
+
if (bytes > config.limits.maxPacketBytes) {
|
|
42
|
+
throw new PacketError(`packet is ${bytes} bytes, over the limit of ${config.limits.maxPacketBytes}`, files.map((f) => `${f.label}: ${f.bytes} bytes`));
|
|
43
|
+
}
|
|
44
|
+
const findings = [];
|
|
45
|
+
for (const f of files) {
|
|
46
|
+
for (const h of scanHygiene(f.content))
|
|
47
|
+
findings.push(formatFinding(f.label, h));
|
|
48
|
+
}
|
|
49
|
+
if (findings.length)
|
|
50
|
+
throw new PacketError('packet refused by the secret and machine-path scan', findings);
|
|
51
|
+
const text = files.map((f) => `===== ${f.label} =====\n${f.content.trimEnd()}\n`).join('\n');
|
|
52
|
+
return { files, text, bytes };
|
|
53
|
+
}
|
|
54
|
+
function formatFinding(label, h) {
|
|
55
|
+
return `${label} line ${h.line} [${h.category}/${h.pattern}]: ${h.redactedSnippet}`;
|
|
56
|
+
}
|
|
57
|
+
/** The base's first message: the packet, then the fixed ready line. */
|
|
58
|
+
export function baseMessage(packet) {
|
|
59
|
+
return `${packet.text}\n${READY_LINE}`;
|
|
60
|
+
}
|
|
61
|
+
/** A run with no base: the packet in front of the task, in one message. */
|
|
62
|
+
export function packetInFront(packet, task) {
|
|
63
|
+
return `${packet.text}\n${task}`;
|
|
64
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
export type RecordKind = 'build' | 'warmup' | 'run' | 'open';
|
|
2
|
+
export interface Usage {
|
|
3
|
+
input: number;
|
|
4
|
+
cacheWrite: number;
|
|
5
|
+
/** The part of cacheWrite written with the one-hour lifetime, when the engine says. */
|
|
6
|
+
cacheWrite1h?: number;
|
|
7
|
+
cacheRead: number;
|
|
8
|
+
output: number;
|
|
9
|
+
}
|
|
10
|
+
/** One JSON line per build, warm-up, run and open (FR-09.1). */
|
|
11
|
+
export interface RunRecord {
|
|
12
|
+
at: string;
|
|
13
|
+
kind: RecordKind;
|
|
14
|
+
project: string;
|
|
15
|
+
profile: string;
|
|
16
|
+
mode: string;
|
|
17
|
+
engine: string;
|
|
18
|
+
engineVersion: string;
|
|
19
|
+
model: string;
|
|
20
|
+
/** The tool set the run had (`all` for the engine's default). */
|
|
21
|
+
tools: string;
|
|
22
|
+
key: string;
|
|
23
|
+
/** Session forked from (base or warm), when any. */
|
|
24
|
+
fromSession: string | null;
|
|
25
|
+
session: string | null;
|
|
26
|
+
/** with-base | no-base | lock-timeout | warmup-failed (for runs). */
|
|
27
|
+
base: string;
|
|
28
|
+
first: Usage | null;
|
|
29
|
+
total: Usage | null;
|
|
30
|
+
refPrefix: number | null;
|
|
31
|
+
readShare: number | null;
|
|
32
|
+
/**
|
|
33
|
+
* The run's cost as the engine reports it (US dollars). Kept only for runs that resume nothing
|
|
34
|
+
* (builds, runs with no base): Claude Code adds the parent session's cost to a fork's total.
|
|
35
|
+
*/
|
|
36
|
+
costUsd?: number | null;
|
|
37
|
+
/** The fork's own tokens: input + cache write of its first request (FR-09.5). */
|
|
38
|
+
ownTokens: number | null;
|
|
39
|
+
cacheMiss: boolean;
|
|
40
|
+
outcome: 'ok' | 'error' | 'stopped';
|
|
41
|
+
error?: string;
|
|
42
|
+
attempt?: number;
|
|
43
|
+
task?: string;
|
|
44
|
+
unverified?: boolean;
|
|
45
|
+
note?: string;
|
|
46
|
+
}
|
|
47
|
+
export declare function recordsDir(home: string): string;
|
|
48
|
+
export declare function appendRecord(home: string, rec: RunRecord): void;
|
|
49
|
+
export declare function readRecords(home: string): RunRecord[];
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import * as fs from 'node:fs';
|
|
2
|
+
import * as path from 'node:path';
|
|
3
|
+
export function recordsDir(home) {
|
|
4
|
+
return path.join(home, 'records');
|
|
5
|
+
}
|
|
6
|
+
export function appendRecord(home, rec) {
|
|
7
|
+
const dir = recordsDir(home);
|
|
8
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
9
|
+
const file = path.join(dir, `${rec.at.slice(0, 7)}.jsonl`);
|
|
10
|
+
fs.appendFileSync(file, JSON.stringify(rec) + '\n');
|
|
11
|
+
}
|
|
12
|
+
export function readRecords(home) {
|
|
13
|
+
const dir = recordsDir(home);
|
|
14
|
+
let names = [];
|
|
15
|
+
try {
|
|
16
|
+
names = fs.readdirSync(dir).filter((n) => n.endsWith('.jsonl')).sort();
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
return [];
|
|
20
|
+
}
|
|
21
|
+
const out = [];
|
|
22
|
+
for (const n of names) {
|
|
23
|
+
for (const line of fs.readFileSync(path.join(dir, n), 'utf8').split('\n')) {
|
|
24
|
+
if (!line.trim())
|
|
25
|
+
continue;
|
|
26
|
+
try {
|
|
27
|
+
out.push(JSON.parse(line));
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
// A torn line is skipped.
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
return out;
|
|
35
|
+
}
|