@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.
@@ -0,0 +1,84 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { agyStatus, agyVersion, UNVERIFIED_MESSAGE } from './engines/agy.js';
3
+ import { claudeStatus, claudeVersion, excludeDynamicOn } from './engines/claude.js';
4
+ import { loadConfig } from './config.js';
5
+ import { breakEven, loadMeasured, major } from './measured.js';
6
+ import { readRecords } from './records.js';
7
+ /** Engine adapters and their modes; Codex is planned for a later release. */
8
+ const MODES = [
9
+ { engine: 'claude', mode: 'fixed', note: 'headless runs' },
10
+ { engine: 'claude', mode: 'default', note: 'headless runs with --mode default' },
11
+ { engine: 'claude', mode: 'open', note: 'interactive open (OQ-04)' },
12
+ { engine: 'agy', mode: 'prefix', note: UNVERIFIED_MESSAGE },
13
+ { engine: 'codex', mode: 'fork', note: 'adapter planned for a later release' },
14
+ ];
15
+ function otherEngine(engine, bin) {
16
+ const out = spawnSync(bin, ['--version'], { encoding: 'utf8' });
17
+ if (out.error || out.status !== 0) {
18
+ return { engine, installed: false, version: null, loggedIn: null, message: 'not installed' };
19
+ }
20
+ const version = (out.stdout.match(/\d+\.\d+\.\d+/) ?? [out.stdout.trim()])[0];
21
+ return { engine, installed: true, version, loggedIn: null, message: 'installed; its adapter is planned for a later release' };
22
+ }
23
+ /** Compare a flagged run with the build of the base it forked (FR-09.4). */
24
+ function explainMiss(miss, all) {
25
+ let baseSession = miss.fromSession;
26
+ const warm = all.find((r) => r.kind === 'warmup' && r.session === miss.fromSession);
27
+ if (warm)
28
+ baseSession = warm.fromSession;
29
+ const build = all.find((r) => r.kind === 'build' && r.session === baseSession);
30
+ if (!build)
31
+ return ['the base build record is missing, so nothing could be compared'];
32
+ const differs = [];
33
+ const fields = [
34
+ ['tools', 'tool set'],
35
+ ['model', 'model'],
36
+ ['engineVersion', 'engine version'],
37
+ ['mode', 'mode'],
38
+ ['profile', 'profile'],
39
+ ['key', 'base key'],
40
+ ];
41
+ for (const [field, label] of fields) {
42
+ if (miss[field] !== build[field])
43
+ differs.push(`${label}: base ${String(build[field])}, run ${String(miss[field])}`);
44
+ }
45
+ if (!differs.length) {
46
+ differs.push('no recorded setting differs; look for a session-start hook or other text that lands before the base ends, or a base past its lifetime');
47
+ }
48
+ return differs;
49
+ }
50
+ export function doctor(home, bar = loadConfig(home).bar) {
51
+ const claude = claudeStatus();
52
+ const agy = agyStatus();
53
+ const engines = [claude, agy, otherEngine('codex', process.env.FABER_CACHE_CODEX_BIN || 'codex')];
54
+ const measured = loadMeasured();
55
+ const records = readRecords(home);
56
+ const currentByEngine = {
57
+ claude: claude.installed ? claudeVersion() : null,
58
+ agy: agy.installed ? agyVersion() : null,
59
+ };
60
+ const modes = MODES.map(({ engine, mode, note }) => {
61
+ const m = measured[engine]?.[mode];
62
+ if (!m)
63
+ return { engine, mode, state: 'unmeasured', needsWarmup: null, breakEven: null, measuredOn: null, note };
64
+ let state = m.complete ? (m.readShare < bar ? 'no cache guarantee' : 'measured') : 'partly measured';
65
+ let why = m.note ?? note;
66
+ const current = currentByEngine[engine] ?? null;
67
+ const missOnNewVersion = records.some((r) => r.engine === engine && r.mode === mode && r.cacheMiss && r.engineVersion !== m.engineVersion);
68
+ if (current && major(current) !== major(m.engineVersion)) {
69
+ state = 're-check';
70
+ why = `measured on ${m.engineVersion}, now ${current} (new major version)`;
71
+ }
72
+ else if (missOnNewVersion) {
73
+ const v = records.filter((r) => r.engine === engine && r.mode === mode && r.cacheMiss && r.engineVersion !== m.engineVersion).pop();
74
+ state = 're-check';
75
+ why = `runs on ${v?.engineVersion} read under the bar; measured on ${m.engineVersion}`;
76
+ }
77
+ return { engine, mode, state, needsWarmup: m.needsWarmup, breakEven: breakEven(m), measuredOn: `${m.date}, ${m.engineVersion}`, note: why };
78
+ });
79
+ const misses = records
80
+ .filter((r) => r.cacheMiss)
81
+ .slice(-20)
82
+ .map((r) => ({ at: r.at, project: r.project, key: r.key, readShare: r.readShare, differs: explainMiss(r, records) }));
83
+ return { engines, settings: { excludeDynamicSystemPromptSections: excludeDynamicOn() }, modes, misses };
84
+ }
@@ -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,67 @@
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
+ /**
46
+ * The latest activity (ms since epoch) of any Claude Code session forked from one of `sessions`
47
+ * in `projectDir`, or null. Every request of such a session reads the base's prefix and so keeps
48
+ * the engine's cache entry alive, though the registry never sees it. A fork's transcript names its
49
+ * ancestors in a `derived-from` record near the top; the file's mtime is its last request.
50
+ */
51
+ export declare function lastForkActivity(projectDir: string, sessions: string[], since?: number): number | null;
52
+ /** Whether per-machine sections are moved out of the system prompt (FR-01.3, FR-01.6). */
53
+ export declare function excludeDynamicOn(): boolean;
54
+ /** A reason the mode cannot run, or null. */
55
+ export declare function modeRefusal(mode: Mode): string | null;
56
+ export declare function keyBits(mode: Mode): {
57
+ settingSources: string;
58
+ excludeDynamic: boolean;
59
+ systemPromptSha: string | null;
60
+ };
61
+ /** Arguments shared by headless runs and the interactive open, so the prefix stays identical. */
62
+ export declare function sessionArgs(mode: Mode, profile: Profile, model: string): string[];
63
+ export declare function headlessArgs(opts: Pick<RunOptions, 'mode' | 'profile' | 'model' | 'resume'>): string[];
64
+ /** The interactive fork of a warm session (FR-06.1). */
65
+ export declare function openArgs(mode: Mode, profile: Profile, model: string, session: string): string[];
66
+ /** One headless `claude -p` call; the first request's usage comes from the first assistant event. */
67
+ export declare function runClaude(opts: RunOptions): Promise<EngineRun>;
@@ -0,0 +1,275 @@
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
+ /**
57
+ * The latest activity (ms since epoch) of any Claude Code session forked from one of `sessions`
58
+ * in `projectDir`, or null. Every request of such a session reads the base's prefix and so keeps
59
+ * the engine's cache entry alive, though the registry never sees it. A fork's transcript names its
60
+ * ancestors in a `derived-from` record near the top; the file's mtime is its last request.
61
+ */
62
+ export function lastForkActivity(projectDir, sessions, since = 0) {
63
+ if (sessions.length === 0)
64
+ return null;
65
+ const dir = path.join(claudeConfigDir(), 'projects', projectDir.replace(/[^a-zA-Z0-9]/g, '-'));
66
+ let names;
67
+ try {
68
+ names = fs.readdirSync(dir).filter((n) => n.endsWith('.jsonl'));
69
+ }
70
+ catch {
71
+ return null;
72
+ }
73
+ let latest = null;
74
+ for (const name of names) {
75
+ const file = path.join(dir, name);
76
+ let mtime;
77
+ try {
78
+ mtime = fs.statSync(file).mtimeMs;
79
+ }
80
+ catch {
81
+ continue;
82
+ }
83
+ if (mtime <= since || (latest !== null && mtime <= latest))
84
+ continue;
85
+ if (derivedFromAny(file, sessions))
86
+ latest = mtime;
87
+ }
88
+ return latest;
89
+ }
90
+ function derivedFromAny(file, sessions) {
91
+ let head;
92
+ try {
93
+ const fd = fs.openSync(file, 'r');
94
+ try {
95
+ const buf = Buffer.alloc(16 * 1024);
96
+ head = buf.toString('utf8', 0, fs.readSync(fd, buf, 0, buf.length, 0));
97
+ }
98
+ finally {
99
+ fs.closeSync(fd);
100
+ }
101
+ }
102
+ catch {
103
+ return false;
104
+ }
105
+ for (const line of head.split('\n')) {
106
+ if (!line.includes('"derived-from"'))
107
+ continue;
108
+ try {
109
+ const rec = JSON.parse(line);
110
+ if (rec.type !== 'derived-from')
111
+ continue;
112
+ return (rec.sessions ?? []).some((s) => s.id !== undefined && sessions.includes(s.id));
113
+ }
114
+ catch {
115
+ continue;
116
+ }
117
+ }
118
+ return false;
119
+ }
120
+ /** Whether per-machine sections are moved out of the system prompt (FR-01.3, FR-01.6). */
121
+ export function excludeDynamicOn() {
122
+ try {
123
+ const raw = JSON.parse(fs.readFileSync(path.join(claudeConfigDir(), 'settings.json'), 'utf8'));
124
+ return raw.excludeDynamicSystemPromptSections === true;
125
+ }
126
+ catch {
127
+ return false;
128
+ }
129
+ }
130
+ /** A reason the mode cannot run, or null. */
131
+ export function modeRefusal(mode) {
132
+ if (mode === 'default' && !excludeDynamicOn()) {
133
+ 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';
134
+ }
135
+ return null;
136
+ }
137
+ export function keyBits(mode) {
138
+ return mode === 'fixed'
139
+ ? { settingSources: '', excludeDynamic: false, systemPromptSha: sha256(FIXED_SYSTEM_PROMPT).slice(0, 16) }
140
+ : { settingSources: 'user,project,local', excludeDynamic: excludeDynamicOn(), systemPromptSha: null };
141
+ }
142
+ /** Arguments shared by headless runs and the interactive open, so the prefix stays identical. */
143
+ export function sessionArgs(mode, profile, model) {
144
+ const args = [];
145
+ if (model && model !== 'default')
146
+ args.push('--model', model);
147
+ if (mode === 'fixed')
148
+ args.push('--system-prompt', FIXED_SYSTEM_PROMPT, '--setting-sources', '', '--strict-mcp-config');
149
+ if (profile.tools)
150
+ args.push('--tools', profile.tools.join(','));
151
+ if (profile.permissionMode)
152
+ args.push('--permission-mode', profile.permissionMode);
153
+ return args;
154
+ }
155
+ export function headlessArgs(opts) {
156
+ const args = ['-p', '--output-format', 'stream-json', '--verbose', ...sessionArgs(opts.mode, opts.profile, opts.model)];
157
+ if (opts.resume)
158
+ args.push('--resume', opts.resume, '--fork-session');
159
+ return args;
160
+ }
161
+ /** The interactive fork of a warm session (FR-06.1). */
162
+ export function openArgs(mode, profile, model, session) {
163
+ return [...sessionArgs(mode, profile, model), '--resume', session, '--fork-session'];
164
+ }
165
+ function usageOf(u) {
166
+ if (!u)
167
+ return null;
168
+ return {
169
+ input: Number(u.input_tokens ?? 0),
170
+ cacheWrite: Number(u.cache_creation_input_tokens ?? 0),
171
+ ...(typeof u.cache_creation?.ephemeral_1h_input_tokens === 'number'
172
+ ? { cacheWrite1h: Number(u.cache_creation.ephemeral_1h_input_tokens) }
173
+ : {}),
174
+ cacheRead: Number(u.cache_read_input_tokens ?? 0),
175
+ output: Number(u.output_tokens ?? 0),
176
+ };
177
+ }
178
+ /** One headless `claude -p` call; the first request's usage comes from the first assistant event. */
179
+ export function runClaude(opts) {
180
+ return new Promise((resolve) => {
181
+ const child = spawn(claudeBin(), headlessArgs(opts), {
182
+ cwd: opts.cwd,
183
+ env: { ...process.env, [DEPTH_ENV]: String(currentDepth() + 1) },
184
+ stdio: ['pipe', 'pipe', 'pipe'],
185
+ });
186
+ if (child.pid)
187
+ opts.onSpawn?.(child.pid);
188
+ let buf = '';
189
+ let stderr = '';
190
+ let first = null;
191
+ const seen = new Set();
192
+ let result = null;
193
+ let turns = 0;
194
+ let stopped = false;
195
+ let stopReason = '';
196
+ const stop = (why) => {
197
+ if (stopped)
198
+ return;
199
+ stopped = true;
200
+ stopReason = why;
201
+ child.kill('SIGTERM');
202
+ setTimeout(() => child.exitCode === null && child.kill('SIGKILL'), 2000).unref();
203
+ };
204
+ const onAbort = () => stop('stopped');
205
+ if (opts.signal?.aborted)
206
+ onAbort();
207
+ opts.signal?.addEventListener('abort', onAbort, { once: true });
208
+ const onLine = (line) => {
209
+ if (!line.trim())
210
+ return;
211
+ let ev;
212
+ try {
213
+ ev = JSON.parse(line);
214
+ }
215
+ catch {
216
+ return;
217
+ }
218
+ if (ev.type === 'assistant') {
219
+ const msg = ev.message;
220
+ // One API request can stream several assistant events with the same message id.
221
+ const id = msg?.id ?? `turn-${seen.size}`;
222
+ if (!seen.has(id)) {
223
+ seen.add(id);
224
+ if (first === null)
225
+ first = usageOf(msg?.usage);
226
+ }
227
+ turns = seen.size;
228
+ if (opts.maxTurns && turns > opts.maxTurns)
229
+ stop(`stopped after ${opts.maxTurns} turns`);
230
+ }
231
+ else if (ev.type === 'result') {
232
+ result = ev;
233
+ }
234
+ };
235
+ child.stdout.setEncoding('utf8');
236
+ child.stdout.on('data', (chunk) => {
237
+ buf += chunk;
238
+ let i;
239
+ while ((i = buf.indexOf('\n')) >= 0) {
240
+ onLine(buf.slice(0, i));
241
+ buf = buf.slice(i + 1);
242
+ }
243
+ });
244
+ child.stderr.setEncoding('utf8');
245
+ child.stderr.on('data', (c) => (stderr += c));
246
+ child.on('error', (err) => {
247
+ opts.signal?.removeEventListener('abort', onAbort);
248
+ resolve({ reply: '', session: null, first: null, total: null, turns, ok: false, error: `cannot start ${claudeBin()}: ${err.message}`, resumeError: false, stopped: false });
249
+ });
250
+ child.on('close', (code) => {
251
+ opts.signal?.removeEventListener('abort', onAbort);
252
+ onLine(buf);
253
+ const r = result;
254
+ const errors = Array.isArray(r?.errors) ? (r?.errors).map(String).join('; ') : '';
255
+ const isError = stopped || !r || r.is_error === true || code !== 0;
256
+ const message = stopped
257
+ ? stopReason
258
+ : errors || (r?.is_error ? String(r.result ?? '') : '') || stderr.trim() || (r ? '' : `no result from the engine (exit ${code})`);
259
+ resolve({
260
+ reply: r && !r.is_error ? String(r.result ?? '') : '',
261
+ session: r ? String(r.session_id ?? '') || null : null,
262
+ first,
263
+ total: usageOf(r?.usage),
264
+ turns,
265
+ costUsd: typeof r?.total_cost_usd === 'number' ? r.total_cost_usd : null,
266
+ ok: !isError,
267
+ error: isError ? message.slice(0, 2000) : undefined,
268
+ resumeError: /no conversation found/i.test(`${errors} ${stderr}`),
269
+ stopped,
270
+ });
271
+ });
272
+ child.stdin.on('error', () => undefined);
273
+ child.stdin.end(opts.stdin);
274
+ });
275
+ }
@@ -0,0 +1,8 @@
1
+ export interface HygieneFinding {
2
+ line: number;
3
+ category: 'secret' | 'machine-path';
4
+ pattern: string;
5
+ message: string;
6
+ redactedSnippet: string;
7
+ }
8
+ export declare function scanHygiene(content: string): HygieneFinding[];