@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
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { Profile } from '../config.js';
|
|
2
|
+
import { EngineRun, EngineStatus, RunOptions } from './claude.js';
|
|
3
|
+
export declare const UNVERIFIED_MESSAGE = "unverified: no cache saving promised";
|
|
4
|
+
export declare function agyBin(): string;
|
|
5
|
+
export declare function agyVersion(): string | null;
|
|
6
|
+
export declare function resetAgyVersionCache(): void;
|
|
7
|
+
export declare function agyStatus(): EngineStatus;
|
|
8
|
+
export declare function agyKeyBits(): {
|
|
9
|
+
settingSources: string;
|
|
10
|
+
excludeDynamic: boolean;
|
|
11
|
+
systemPromptSha: string | null;
|
|
12
|
+
};
|
|
13
|
+
/** CLI arguments for one headless `agy` run in prefix mode (FR-07.3, FR-10.2). */
|
|
14
|
+
export declare function agyArgs(opts: Pick<RunOptions, 'profile' | 'model'>): string[];
|
|
15
|
+
/** One headless `agy` call; sends the prompt as a stream-json user message on stdin. */
|
|
16
|
+
export declare function runAgy(opts: RunOptions): Promise<EngineRun>;
|
|
17
|
+
export type AgyProfile = Profile;
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
2
|
+
import { BYPASS_MODE } from '../config.js';
|
|
3
|
+
import { currentDepth, DEPTH_ENV } from './claude.js';
|
|
4
|
+
export const UNVERIFIED_MESSAGE = 'unverified: no cache saving promised';
|
|
5
|
+
export function agyBin() {
|
|
6
|
+
return process.env.FABER_CACHE_AGY_BIN || 'agy';
|
|
7
|
+
}
|
|
8
|
+
let versionCache;
|
|
9
|
+
export function agyVersion() {
|
|
10
|
+
if (versionCache !== undefined)
|
|
11
|
+
return versionCache;
|
|
12
|
+
const out = spawnSync(agyBin(), ['--version'], { encoding: 'utf8' });
|
|
13
|
+
if (out.error || out.status !== 0) {
|
|
14
|
+
versionCache = null;
|
|
15
|
+
}
|
|
16
|
+
else {
|
|
17
|
+
versionCache = (out.stdout.match(/\d+\.\d+\.\d+/) ?? [out.stdout.trim()])[0] || null;
|
|
18
|
+
}
|
|
19
|
+
return versionCache;
|
|
20
|
+
}
|
|
21
|
+
export function resetAgyVersionCache() {
|
|
22
|
+
versionCache = undefined;
|
|
23
|
+
}
|
|
24
|
+
export function agyStatus() {
|
|
25
|
+
const version = agyVersion();
|
|
26
|
+
if (!version) {
|
|
27
|
+
return { engine: 'agy', installed: false, version: null, loggedIn: null, message: 'not installed: install Antigravity CLI (`agy`)' };
|
|
28
|
+
}
|
|
29
|
+
return { engine: 'agy', installed: true, version, loggedIn: null, message: 'ok (prefix mode)' };
|
|
30
|
+
}
|
|
31
|
+
export function agyKeyBits() {
|
|
32
|
+
return { settingSources: 'agy', excludeDynamic: false, systemPromptSha: null };
|
|
33
|
+
}
|
|
34
|
+
/** CLI arguments for one headless `agy` run in prefix mode (FR-07.3, FR-10.2). */
|
|
35
|
+
export function agyArgs(opts) {
|
|
36
|
+
const args = ['--input-format', 'stream-json', '--output-format', 'stream-json', '--disable-slash-commands'];
|
|
37
|
+
if (opts.model && opts.model !== 'default')
|
|
38
|
+
args.push('--model', opts.model);
|
|
39
|
+
if (opts.profile.permissionMode === BYPASS_MODE) {
|
|
40
|
+
args.push('--dangerously-skip-permissions');
|
|
41
|
+
}
|
|
42
|
+
else if (opts.profile.permissionMode === 'acceptEdits') {
|
|
43
|
+
args.push('--mode', 'accept-edits');
|
|
44
|
+
}
|
|
45
|
+
else if (opts.profile.permissionMode === 'dontAsk') {
|
|
46
|
+
args.push('--mode', 'plan', '--settings', JSON.stringify({ permissions: { allow: ['read_file(*)'] } }));
|
|
47
|
+
}
|
|
48
|
+
return args;
|
|
49
|
+
}
|
|
50
|
+
function usageOfAgy(u) {
|
|
51
|
+
if (!u)
|
|
52
|
+
return null;
|
|
53
|
+
return {
|
|
54
|
+
input: Number(u.input_tokens ?? 0),
|
|
55
|
+
cacheWrite: 0,
|
|
56
|
+
cacheRead: Number(u.cache_read_tokens ?? 0),
|
|
57
|
+
output: Number(u.output_tokens ?? 0),
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
/** One headless `agy` call; sends the prompt as a stream-json user message on stdin. */
|
|
61
|
+
export function runAgy(opts) {
|
|
62
|
+
return new Promise((resolve) => {
|
|
63
|
+
const child = spawn(agyBin(), agyArgs(opts), {
|
|
64
|
+
cwd: opts.cwd,
|
|
65
|
+
env: { ...process.env, [DEPTH_ENV]: String(currentDepth() + 1) },
|
|
66
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
67
|
+
});
|
|
68
|
+
if (child.pid)
|
|
69
|
+
opts.onSpawn?.(child.pid);
|
|
70
|
+
let buf = '';
|
|
71
|
+
let stderr = '';
|
|
72
|
+
let first = null;
|
|
73
|
+
const seen = new Set();
|
|
74
|
+
let initSession = null;
|
|
75
|
+
let result = null;
|
|
76
|
+
let turns = 0;
|
|
77
|
+
let stopped = false;
|
|
78
|
+
let stopReason = '';
|
|
79
|
+
const stop = (why) => {
|
|
80
|
+
if (stopped)
|
|
81
|
+
return;
|
|
82
|
+
stopped = true;
|
|
83
|
+
stopReason = why;
|
|
84
|
+
child.kill('SIGTERM');
|
|
85
|
+
setTimeout(() => child.exitCode === null && child.kill('SIGKILL'), 2000).unref();
|
|
86
|
+
};
|
|
87
|
+
const onAbort = () => stop('stopped');
|
|
88
|
+
if (opts.signal?.aborted)
|
|
89
|
+
onAbort();
|
|
90
|
+
opts.signal?.addEventListener('abort', onAbort, { once: true });
|
|
91
|
+
const onLine = (line) => {
|
|
92
|
+
if (!line.trim())
|
|
93
|
+
return;
|
|
94
|
+
let ev;
|
|
95
|
+
try {
|
|
96
|
+
ev = JSON.parse(line);
|
|
97
|
+
}
|
|
98
|
+
catch {
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
if (ev.event === 'init') {
|
|
102
|
+
if (typeof ev.conversation_id === 'string' && ev.conversation_id)
|
|
103
|
+
initSession = ev.conversation_id;
|
|
104
|
+
}
|
|
105
|
+
else if (ev.event === 'step_update') {
|
|
106
|
+
const su = ev.step_update;
|
|
107
|
+
if (su?.step_type === 'agent_response') {
|
|
108
|
+
const idx = typeof su.step_index === 'number' ? su.step_index : seen.size;
|
|
109
|
+
seen.add(idx);
|
|
110
|
+
turns = seen.size;
|
|
111
|
+
if (su.state === 'DONE' && su.usage && first === null) {
|
|
112
|
+
first = usageOfAgy(su.usage);
|
|
113
|
+
}
|
|
114
|
+
if (opts.maxTurns && turns > opts.maxTurns)
|
|
115
|
+
stop(`stopped after ${opts.maxTurns} turns`);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
else if (ev.event === 'result') {
|
|
119
|
+
const r = ev.result;
|
|
120
|
+
if (r && typeof r === 'object')
|
|
121
|
+
result = r;
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
child.stdout.setEncoding('utf8');
|
|
125
|
+
child.stdout.on('data', (chunk) => {
|
|
126
|
+
buf += chunk;
|
|
127
|
+
let i;
|
|
128
|
+
while ((i = buf.indexOf('\n')) >= 0) {
|
|
129
|
+
onLine(buf.slice(0, i));
|
|
130
|
+
buf = buf.slice(i + 1);
|
|
131
|
+
}
|
|
132
|
+
});
|
|
133
|
+
child.stderr.setEncoding('utf8');
|
|
134
|
+
child.stderr.on('data', (c) => (stderr += c));
|
|
135
|
+
child.on('error', (err) => {
|
|
136
|
+
opts.signal?.removeEventListener('abort', onAbort);
|
|
137
|
+
resolve({ reply: '', session: null, first: null, total: null, turns, ok: false, error: `cannot start ${agyBin()}: ${err.message}`, resumeError: false, stopped: false });
|
|
138
|
+
});
|
|
139
|
+
child.on('close', (code) => {
|
|
140
|
+
opts.signal?.removeEventListener('abort', onAbort);
|
|
141
|
+
onLine(buf);
|
|
142
|
+
const r = result;
|
|
143
|
+
const status = typeof r?.status === 'string' ? r.status : '';
|
|
144
|
+
const isError = stopped || !r || (status !== '' && status !== 'SUCCESS') || code !== 0;
|
|
145
|
+
const total = usageOfAgy(r?.usage);
|
|
146
|
+
const numTurns = Number(r?.num_turns ?? turns) || turns;
|
|
147
|
+
if (first === null && total !== null && numTurns <= 1)
|
|
148
|
+
first = total;
|
|
149
|
+
const errText = typeof r?.error === 'string'
|
|
150
|
+
? r.error
|
|
151
|
+
: typeof r?.message === 'string'
|
|
152
|
+
? r.message
|
|
153
|
+
: status && status !== 'SUCCESS'
|
|
154
|
+
? `agy status ${status}`
|
|
155
|
+
: '';
|
|
156
|
+
const message = stopped
|
|
157
|
+
? stopReason
|
|
158
|
+
: errText || stderr.trim() || (r ? '' : `no result from the engine (exit ${code})`);
|
|
159
|
+
resolve({
|
|
160
|
+
reply: r && !isError ? String(r.response ?? '') : '',
|
|
161
|
+
session: (typeof r?.conversation_id === 'string' && r.conversation_id) || initSession,
|
|
162
|
+
first,
|
|
163
|
+
total,
|
|
164
|
+
turns: numTurns,
|
|
165
|
+
ok: !isError,
|
|
166
|
+
error: isError ? message.slice(0, 2000) : undefined,
|
|
167
|
+
resumeError: false,
|
|
168
|
+
stopped,
|
|
169
|
+
});
|
|
170
|
+
});
|
|
171
|
+
child.stdin.on('error', () => undefined);
|
|
172
|
+
const payload = JSON.stringify({ event: 'user', message: { content: opts.stdin } }) + '\n';
|
|
173
|
+
child.stdin.end(payload);
|
|
174
|
+
});
|
|
175
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { Profile } from '../config.js';
|
|
2
|
+
import { Usage } from '../records.js';
|
|
3
|
+
export type Mode = 'fixed' | 'default' | 'prefix';
|
|
4
|
+
export declare const FIXED_SYSTEM_PROMPT: string;
|
|
5
|
+
export declare const WARMUP_MESSAGE = "Reply with the single word: ok";
|
|
6
|
+
export declare const DEPTH_ENV = "FABER_CACHE_DEPTH";
|
|
7
|
+
export interface EngineRun {
|
|
8
|
+
reply: string;
|
|
9
|
+
session: string | null;
|
|
10
|
+
first: Usage | null;
|
|
11
|
+
total: Usage | null;
|
|
12
|
+
turns: number;
|
|
13
|
+
/** The run's cost as the engine reports it, in US dollars; for a fork it includes the parent's cost. */
|
|
14
|
+
costUsd?: number | null;
|
|
15
|
+
ok: boolean;
|
|
16
|
+
error?: string;
|
|
17
|
+
resumeError: boolean;
|
|
18
|
+
stopped: boolean;
|
|
19
|
+
}
|
|
20
|
+
export interface RunOptions {
|
|
21
|
+
engine?: string;
|
|
22
|
+
mode: Mode;
|
|
23
|
+
profile: Profile;
|
|
24
|
+
model: string;
|
|
25
|
+
cwd: string;
|
|
26
|
+
stdin: string;
|
|
27
|
+
resume?: string;
|
|
28
|
+
maxTurns?: number;
|
|
29
|
+
signal?: AbortSignal;
|
|
30
|
+
/** Called with the child's PID once it starts (tests, MCP clean-up). */
|
|
31
|
+
onSpawn?: (pid: number) => void;
|
|
32
|
+
}
|
|
33
|
+
export interface EngineStatus {
|
|
34
|
+
engine: string;
|
|
35
|
+
installed: boolean;
|
|
36
|
+
version: string | null;
|
|
37
|
+
loggedIn: boolean | null;
|
|
38
|
+
message: string;
|
|
39
|
+
}
|
|
40
|
+
export declare function claudeBin(): string;
|
|
41
|
+
export declare function currentDepth(): number;
|
|
42
|
+
export declare function claudeVersion(): string | null;
|
|
43
|
+
export declare function resetVersionCache(): void;
|
|
44
|
+
export declare function claudeStatus(): EngineStatus;
|
|
45
|
+
/** Whether per-machine sections are moved out of the system prompt (FR-01.3, FR-01.6). */
|
|
46
|
+
export declare function excludeDynamicOn(): boolean;
|
|
47
|
+
/** A reason the mode cannot run, or null. */
|
|
48
|
+
export declare function modeRefusal(mode: Mode): string | null;
|
|
49
|
+
export declare function keyBits(mode: Mode): {
|
|
50
|
+
settingSources: string;
|
|
51
|
+
excludeDynamic: boolean;
|
|
52
|
+
systemPromptSha: string | null;
|
|
53
|
+
};
|
|
54
|
+
/** Arguments shared by headless runs and the interactive open, so the prefix stays identical. */
|
|
55
|
+
export declare function sessionArgs(mode: Mode, profile: Profile, model: string): string[];
|
|
56
|
+
export declare function headlessArgs(opts: Pick<RunOptions, 'mode' | 'profile' | 'model' | 'resume'>): string[];
|
|
57
|
+
/** The interactive fork of a warm session (FR-06.1). */
|
|
58
|
+
export declare function openArgs(mode: Mode, profile: Profile, model: string, session: string): string[];
|
|
59
|
+
/** One headless `claude -p` call; the first request's usage comes from the first assistant event. */
|
|
60
|
+
export declare function runClaude(opts: RunOptions): Promise<EngineRun>;
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
2
|
+
import * as fs from 'node:fs';
|
|
3
|
+
import * as os from 'node:os';
|
|
4
|
+
import * as path from 'node:path';
|
|
5
|
+
import { sha256 } from '../packet.js';
|
|
6
|
+
export const FIXED_SYSTEM_PROMPT = 'You are a careful software assistant working on one task at a time in this project. ' +
|
|
7
|
+
'The first message holds the project background; read it, then do the task you are given.';
|
|
8
|
+
export const WARMUP_MESSAGE = 'Reply with the single word: ok';
|
|
9
|
+
export const DEPTH_ENV = 'FABER_CACHE_DEPTH';
|
|
10
|
+
export function claudeBin() {
|
|
11
|
+
return process.env.FABER_CACHE_CLAUDE_BIN || 'claude';
|
|
12
|
+
}
|
|
13
|
+
export function currentDepth() {
|
|
14
|
+
return Number(process.env[DEPTH_ENV] || 0) || 0;
|
|
15
|
+
}
|
|
16
|
+
let versionCache;
|
|
17
|
+
export function claudeVersion() {
|
|
18
|
+
if (versionCache !== undefined)
|
|
19
|
+
return versionCache;
|
|
20
|
+
const out = spawnSync(claudeBin(), ['--version'], { encoding: 'utf8' });
|
|
21
|
+
if (out.error || out.status !== 0) {
|
|
22
|
+
versionCache = null;
|
|
23
|
+
}
|
|
24
|
+
else {
|
|
25
|
+
versionCache = (out.stdout.match(/\d+\.\d+\.\d+/) ?? [out.stdout.trim()])[0] || null;
|
|
26
|
+
}
|
|
27
|
+
return versionCache;
|
|
28
|
+
}
|
|
29
|
+
export function resetVersionCache() {
|
|
30
|
+
versionCache = undefined;
|
|
31
|
+
}
|
|
32
|
+
export function claudeStatus() {
|
|
33
|
+
const version = claudeVersion();
|
|
34
|
+
if (!version) {
|
|
35
|
+
return { engine: 'claude', installed: false, version: null, loggedIn: null, message: 'not installed: install Claude Code, then run `claude auth login`' };
|
|
36
|
+
}
|
|
37
|
+
const out = spawnSync(claudeBin(), ['auth', 'status'], { encoding: 'utf8' });
|
|
38
|
+
let loggedIn = null;
|
|
39
|
+
try {
|
|
40
|
+
loggedIn = Boolean(JSON.parse(out.stdout).loggedIn);
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
loggedIn = out.status === 0 ? null : false;
|
|
44
|
+
}
|
|
45
|
+
return {
|
|
46
|
+
engine: 'claude',
|
|
47
|
+
installed: true,
|
|
48
|
+
version,
|
|
49
|
+
loggedIn,
|
|
50
|
+
message: loggedIn === false ? 'logged out: run `claude auth login`' : loggedIn ? 'ok' : 'login state unknown',
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
function claudeConfigDir() {
|
|
54
|
+
return process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude');
|
|
55
|
+
}
|
|
56
|
+
/** Whether per-machine sections are moved out of the system prompt (FR-01.3, FR-01.6). */
|
|
57
|
+
export function excludeDynamicOn() {
|
|
58
|
+
try {
|
|
59
|
+
const raw = JSON.parse(fs.readFileSync(path.join(claudeConfigDir(), 'settings.json'), 'utf8'));
|
|
60
|
+
return raw.excludeDynamicSystemPromptSections === true;
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
return false;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
/** A reason the mode cannot run, or null. */
|
|
67
|
+
export function modeRefusal(mode) {
|
|
68
|
+
if (mode === 'default' && !excludeDynamicOn()) {
|
|
69
|
+
return 'default-prompt mode needs `"excludeDynamicSystemPromptSections": true` in the Claude Code user settings (~/.claude/settings.json); without it the folder, date and git status sit in the system prompt and every fork misses the cache';
|
|
70
|
+
}
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
export function keyBits(mode) {
|
|
74
|
+
return mode === 'fixed'
|
|
75
|
+
? { settingSources: '', excludeDynamic: false, systemPromptSha: sha256(FIXED_SYSTEM_PROMPT).slice(0, 16) }
|
|
76
|
+
: { settingSources: 'user,project,local', excludeDynamic: excludeDynamicOn(), systemPromptSha: null };
|
|
77
|
+
}
|
|
78
|
+
/** Arguments shared by headless runs and the interactive open, so the prefix stays identical. */
|
|
79
|
+
export function sessionArgs(mode, profile, model) {
|
|
80
|
+
const args = [];
|
|
81
|
+
if (model && model !== 'default')
|
|
82
|
+
args.push('--model', model);
|
|
83
|
+
if (mode === 'fixed')
|
|
84
|
+
args.push('--system-prompt', FIXED_SYSTEM_PROMPT, '--setting-sources', '', '--strict-mcp-config');
|
|
85
|
+
if (profile.tools)
|
|
86
|
+
args.push('--tools', profile.tools.join(','));
|
|
87
|
+
if (profile.permissionMode)
|
|
88
|
+
args.push('--permission-mode', profile.permissionMode);
|
|
89
|
+
return args;
|
|
90
|
+
}
|
|
91
|
+
export function headlessArgs(opts) {
|
|
92
|
+
const args = ['-p', '--output-format', 'stream-json', '--verbose', ...sessionArgs(opts.mode, opts.profile, opts.model)];
|
|
93
|
+
if (opts.resume)
|
|
94
|
+
args.push('--resume', opts.resume, '--fork-session');
|
|
95
|
+
return args;
|
|
96
|
+
}
|
|
97
|
+
/** The interactive fork of a warm session (FR-06.1). */
|
|
98
|
+
export function openArgs(mode, profile, model, session) {
|
|
99
|
+
return [...sessionArgs(mode, profile, model), '--resume', session, '--fork-session'];
|
|
100
|
+
}
|
|
101
|
+
function usageOf(u) {
|
|
102
|
+
if (!u)
|
|
103
|
+
return null;
|
|
104
|
+
return {
|
|
105
|
+
input: Number(u.input_tokens ?? 0),
|
|
106
|
+
cacheWrite: Number(u.cache_creation_input_tokens ?? 0),
|
|
107
|
+
...(typeof u.cache_creation?.ephemeral_1h_input_tokens === 'number'
|
|
108
|
+
? { cacheWrite1h: Number(u.cache_creation.ephemeral_1h_input_tokens) }
|
|
109
|
+
: {}),
|
|
110
|
+
cacheRead: Number(u.cache_read_input_tokens ?? 0),
|
|
111
|
+
output: Number(u.output_tokens ?? 0),
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
/** One headless `claude -p` call; the first request's usage comes from the first assistant event. */
|
|
115
|
+
export function runClaude(opts) {
|
|
116
|
+
return new Promise((resolve) => {
|
|
117
|
+
const child = spawn(claudeBin(), headlessArgs(opts), {
|
|
118
|
+
cwd: opts.cwd,
|
|
119
|
+
env: { ...process.env, [DEPTH_ENV]: String(currentDepth() + 1) },
|
|
120
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
121
|
+
});
|
|
122
|
+
if (child.pid)
|
|
123
|
+
opts.onSpawn?.(child.pid);
|
|
124
|
+
let buf = '';
|
|
125
|
+
let stderr = '';
|
|
126
|
+
let first = null;
|
|
127
|
+
const seen = new Set();
|
|
128
|
+
let result = null;
|
|
129
|
+
let turns = 0;
|
|
130
|
+
let stopped = false;
|
|
131
|
+
let stopReason = '';
|
|
132
|
+
const stop = (why) => {
|
|
133
|
+
if (stopped)
|
|
134
|
+
return;
|
|
135
|
+
stopped = true;
|
|
136
|
+
stopReason = why;
|
|
137
|
+
child.kill('SIGTERM');
|
|
138
|
+
setTimeout(() => child.exitCode === null && child.kill('SIGKILL'), 2000).unref();
|
|
139
|
+
};
|
|
140
|
+
const onAbort = () => stop('stopped');
|
|
141
|
+
if (opts.signal?.aborted)
|
|
142
|
+
onAbort();
|
|
143
|
+
opts.signal?.addEventListener('abort', onAbort, { once: true });
|
|
144
|
+
const onLine = (line) => {
|
|
145
|
+
if (!line.trim())
|
|
146
|
+
return;
|
|
147
|
+
let ev;
|
|
148
|
+
try {
|
|
149
|
+
ev = JSON.parse(line);
|
|
150
|
+
}
|
|
151
|
+
catch {
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
if (ev.type === 'assistant') {
|
|
155
|
+
const msg = ev.message;
|
|
156
|
+
// One API request can stream several assistant events with the same message id.
|
|
157
|
+
const id = msg?.id ?? `turn-${seen.size}`;
|
|
158
|
+
if (!seen.has(id)) {
|
|
159
|
+
seen.add(id);
|
|
160
|
+
if (first === null)
|
|
161
|
+
first = usageOf(msg?.usage);
|
|
162
|
+
}
|
|
163
|
+
turns = seen.size;
|
|
164
|
+
if (opts.maxTurns && turns > opts.maxTurns)
|
|
165
|
+
stop(`stopped after ${opts.maxTurns} turns`);
|
|
166
|
+
}
|
|
167
|
+
else if (ev.type === 'result') {
|
|
168
|
+
result = ev;
|
|
169
|
+
}
|
|
170
|
+
};
|
|
171
|
+
child.stdout.setEncoding('utf8');
|
|
172
|
+
child.stdout.on('data', (chunk) => {
|
|
173
|
+
buf += chunk;
|
|
174
|
+
let i;
|
|
175
|
+
while ((i = buf.indexOf('\n')) >= 0) {
|
|
176
|
+
onLine(buf.slice(0, i));
|
|
177
|
+
buf = buf.slice(i + 1);
|
|
178
|
+
}
|
|
179
|
+
});
|
|
180
|
+
child.stderr.setEncoding('utf8');
|
|
181
|
+
child.stderr.on('data', (c) => (stderr += c));
|
|
182
|
+
child.on('error', (err) => {
|
|
183
|
+
opts.signal?.removeEventListener('abort', onAbort);
|
|
184
|
+
resolve({ reply: '', session: null, first: null, total: null, turns, ok: false, error: `cannot start ${claudeBin()}: ${err.message}`, resumeError: false, stopped: false });
|
|
185
|
+
});
|
|
186
|
+
child.on('close', (code) => {
|
|
187
|
+
opts.signal?.removeEventListener('abort', onAbort);
|
|
188
|
+
onLine(buf);
|
|
189
|
+
const r = result;
|
|
190
|
+
const errors = Array.isArray(r?.errors) ? (r?.errors).map(String).join('; ') : '';
|
|
191
|
+
const isError = stopped || !r || r.is_error === true || code !== 0;
|
|
192
|
+
const message = stopped
|
|
193
|
+
? stopReason
|
|
194
|
+
: errors || (r?.is_error ? String(r.result ?? '') : '') || stderr.trim() || (r ? '' : `no result from the engine (exit ${code})`);
|
|
195
|
+
resolve({
|
|
196
|
+
reply: r && !r.is_error ? String(r.result ?? '') : '',
|
|
197
|
+
session: r ? String(r.session_id ?? '') || null : null,
|
|
198
|
+
first,
|
|
199
|
+
total: usageOf(r?.usage),
|
|
200
|
+
turns,
|
|
201
|
+
costUsd: typeof r?.total_cost_usd === 'number' ? r.total_cost_usd : null,
|
|
202
|
+
ok: !isError,
|
|
203
|
+
error: isError ? message.slice(0, 2000) : undefined,
|
|
204
|
+
resumeError: /no conversation found/i.test(`${errors} ${stderr}`),
|
|
205
|
+
stopped,
|
|
206
|
+
});
|
|
207
|
+
});
|
|
208
|
+
child.stdin.on('error', () => undefined);
|
|
209
|
+
child.stdin.end(opts.stdin);
|
|
210
|
+
});
|
|
211
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
const SECRET_FIX = 'remove the value; store a pointer to where it lives instead';
|
|
2
|
+
const RULES = [
|
|
3
|
+
{
|
|
4
|
+
category: 'secret',
|
|
5
|
+
pattern: 'private-key',
|
|
6
|
+
regex: /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/,
|
|
7
|
+
label: 'Private key header detected',
|
|
8
|
+
fix: SECRET_FIX,
|
|
9
|
+
},
|
|
10
|
+
{
|
|
11
|
+
category: 'secret',
|
|
12
|
+
pattern: 'jwt',
|
|
13
|
+
regex: /\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/,
|
|
14
|
+
label: 'JWT token detected',
|
|
15
|
+
fix: SECRET_FIX,
|
|
16
|
+
},
|
|
17
|
+
{
|
|
18
|
+
category: 'secret',
|
|
19
|
+
pattern: 'bearer-token',
|
|
20
|
+
regex: /\bBearer\s+[A-Za-z0-9._~+/-]{12,}/i,
|
|
21
|
+
label: 'Bearer token detected',
|
|
22
|
+
fix: SECRET_FIX,
|
|
23
|
+
},
|
|
24
|
+
{
|
|
25
|
+
category: 'secret',
|
|
26
|
+
pattern: 'api-key-prefix',
|
|
27
|
+
regex: /\b(?:sk-[A-Za-z0-9_-]{16,}|sk_live_[A-Za-z0-9]{12,}|ghp_[A-Za-z0-9]{20,}|gho_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|AKIA[0-9A-Z]{16}|AIza[0-9A-Za-z_-]{30,}|xox[baprs]-[A-Za-z0-9-]{10,})\b/,
|
|
28
|
+
label: 'Known API key prefix detected',
|
|
29
|
+
fix: SECRET_FIX,
|
|
30
|
+
},
|
|
31
|
+
{
|
|
32
|
+
category: 'secret',
|
|
33
|
+
pattern: 'credential-assignment',
|
|
34
|
+
regex: /\b(?:api[_-]?key|secret[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|password|passwd)\s*[:=]\s*["']?[A-Za-z0-9._~+/=-]{12,}["']?/i,
|
|
35
|
+
label: 'Credential assignment detected',
|
|
36
|
+
fix: SECRET_FIX,
|
|
37
|
+
},
|
|
38
|
+
{
|
|
39
|
+
category: 'machine-path',
|
|
40
|
+
pattern: 'macos-user-path',
|
|
41
|
+
regex: /\/Users\/[A-Za-z0-9._-]+\//,
|
|
42
|
+
label: 'Machine-specific macOS home path detected',
|
|
43
|
+
fix: 'write ~/ or $HOME instead of /Users/<name>/',
|
|
44
|
+
},
|
|
45
|
+
{
|
|
46
|
+
category: 'machine-path',
|
|
47
|
+
pattern: 'linux-user-path',
|
|
48
|
+
regex: /\/home\/[A-Za-z0-9._-]+\//,
|
|
49
|
+
label: 'Machine-specific Linux home path detected',
|
|
50
|
+
fix: 'write ~/ or $HOME instead of /home/<name>/',
|
|
51
|
+
},
|
|
52
|
+
{
|
|
53
|
+
category: 'machine-path',
|
|
54
|
+
pattern: 'windows-user-path',
|
|
55
|
+
regex: /\b[A-Za-z]:\\Users\\[A-Za-z0-9._-]+\\/,
|
|
56
|
+
label: 'Machine-specific Windows home path detected',
|
|
57
|
+
fix: 'write ~\\ or %USERPROFILE% instead of C:\\Users\\<name>\\',
|
|
58
|
+
},
|
|
59
|
+
];
|
|
60
|
+
export function scanHygiene(content) {
|
|
61
|
+
const findings = [];
|
|
62
|
+
const lines = content.replace(/\r\n/g, '\n').split('\n');
|
|
63
|
+
for (let i = 0; i < lines.length; i++) {
|
|
64
|
+
const lineText = lines[i];
|
|
65
|
+
for (const rule of RULES) {
|
|
66
|
+
const match = rule.regex.exec(lineText);
|
|
67
|
+
if (match) {
|
|
68
|
+
const redactedSnippet = lineText
|
|
69
|
+
.replace(rule.regex, rule.category === 'secret' ? '[REDACTED]' : '[MACHINE_PATH]')
|
|
70
|
+
.trim()
|
|
71
|
+
.slice(0, 120);
|
|
72
|
+
findings.push({
|
|
73
|
+
line: i + 1,
|
|
74
|
+
category: rule.category,
|
|
75
|
+
pattern: rule.pattern,
|
|
76
|
+
message: `${rule.label} (${rule.category}/${rule.pattern}) at line ${i + 1}; fix: ${rule.fix}`,
|
|
77
|
+
redactedSnippet,
|
|
78
|
+
});
|
|
79
|
+
break;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return findings;
|
|
84
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export * from './config.js';
|
|
2
|
+
export * from './core.js';
|
|
3
|
+
export { buildPacket, PacketError } from './packet.js';
|
|
4
|
+
export type { Packet, PacketFile } from './packet.js';
|
|
5
|
+
export { computeStats } from './stats.js';
|
|
6
|
+
export { doctor } from './doctor.js';
|
|
7
|
+
export { breakEven, isModeVerified, modePolicy } from './measured.js';
|
|
8
|
+
export { agyStatus, agyVersion } from './engines/agy.js';
|
|
9
|
+
export type { RunRecord, Usage } from './records.js';
|
|
10
|
+
export type { BaseEntry } from './registry.js';
|
|
11
|
+
export { McpServer, MCP_TOOLS } from './mcp.js';
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export * from './config.js';
|
|
2
|
+
export * from './core.js';
|
|
3
|
+
export { buildPacket, PacketError } from './packet.js';
|
|
4
|
+
export { computeStats } from './stats.js';
|
|
5
|
+
export { doctor } from './doctor.js';
|
|
6
|
+
export { breakEven, isModeVerified, modePolicy } from './measured.js';
|
|
7
|
+
export { agyStatus, agyVersion } from './engines/agy.js';
|
|
8
|
+
export { McpServer, MCP_TOOLS } from './mcp.js';
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { Packet } from './packet.js';
|
|
2
|
+
/** Everything that changes the engine's prefix (FR-01.4). Any change gives a new key. */
|
|
3
|
+
export interface KeyParts {
|
|
4
|
+
engine: string;
|
|
5
|
+
engineVersion: string;
|
|
6
|
+
model: string;
|
|
7
|
+
mode: string;
|
|
8
|
+
profile: string;
|
|
9
|
+
tools: string[] | null;
|
|
10
|
+
permissionMode: string | null;
|
|
11
|
+
settingSources: string;
|
|
12
|
+
excludeDynamic: boolean;
|
|
13
|
+
systemPromptSha: string | null;
|
|
14
|
+
}
|
|
15
|
+
export declare function keyParts(parts: KeyParts, packet: Packet): Record<string, unknown>;
|
|
16
|
+
export declare function keyOf(parts: KeyParts, packet: Packet): string;
|
package/dist/src/key.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { sha256 } from './packet.js';
|
|
2
|
+
export function keyParts(parts, packet) {
|
|
3
|
+
return { ...parts, packet: packet.files.map((f) => `${f.label}:${f.sha}`) };
|
|
4
|
+
}
|
|
5
|
+
export function keyOf(parts, packet) {
|
|
6
|
+
return sha256(JSON.stringify(keyParts(parts, packet))).slice(0, 20);
|
|
7
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export declare function sleepSync(ms: number): void;
|
|
2
|
+
export declare function pidAlive(pid: number): boolean;
|
|
3
|
+
/** Try once to take a lock file; a lock whose process is gone is taken over (FR-03.5). */
|
|
4
|
+
export declare function tryLock(file: string): boolean;
|
|
5
|
+
export declare function unlock(file: string): void;
|
|
6
|
+
/** Wait for a lock up to `waitMs`; false on timeout. */
|
|
7
|
+
export declare function acquire(file: string, waitMs: number, pollMs?: number): Promise<boolean>;
|
|
8
|
+
/** A short, synchronous critical section (registry writes). */
|
|
9
|
+
export declare function withLockSync<T>(file: string, fn: () => T, waitMs?: number): T;
|