limitcast 0.18.2 → 0.19.1

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,397 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { existsSync, mkdirSync, readFileSync, realpathSync, statSync } from 'node:fs';
4
+ import { join } from 'node:path';
5
+ import { stateDir, updateConfig, writeAtomic } from './store.mjs';
6
+
7
+ export const digest = (text) => createHash('sha256').update(text).digest('hex');
8
+ export const HOSTS = ['claude', 'codex', 'grok', 'copilot', 'pi'];
9
+ export const CORE_TOOLS =
10
+ /^(?:Bash|Read|Edit|Write|Grep|Glob|Skill|WebSearch|WebFetch|AskUserQuestion|exec|exec_command|apply_patch|request_user_input)$/i;
11
+ const CAPABILITIES = {
12
+ collaboration: /spawn_agent|spawn_subagent|collab|send_message|followup_task|wait_agent|list_agents|interrupt_agent/,
13
+ goals: /create_goal|get_goal|update_goal/,
14
+ image_media: /view_image|imagegen|image_generation|generatedImage|emitImage/,
15
+ };
16
+ const validTool = (name) => typeof name === 'string' && /^[\w:.-]{1,100}$/.test(name) && !Object.hasOwn(Object.prototype, name);
17
+
18
+ export function repository(cwd = process.cwd()) {
19
+ const root = realpathSync(execFileSync('git', ['-C', cwd, 'rev-parse', '--show-toplevel'], { encoding: 'utf8', timeout: 2000 }).trim());
20
+ return { root, id: digest(root).slice(0, 24) };
21
+ }
22
+
23
+ const location = (repo) => join(stateDir(), 'optimize', `${repo.id}.json`);
24
+ export function readOptimization(repo) {
25
+ const path = location(repo);
26
+ if (!existsSync(path)) return { version: 1, hosts: {}, facts: [], receipts: [], config: { learn: false, map: false, keep: [] } };
27
+ if (statSync(path).size > 2_000_000) throw new Error('optimizer state exceeds its size limit');
28
+ const state = JSON.parse(readFileSync(path, 'utf8'));
29
+ if (
30
+ state.version !== 1 ||
31
+ !state.hosts ||
32
+ Array.isArray(state.hosts) ||
33
+ !Array.isArray(state.facts) ||
34
+ !Array.isArray(state.receipts) ||
35
+ !state.config ||
36
+ !Array.isArray(state.config.keep)
37
+ )
38
+ throw new Error('unsupported optimizer state; inspect before changing it');
39
+ return state;
40
+ }
41
+
42
+ // Reuse the settings lock; callbacks only read/write bounded local JSON and never run a command or model.
43
+ export function changeOptimization(repo, change) {
44
+ let result;
45
+ updateConfig((cfg) => {
46
+ const state = readOptimization(repo);
47
+ result = change(state);
48
+ saveOptimization(repo, state);
49
+ return cfg;
50
+ });
51
+ return result;
52
+ }
53
+
54
+ export function saveOptimization(repo, state) {
55
+ const text = JSON.stringify(state);
56
+ if (text.length > 2_000_000) throw new Error('optimizer state exceeds its size limit');
57
+ mkdirSync(join(stateDir(), 'optimize'), { recursive: true, mode: 0o700 });
58
+ writeAtomic(location(repo), text);
59
+ }
60
+
61
+ export function commandShape(command) {
62
+ if (typeof command !== 'string' || command.length > 300 || /[;&|<>`$\n\r]/.test(command)) return null;
63
+ const clean = command
64
+ .trim()
65
+ .replace(/^rtk\s+/, '')
66
+ .replace(/\s+/g, ' ');
67
+ if (/^(?:python3?|\.venv\/bin\/python3?) -m (?:pytest|unittest)$/.test(clean)) return clean;
68
+ if (/^(?:pytest|npm test|node --test|cargo (?:test|check|build)|go test \.\/\.\.\.)$/.test(clean)) return clean;
69
+ if (/^npm run (?:test|build|lint|check|typecheck)$/.test(clean)) return clean;
70
+ if (/^npx (?:tsc|vitest run)$/.test(clean)) return clean;
71
+ return null;
72
+ }
73
+
74
+ function responseText(value) {
75
+ if (typeof value === 'string') return value.slice(0, 16000);
76
+ if (!value || typeof value !== 'object') return '';
77
+ return [
78
+ value.stdout,
79
+ value.text_result_for_llm,
80
+ value.textResultForLlm,
81
+ value.stderr,
82
+ value.output_for_prompt,
83
+ value.output,
84
+ typeof value.content === 'string'
85
+ ? value.content
86
+ : value.content
87
+ ?.filter?.((x) => x.type === 'text')
88
+ .map((x) => x.text)
89
+ .join('\n'),
90
+ ]
91
+ .filter((x) => typeof x === 'string')
92
+ .join('\n')
93
+ .slice(0, 16000);
94
+ }
95
+
96
+ export function normalizeEvent(hook, host) {
97
+ if (!HOSTS.includes(host) || !hook || typeof hook !== 'object') throw new Error('unsupported optimizer host or event');
98
+ const sid = String(hook.session_id ?? hook.sessionId ?? '').slice(0, 200);
99
+ if (!sid) throw new Error('optimizer needs a session id');
100
+ const rawEvent = String(hook.hook_event_name ?? hook.hookEventName ?? hook.event ?? '');
101
+ const event = rawEvent.includes('_')
102
+ ? rawEvent
103
+ .split('_')
104
+ .map((s) => s[0]?.toUpperCase() + s.slice(1))
105
+ .join('')
106
+ : ({ agentStop: 'Stop', userPromptSubmitted: 'UserPromptSubmit' }[rawEvent] ?? rawEvent[0]?.toUpperCase() + rawEvent.slice(1));
107
+ if (!['SessionStart', 'SessionEnd', 'UserPromptSubmit', 'PreToolUse', 'PostToolUse', 'PostToolUseFailure', 'Stop'].includes(event))
108
+ throw new Error('unsupported optimizer event');
109
+ const nativeName = String(hook.tool_name ?? hook.toolName ?? '').slice(0, 100);
110
+ const aliases = {
111
+ bash: 'Bash',
112
+ edit: 'Edit',
113
+ write: 'Write',
114
+ read: 'Read',
115
+ run_terminal_command: 'Bash',
116
+ run_terminal_cmd: 'Bash',
117
+ search_replace: 'Edit',
118
+ read_file: 'Read',
119
+ };
120
+ const name = Object.hasOwn(aliases, nativeName) ? aliases[nativeName] : nativeName;
121
+ let input = hook.tool_input ?? hook.toolInput ?? hook.toolArgs ?? {};
122
+ if (typeof input === 'string') {
123
+ try {
124
+ input = JSON.parse(input);
125
+ } catch {
126
+ input = { code: input };
127
+ }
128
+ }
129
+ const response = hook.tool_response ?? hook.tool_result ?? hook.toolResult ?? hook.error;
130
+ let parsedResponse = response;
131
+ if (typeof response === 'string') {
132
+ try {
133
+ parsedResponse = JSON.parse(response);
134
+ } catch {
135
+ /* plain tool output */
136
+ }
137
+ }
138
+ const text = responseText(parsedResponse);
139
+ const rawCode = typeof input?.code === 'string' ? input.code : typeof input?.input === 'string' ? input.input : '';
140
+ let patchText = rawCode;
141
+ const patchLiteral = /\btools\.apply_patch\s*\(\s*("(?:[^"\\]|\\.)*")/.exec(rawCode)?.[1];
142
+ if (patchLiteral) {
143
+ try {
144
+ patchText = JSON.parse(patchLiteral);
145
+ } catch {
146
+ /* retain the raw form when ambiguous */
147
+ }
148
+ }
149
+ const nested = [...rawCode.matchAll(/\b(?:cmd|command)\s*:\s*("(?:[^"\\]|\\.)*"|'[^'\\]*')/g)];
150
+ let nestedCommand;
151
+ if (nested.length === 1) {
152
+ try {
153
+ nestedCommand = nested[0][1][0] === '"' ? JSON.parse(nested[0][1]) : nested[0][1].slice(1, -1);
154
+ } catch {
155
+ /* ambiguous command: no learning */
156
+ }
157
+ }
158
+ const command = commandShape(input?.command ?? input?.cmd ?? nestedCommand);
159
+ const reportedCode = /(?:^|\n)(?:Exit code:? |Process exited with code |exit: )(\d+)\b/i.exec(text)?.[1];
160
+ const status =
161
+ parsedResponse?.exit_code ?? parsedResponse?.exitCode ?? hook.exit_code ?? (reportedCode === undefined ? undefined : Number(reportedCode));
162
+ const failed =
163
+ event === 'PostToolUseFailure' ||
164
+ parsedResponse?.is_error === true ||
165
+ parsedResponse?.isError === true ||
166
+ (typeof status === 'number' && status !== 0) ||
167
+ (Boolean(command) && /(?:^|\s)[1-9]\d* failed\b/.test(text));
168
+ const path = String(
169
+ input?.file_path ?? input?.target_file ?? input?.path ?? /\*\*\* (?:Update|Add|Delete) File: ([^\r\n]+)/.exec(patchText)?.[1] ?? '',
170
+ );
171
+ const edit = /^(?:Edit|Write|MultiEdit|apply_patch|replace_file_content|write_to_file)$/i.test(name) || /\btools\.apply_patch\s*\(/.test(rawCode);
172
+ const succeeded = Boolean(command) && !failed && (status === 0 || /(?:^|\n)(?:# fail 0|.*\b\d+ passed\b|OK)\s*$/m.test(text));
173
+ const id = hook.tool_use_id ?? hook.toolUseId ?? hook.call_id;
174
+ return {
175
+ host,
176
+ sid: digest(`${host}:${sid}`).slice(0, 24),
177
+ event,
178
+ name,
179
+ command,
180
+ failed,
181
+ succeeded,
182
+ edit,
183
+ environmentFailure: failed && /command not found|No module named|not recognized as an? (?:internal|external) command|ENOENT/.test(text),
184
+ file: path ? digest(path).slice(0, 16) : '',
185
+ // Keep only a digest of failure evidence, never command output, prompts or credentials.
186
+ failure: failed ? digest(text.replace(/0x[\da-f]+|\b\d+\b/gi, '#')).slice(0, 20) : '',
187
+ identity: id ? digest(`${event.replace('PostToolUseFailure', 'PostToolUse')}:${String(id)}`).slice(0, 32) : null,
188
+ capabilities: Object.entries(CAPABILITIES)
189
+ .filter(([, re]) => re.test(`${name} ${JSON.stringify(input).slice(0, 32000)}`))
190
+ .map(([key]) => key),
191
+ tools: Array.isArray(hook.tools)
192
+ ? hook.tools
193
+ .map((t) => (typeof t === 'string' ? t : t?.name))
194
+ .filter(validTool)
195
+ .slice(0, 200)
196
+ : [],
197
+ };
198
+ }
199
+
200
+ const freshTurn = () => ({ trace: [], calls: 0, errors: 0, repeats: 0, failures: [], edits: {}, green: false, nudged: false, warned: false });
201
+
202
+ export function loopDecision(turn, productiveLengths = []) {
203
+ const churn = Math.max(0, ...Object.values(turn.edits));
204
+ if (turn.green || turn.calls < 18 || turn.errors < 4 || turn.repeats < 3 || churn < 3) return null;
205
+ const sorted = productiveLengths.slice().sort((a, b) => a - b);
206
+ const normal = sorted.length >= 5 ? sorted[Math.floor((sorted.length - 1) * 0.9)] : 20;
207
+ if (turn.calls < Math.max(18, normal * 1.25)) return null;
208
+ if (!turn.nudged) return 'redirect';
209
+ if (!turn.warned && turn.calls >= turn.nudgeAt + 12 && turn.repeats >= turn.nudgeRepeats + 3) return 'notice';
210
+ return null;
211
+ }
212
+
213
+ function learn(state, session, e) {
214
+ if (!state.config.learn || !e.command) return;
215
+ for (const fact of state.facts) {
216
+ if (fact.to === e.command && e.environmentFailure && fact.state === 'active') fact.state = 'retired';
217
+ }
218
+ if (e.environmentFailure) session.failed = [...new Set([...(session.failed ?? []), e.command])].slice(-6);
219
+ if (!e.succeeded) return;
220
+ for (const from of session.failed ?? []) {
221
+ if (from === e.command) continue;
222
+ if (/test/.test(from) !== /test/.test(e.command)) continue;
223
+ let fact = state.facts.find((f) => f.from === from && f.to === e.command);
224
+ if (!fact) {
225
+ fact = { id: digest(`${from}\0${e.command}`).slice(0, 16), from, to: e.command, state: 'candidate', sessions: [] };
226
+ state.facts.push(fact);
227
+ }
228
+ if (fact.state === 'retired') continue;
229
+ fact.sessions = [...new Set([...fact.sessions, e.sid])].slice(-3);
230
+ if (fact.sessions.length >= 3) fact.state = 'active';
231
+ }
232
+ session.failed = [];
233
+ state.facts = state.facts.slice(-100);
234
+ }
235
+
236
+ export function learnedContext(state) {
237
+ if (!state.config.learn) return '';
238
+ return state.facts
239
+ .filter((f) => f.state === 'active' && commandShape(f.to) && (f.kind === 'check' || commandShape(f.from)))
240
+ .slice(0, 4)
241
+ .map((f) =>
242
+ f.kind === 'check'
243
+ ? `Repository evidence: ${f.to} passed in three independent sessions and was selected by the learning model. Consider it for verification.`
244
+ : `Repository evidence: ${f.from} failed and ${f.to} succeeded in three independent sessions. Consider ${f.to} for that check.`,
245
+ )
246
+ .join('\n')
247
+ .slice(0, 1000);
248
+ }
249
+
250
+ export function processEvent(state, e, now = Date.now()) {
251
+ const host = (state.hosts[e.host] ??= {
252
+ sessions: {},
253
+ completed: 0,
254
+ finished: [],
255
+ prompts: 0,
256
+ used: [],
257
+ usedTools: [],
258
+ catalog: {},
259
+ productive: [],
260
+ });
261
+ const old = Object.keys(host.sessions);
262
+ if (!host.sessions[e.sid] && old.length >= 30) delete host.sessions[old[0]];
263
+ const session = (host.sessions[e.sid] ??= { turn: freshTurn(), seen: [], started: now });
264
+ if (e.identity && session.seen.includes(e.identity)) return {};
265
+ if (e.identity) session.seen = [...session.seen, e.identity].slice(-500);
266
+ const receipt = (kind) => {
267
+ state.receipts = [...state.receipts, { kind, host: e.host, session: e.sid, t: now }].slice(-200);
268
+ };
269
+ host.used = [...new Set([...host.used, ...e.capabilities])];
270
+ if (validTool(e.name) && host.usedTools.length < 200) host.usedTools = [...new Set([...host.usedTools, e.name])];
271
+ for (const tool of e.tools) {
272
+ if (Object.keys(host.catalog).length < 200) host.catalog[tool] ??= { used: host.usedTools.includes(tool), sessions: [] };
273
+ }
274
+ if (Object.hasOwn(host.catalog, e.name)) host.catalog[e.name].used = true;
275
+ if (e.event === 'SessionStart' || (e.host === 'grok' && /^PostToolUse(?:Failure)?$/.test(e.event) && !session.injected)) {
276
+ if (e.host === 'grok' && e.event === 'SessionStart') return {};
277
+ if (session.injected) return {};
278
+ session.injected = true;
279
+ const context = learnedContext(state);
280
+ if (context) receipt('facts-injected');
281
+ if (e.host !== 'grok') return { context, map: state.config.map };
282
+ session.pendingContext = context;
283
+ session.pendingMap = state.config.map;
284
+ }
285
+ if (e.event === 'UserPromptSubmit') {
286
+ session.turn = freshTurn();
287
+ session.turnId = (session.turnId ?? 0) + 1;
288
+ session.stopped = false;
289
+ session.failed = [];
290
+ host.prompts++;
291
+ } else if (e.event === 'Stop' || e.event === 'SessionEnd') {
292
+ if (!session.stopped && session.turn.green && session.turn.calls) host.productive = [...host.productive, session.turn.calls].slice(-50);
293
+ session.stopped = true;
294
+ if (!host.finished.includes(e.sid)) {
295
+ host.finished = [...host.finished, e.sid].slice(-1000);
296
+ host.completed++;
297
+ for (const name of e.tools) {
298
+ const tool = host.catalog[name];
299
+ if (tool) tool.sessions = [...new Set([...tool.sessions, e.sid])].slice(-5);
300
+ }
301
+ }
302
+ } else if (/^PostToolUse(?:Failure)?$/.test(e.event)) {
303
+ const turn = session.turn;
304
+ turn.calls++;
305
+ turn.trace = [
306
+ ...(turn.trace ?? []),
307
+ {
308
+ action: e.edit ? 'edit' : e.command ? 'check' : 'other',
309
+ command: e.command,
310
+ failed: e.failed,
311
+ succeeded: e.succeeded,
312
+ file: e.file,
313
+ failure: e.failure,
314
+ },
315
+ ].slice(-30);
316
+ if (e.command) {
317
+ session.checks ??= {};
318
+ if (e.succeeded) session.checks[e.command] = true;
319
+ if (e.failed) {
320
+ delete session.checks[e.command];
321
+ for (const f of state.facts) if (f.kind === 'check' && f.to === e.command) f.state = 'retired';
322
+ }
323
+ }
324
+ if (e.edit) {
325
+ if (Object.keys(turn.edits).length < 64 || turn.edits[e.file || e.name]) turn.edits[e.file || e.name] = (turn.edits[e.file || e.name] ?? 0) + 1;
326
+ turn.green = false;
327
+ }
328
+ if (e.failed) {
329
+ turn.errors++;
330
+ if (turn.failures.includes(e.failure)) turn.repeats++;
331
+ turn.failures = [...turn.failures, e.failure].slice(-30);
332
+ turn.green = false;
333
+ }
334
+ if (e.succeeded) {
335
+ turn.green = true;
336
+ turn.errors = 0;
337
+ turn.repeats = 0;
338
+ turn.failures = [];
339
+ turn.edits = {};
340
+ }
341
+ learn(state, session, e);
342
+ const decision = loopDecision(turn, host.productive);
343
+ if (decision === 'redirect' && state.config.model) {
344
+ const verdict = turn.judgment;
345
+ if (!verdict || now - verdict.at > 300000 || turn.calls - verdict.calls > 12) {
346
+ if (!turn.judgeRequested || now - turn.judgeRequested > 300000) return { modelJob: 'judge' };
347
+ return {};
348
+ }
349
+ if (!verdict.stuck || verdict.confidence < 0.7) return {};
350
+ }
351
+ if (decision === 'redirect') {
352
+ turn.nudged = true;
353
+ turn.nudgeAt = turn.calls;
354
+ turn.nudgeRepeats = turn.repeats;
355
+ receipt('loop-redirect');
356
+ return {
357
+ context:
358
+ 'Limitcast process check: repeated failures and edits have stopped making progress. Re-read the failing check, form a different root-cause hypothesis, and verify it before editing again. Continue the task; this notice does not stop it.',
359
+ };
360
+ }
361
+ if (decision === 'notice') {
362
+ turn.warned = true;
363
+ receipt('loop-notice');
364
+ return { notice: 'Limitcast: repeated failures continued after a redirect. Review the approach; interrupt the turn if needed.' };
365
+ }
366
+ }
367
+ if (
368
+ state.config.learn &&
369
+ state.config.model &&
370
+ ['Stop', 'SessionEnd'].includes(e.event) &&
371
+ !session.learningRequested &&
372
+ Object.keys(session.checks ?? {}).length
373
+ )
374
+ return { modelJob: 'learn' };
375
+ // Keep ended-session tombstones so replay cannot count the same session twice.
376
+ const ids = Object.keys(host.sessions);
377
+ for (const id of ids.slice(0, Math.max(0, ids.length - 30))) delete host.sessions[id];
378
+ if (session.pendingContext || session.pendingMap) {
379
+ const result = { context: session.pendingContext, map: session.pendingMap };
380
+ delete session.pendingContext;
381
+ delete session.pendingMap;
382
+ return result;
383
+ }
384
+ return {};
385
+ }
386
+
387
+ export function capabilityProposals(state, host) {
388
+ const h = state.hosts[host];
389
+ if (!h || h.completed < 5 || h.prompts < 10) return [];
390
+ const keep = state.config.keep ?? [];
391
+ if (host === 'codex') return Object.keys(CAPABILITIES).filter((c) => !h.used.includes(c) && !keep.includes(c));
392
+ if (host === 'claude')
393
+ return Object.entries(h.catalog)
394
+ .filter(([n, t]) => !CORE_TOOLS.test(n) && !t.used && t.sessions.length >= 5 && !keep.includes(n))
395
+ .map(([n]) => n);
396
+ return [];
397
+ }
@@ -0,0 +1,54 @@
1
+ import { copyFileSync, existsSync, lstatSync, mkdirSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { dirname, join } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { readSettings } from './install.mjs';
6
+ import { writeAtomic } from './store.mjs';
7
+
8
+ export function installOptimizerHost(
9
+ host,
10
+ {
11
+ home = host === 'copilot'
12
+ ? (process.env.COPILOT_HOME ?? join(homedir(), '.copilot'))
13
+ : (process.env.PI_CODING_AGENT_DIR ?? join(homedir(), '.pi', 'agent')),
14
+ undo = false,
15
+ } = {},
16
+ ) {
17
+ if (!['copilot', 'pi'].includes(host)) throw new Error('choose --copilot or --pi');
18
+ const path = host === 'copilot' ? join(home, 'hooks', 'limitcast.json') : join(home, 'settings.json');
19
+ for (const item of [home, dirname(path), path])
20
+ if (existsSync(item) && lstatSync(item).isSymbolicLink()) throw new Error('refuse symlinked optimizer settings');
21
+ const cfg = readSettings(path);
22
+ if (host === 'copilot') {
23
+ if (cfg.limitcast !== undefined && cfg.limitcast !== true) throw new Error('existing hook file is not owned by Limitcast');
24
+ if (existsSync(path) && cfg.limitcast !== true) throw new Error('preserve the existing hook file before installing');
25
+ cfg.version = 1;
26
+ cfg.limitcast = true;
27
+ cfg.hooks = undo
28
+ ? {}
29
+ : Object.fromEntries(
30
+ ['SessionStart', 'UserPromptSubmit', 'PostToolUse', 'PostToolUseFailure', 'Stop', 'SessionEnd'].map((event) => [
31
+ event,
32
+ [
33
+ {
34
+ type: 'command',
35
+ exec: process.execPath,
36
+ args: [fileURLToPath(new URL('../bin/limitcast.mjs', import.meta.url)), '_optimize-hook', '--src', host],
37
+ timeoutSec: 10,
38
+ },
39
+ ],
40
+ ]),
41
+ );
42
+ } else {
43
+ const extension = fileURLToPath(new URL('./pi-extension.mjs', import.meta.url));
44
+ if (cfg.extensions !== undefined && !Array.isArray(cfg.extensions)) throw new Error('Pi extensions must be an array');
45
+ cfg.extensions = (cfg.extensions ?? []).filter(
46
+ (p) => typeof p !== 'string' || (!/(?:^|\/)limitcast(?:\/|$).*\/pi-extension\.mjs$/.test(p) && p !== extension),
47
+ );
48
+ if (!undo) cfg.extensions.push(extension);
49
+ }
50
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
51
+ if (existsSync(path)) copyFileSync(path, `${path}.limitcast-backup`);
52
+ writeAtomic(path, `${JSON.stringify(cfg, null, 2)}\n`);
53
+ return { host, path, installed: !undo, runtimeDelivery: 'unverified; restart the host' };
54
+ }
@@ -0,0 +1,79 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { fileURLToPath } from 'node:url';
3
+
4
+ export function carriedContext(entries) {
5
+ let text = '';
6
+ for (const entry of entries) {
7
+ const sections = entry.type === 'compaction' ? entry.systemMessage?.sections : entry.message?.role === 'system' ? entry.message.sections : null;
8
+ if (sections && Object.hasOwn(sections, 'limitcast')) text = sections.limitcast ?? '';
9
+ }
10
+ return typeof text === 'string'
11
+ ? text
12
+ .replace(/^<limitcast>\n/, '')
13
+ .replace(/\n<\/limitcast>$/, '')
14
+ .slice(0, 8000)
15
+ : '';
16
+ }
17
+
18
+ export default function limitcast(pi) {
19
+ let context = '';
20
+ const base = (ctx) => ({ session_id: ctx.sessionManager.getSessionId(), cwd: ctx.cwd });
21
+ function hook(ctx, event, fields = {}) {
22
+ if (process.env.LIMITCAST_ALLOW === '1' || process.env.LIMITCAST_MODEL_WORKER === '1') return Promise.resolve({});
23
+ return new Promise((resolve) => {
24
+ let out = '';
25
+ const child = spawn(process.execPath, [fileURLToPath(new URL('../bin/limitcast.mjs', import.meta.url)), '_optimize-hook', '--src', 'pi'], {
26
+ cwd: ctx.cwd,
27
+ stdio: ['pipe', 'pipe', 'ignore'],
28
+ });
29
+ const timer = setTimeout(() => {
30
+ child.kill('SIGKILL');
31
+ resolve({});
32
+ }, 8000);
33
+ child.stdout.setEncoding('utf8');
34
+ child.stdout.on('data', (data) => {
35
+ out += data;
36
+ if (out.length > 32000) child.kill('SIGKILL');
37
+ });
38
+ child.on('error', () => {
39
+ clearTimeout(timer);
40
+ resolve({});
41
+ });
42
+ child.on('close', () => {
43
+ clearTimeout(timer);
44
+ try {
45
+ resolve(JSON.parse(out));
46
+ } catch {
47
+ resolve({});
48
+ }
49
+ });
50
+ child.stdin.on('error', () => {});
51
+ child.stdin.end(JSON.stringify({ ...base(ctx), hook_event_name: event, ...fields }));
52
+ });
53
+ }
54
+ pi.on('session_start', async (_, ctx) => {
55
+ const out = await hook(ctx, 'SessionStart');
56
+ const entries = ctx.sessionManager.getBranch?.() ?? [];
57
+ context = entries.some((e) => e.type === 'message') ? carriedContext(entries) : (out.hookSpecificOutput?.additionalContext ?? '');
58
+ });
59
+ pi.on('before_agent_start', async (event, ctx) => {
60
+ await hook(ctx, 'UserPromptSubmit');
61
+ if (context) event.systemPromptOptions.sections = { ...event.systemPromptOptions.sections, limitcast: context };
62
+ });
63
+ pi.on('tool_result', async (event, ctx) => {
64
+ const out = await hook(ctx, 'PostToolUse', {
65
+ tool_name: event.toolName,
66
+ tool_use_id: event.toolCallId,
67
+ tool_input: event.input,
68
+ tool_response: { content: event.content, isError: event.isError, exit_code: event.structuredContent?.exit_code },
69
+ });
70
+ const text = out.hookSpecificOutput?.additionalContext ?? out.systemMessage;
71
+ if (text) pi.sendMessage({ customType: 'limitcast', content: text, display: true }, { deliverAs: 'steer' });
72
+ });
73
+ pi.on('agent_end', async (_, ctx) => {
74
+ await hook(ctx, 'Stop');
75
+ });
76
+ pi.on('session_shutdown', async (_, ctx) => {
77
+ await hook(ctx, 'SessionEnd');
78
+ });
79
+ }
package/src/plan.mjs CHANGED
@@ -3,7 +3,7 @@ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
4
  import { claudeAccounts } from './forecast.mjs';
5
5
  import { fmtUsd } from './prices.mjs';
6
- import { stateDir, writeAtomic } from './store.mjs';
6
+ import { stateDir, updateConfig } from './store.mjs';
7
7
 
8
8
  // `limitcast plan`: does your Claude plan fit how much you use? From a long-lived record of the peak of every
9
9
  // 5-hour and weekly window (the samples themselves are only kept for 8 days), it says whether you hit your limits often
@@ -42,14 +42,7 @@ export function getPlan() {
42
42
 
43
43
  /** @param {PlanId|null} plan */
44
44
  export function setPlan(plan) {
45
- let cfg = {};
46
- try {
47
- cfg = JSON.parse(readFileSync(configFile(), 'utf8'));
48
- } catch {
49
- /* new */
50
- }
51
- mkdirSync(stateDir(), { recursive: true });
52
- writeAtomic(configFile(), JSON.stringify({ ...cfg, plan }));
45
+ updateConfig((cfg) => ({ ...cfg, plan }));
53
46
  }
54
47
 
55
48
  /**
@@ -0,0 +1,53 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync } from 'node:fs';
3
+ import { join, relative, sep } from 'node:path';
4
+ import { digest } from './optimize.mjs';
5
+ import { stateDir, writeAtomic } from './store.mjs';
6
+
7
+ const SOURCE = /\.(?:[cm]?[jt]sx?|py|rs|go|java|rb|php|[ch](?:pp)?)$/;
8
+ const EXCLUDE =
9
+ /(?:^|\/)(?:\.[^/]+|node_modules|vendor|dist|build|coverage|fixtures|generated|__pycache__)(?:\/|$)|(?:secret|credential|private[-_]?key|\.min\.)/i;
10
+
11
+ export function repositoryMap(repo, { refresh = false, maxChars = 6000 } = {}) {
12
+ if (!Number.isInteger(maxChars) || maxChars < 100 || maxChars > 8000) throw new Error('map budget must be 100–8000 characters');
13
+ const git = (...args) => execFileSync('git', ['-C', repo.root, ...args], { encoding: 'utf8', timeout: 2000, maxBuffer: 1_000_000 });
14
+ const head = git('rev-parse', 'HEAD').trim();
15
+ const dirty = git('status', '--porcelain', '--untracked-files=no');
16
+ const path = join(stateDir(), 'optimize', `${repo.id}.map.json`);
17
+ if (!refresh && !dirty && existsSync(path)) {
18
+ const cached = JSON.parse(readFileSync(path, 'utf8'));
19
+ if (cached.head === head && cached.budget === maxChars) return cached.text;
20
+ }
21
+ const files = git('ls-files', '-z')
22
+ .split('\0')
23
+ .filter((f) => /^[\w./@+-]+$/.test(f) && SOURCE.test(f) && !EXCLUDE.test(f))
24
+ .slice(0, 1000);
25
+ const rows = [];
26
+ let read = 0;
27
+ for (const name of files) {
28
+ const full = join(repo.root, name);
29
+ if (!existsSync(full) || !lstatSync(full).isFile() || lstatSync(full).size > 100_000) continue;
30
+ const rel = relative(repo.root, realpathSync(full));
31
+ if (rel.startsWith(`..${sep}`) || rel === '..') continue;
32
+ const text = readFileSync(full, 'utf8');
33
+ read += text.length;
34
+ if (read > 2_000_000) break;
35
+ const names = [
36
+ ...text.matchAll(
37
+ /(?:^|\n)\s*(?:export\s+)?(?:pub\s+)?(?:async\s+)?(?:function|class|def|fn|func)\s+([A-Za-z_$][\w$]*)|(?:^|\n)export\s+const\s+([A-Za-z_$][\w$]*)/g,
38
+ ),
39
+ ]
40
+ .map((m) => m[1] ?? m[2])
41
+ .slice(0, 12);
42
+ rows.push({ name, symbols: [...new Set(names)], score: (name.startsWith('src/') ? 3 : 0) + (name.startsWith('test/') ? 0 : 1) + names.length });
43
+ }
44
+ rows.sort((a, b) => b.score - a.score || a.name.localeCompare(b.name));
45
+ let text = 'Repository map (tracked source files; names only):\n';
46
+ for (const row of rows) {
47
+ const line = `${row.name}${row.symbols.length ? `: ${row.symbols.join(', ')}` : ''}\n`;
48
+ if (text.length + line.length <= maxChars) text += line;
49
+ }
50
+ mkdirSync(join(stateDir(), 'optimize'), { recursive: true, mode: 0o700 });
51
+ writeAtomic(path, JSON.stringify({ head, budget: maxChars, fingerprint: digest(text), text }));
52
+ return text;
53
+ }