limitcast 0.19.3 → 0.20.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/README.md +4 -3
- package/bin/limitcast.mjs +157 -38
- package/package.json +2 -2
- package/src/apply.mjs +96 -116
- package/src/capabilities.mjs +19 -6
- package/src/codex-trust.mjs +85 -0
- package/src/codex.mjs +115 -64
- package/src/grok.mjs +112 -67
- package/src/guard.mjs +8 -2
- package/src/inflight.mjs +7 -2
- package/src/install.mjs +34 -10
- package/src/notify.mjs +17 -0
- package/src/optimize-cli.mjs +13 -0
- package/src/overhead.mjs +39 -13
- package/src/prices.mjs +9 -2
- package/src/receipts.mjs +188 -0
- package/src/report.mjs +9 -0
- package/src/results.mjs +21 -3
- package/src/store.mjs +76 -31
- package/src/subagents.mjs +35 -4
- package/src/toolcheck.mjs +50 -8
- package/src/toollimit.mjs +63 -9
- package/src/transaction.mjs +93 -0
- package/src/usage.mjs +53 -10
- package/src/value.mjs +13 -1
package/src/grok.mjs
CHANGED
|
@@ -4,7 +4,8 @@ import { homedir } from 'node:os';
|
|
|
4
4
|
import { dirname, join } from 'node:path';
|
|
5
5
|
import { codexServers, setEnabled } from './codex.mjs';
|
|
6
6
|
import { windowMs } from './forecast.mjs';
|
|
7
|
-
import { KEEP_MS, stateDir, updateConfig } from './store.mjs';
|
|
7
|
+
import { KEEP_MS, stateDir, updateConfig, withStateLock } from './store.mjs';
|
|
8
|
+
import { commitTransaction, editText, readLedger, recoverTransaction } from './transaction.mjs';
|
|
8
9
|
import { grokRoot } from './usage.mjs';
|
|
9
10
|
|
|
10
11
|
/** @typedef {import('./forecast.mjs').Sample} Sample */
|
|
@@ -57,23 +58,38 @@ export function grokUsedServers(since, root = grokRoot()) {
|
|
|
57
58
|
}
|
|
58
59
|
|
|
59
60
|
/**
|
|
60
|
-
* Sizes from the newest session
|
|
61
|
+
* Sizes from the newest interactive session (a subagent's child session is skipped: it carries its own prompt): the
|
|
62
|
+
* system prompt Grok loaded, the tool list, and the instruction files (AGENTS.md and the like), all in characters, and
|
|
63
|
+
* `at`, when the session started.
|
|
61
64
|
* @param {string} [root]
|
|
62
|
-
* @returns {{prompt:number, tools:number}|null}
|
|
65
|
+
* @returns {{prompt:number, tools:number, agentsMd:number, at?:number}|null}
|
|
63
66
|
*/
|
|
64
67
|
export function grokStartup(root = grokRoot()) {
|
|
65
|
-
const usage
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
68
|
+
for (const usage of newestFiles(root, (n) => n === 'usage.json').slice(0, 40)) {
|
|
69
|
+
const dir = dirname(usage);
|
|
70
|
+
const json = (/** @type {string} */ n) => {
|
|
71
|
+
try {
|
|
72
|
+
return JSON.parse(readFileSync(join(dir, n), 'utf8'));
|
|
73
|
+
} catch {
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
const summary = json('summary.json');
|
|
78
|
+
if (summary?.session_kind === 'subagent') continue;
|
|
79
|
+
const at = Date.parse(summary?.created_at);
|
|
80
|
+
const size = (/** @type {string} */ n) => {
|
|
81
|
+
const p = join(dir, n);
|
|
82
|
+
return existsSync(p) ? statSync(p).size : 0;
|
|
83
|
+
};
|
|
84
|
+
const files = json('prompt_context.json')?.agents_md_files;
|
|
85
|
+
const agentsMd = Array.isArray(files) ? files.reduce((a, f) => a + String(f?.content ?? '').length, 0) : 0;
|
|
86
|
+
return { prompt: size('system_prompt.txt'), tools: size('tool_definitions.json'), agentsMd, ...(Number.isFinite(at) ? { at } : {}) };
|
|
87
|
+
}
|
|
88
|
+
return null;
|
|
73
89
|
}
|
|
74
90
|
|
|
75
91
|
/**
|
|
76
|
-
* @param {{servers:{name:string, enabled:boolean|undefined}[], used:Set<string>, usedMonth?:Set<string>|null, startup:{prompt:number, tools:number}|null, days:number, pro:boolean, keep?:string[]}} r
|
|
92
|
+
* @param {{servers:{name:string, enabled:boolean|undefined}[], used:Set<string>, usedMonth?:Set<string>|null, startup:{prompt:number, tools:number, agentsMd?:number}|null, days:number, pro:boolean, keep?:string[]}} r
|
|
77
93
|
* keep: the `trim keep` list; unused servers on it are reported as kept and left out of `unused`.
|
|
78
94
|
* usedMonth: normalized names used in 30 days. Servers in it stay out of `unused`.
|
|
79
95
|
*/
|
|
@@ -85,11 +101,14 @@ export function grokTrimReport({ servers, used, usedMonth = null, startup, days,
|
|
|
85
101
|
const unused = idle.filter((s) => !kept.includes(s) && !standing.includes(s));
|
|
86
102
|
const tok = (/** @type {number} */ c) => `${(c / 4000).toFixed(1)}k`;
|
|
87
103
|
const out = ['# limitcast trim --grok', ''];
|
|
88
|
-
if (startup)
|
|
104
|
+
if (startup) {
|
|
105
|
+
const files = startup.agentsMd ? ` and ~${tok(startup.agentsMd)} of instruction files` : '';
|
|
106
|
+
const total = startup.prompt + startup.tools + (startup.agentsMd ?? 0);
|
|
89
107
|
out.push(
|
|
90
|
-
`Grok sessions start with ~${tok(startup.prompt)} tokens of system prompt
|
|
108
|
+
`Grok sessions start with ~${tok(startup.prompt)} tokens of system prompt, ~${tok(startup.tools)} of tool definitions${files}${startup.agentsMd ? ` (about ${tok(total)} in all, estimated from file sizes)` : ''}, re-sent on every turn.`,
|
|
91
109
|
'',
|
|
92
110
|
);
|
|
111
|
+
}
|
|
93
112
|
out.push(`## MCP servers: ${on.length} on, ${unused.length + standing.length} not used in ${days} days`);
|
|
94
113
|
if (standing.length)
|
|
95
114
|
out.push('', `${standing.length} used in the last 30 days, so \`trim --apply\` leaves them on:`, ...standing.map((s) => `- ${s.name}`));
|
|
@@ -119,41 +138,49 @@ export function grokTrimReport({ servers, used, usedMonth = null, startup, days,
|
|
|
119
138
|
* @param {string[]} names
|
|
120
139
|
*/
|
|
121
140
|
export function applyGrokTrim(names, { now = Date.now(), path = grokConfigPath() } = {}) {
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
141
|
+
return withStateLock(() => {
|
|
142
|
+
recoverTransaction(trimLedger());
|
|
143
|
+
const ledger = loadTrimLedger();
|
|
144
|
+
if (!names.length || !existsSync(path)) return [];
|
|
145
|
+
let toml;
|
|
146
|
+
const update = editText(path, (text) => {
|
|
147
|
+
toml = text;
|
|
148
|
+
return setEnabled(text, Object.fromEntries(names.map((n) => [n, false])));
|
|
149
|
+
});
|
|
150
|
+
const before = new Map(codexServers(toml).map((s) => [s.name, s.enabled]));
|
|
151
|
+
copyFileSync(path, `${path}.limitcast-backup-${new Date(now).toISOString().replace(/[:.]/g, '-')}`);
|
|
152
|
+
const servers = names.map((name) => ({ name, prev: before.get(name) ?? null }));
|
|
153
|
+
commitTransaction(trimLedger(), [...ledger, { at: now, servers }], [update]);
|
|
154
|
+
return servers;
|
|
155
|
+
});
|
|
131
156
|
}
|
|
132
157
|
|
|
133
158
|
/** Reverse the last --apply. Servers the user turned back on stay on. */
|
|
134
159
|
export function undoGrokTrim({ path = grokConfigPath() } = {}) {
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
160
|
+
return withStateLock(() => {
|
|
161
|
+
recoverTransaction(trimLedger());
|
|
162
|
+
const ledger = loadTrimLedger();
|
|
163
|
+
const last = ledger.pop();
|
|
164
|
+
if (!last || !existsSync(path)) return null;
|
|
165
|
+
const update = editText(path, (toml) => {
|
|
166
|
+
const off = new Set(
|
|
167
|
+
codexServers(toml)
|
|
168
|
+
.filter((s) => s.enabled === false)
|
|
169
|
+
.map((s) => s.name),
|
|
170
|
+
);
|
|
171
|
+
return setEnabled(toml, Object.fromEntries(last.servers.filter((s) => off.has(s.name)).map((s) => [s.name, s.prev])));
|
|
172
|
+
});
|
|
173
|
+
copyFileSync(path, `${path}.limitcast-backup-${new Date().toISOString().replace(/[:.]/g, '-')}`);
|
|
174
|
+
commitTransaction(trimLedger(), ledger, [update]);
|
|
175
|
+
return last;
|
|
176
|
+
});
|
|
148
177
|
}
|
|
149
178
|
|
|
150
179
|
/** @returns {{at:number, servers:{name:string, prev:boolean|null}[]}[]} */
|
|
151
180
|
function loadTrimLedger() {
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
return [];
|
|
156
|
-
}
|
|
181
|
+
const entries = readLedger(trimLedger());
|
|
182
|
+
if (entries.some((e) => !Array.isArray(e.servers))) throw new Error('invalid Grok trim ledger');
|
|
183
|
+
return entries;
|
|
157
184
|
}
|
|
158
185
|
|
|
159
186
|
/**
|
|
@@ -499,7 +526,7 @@ export function grokHistory(since, now, { root = grokRoot(), budget = getGrokBud
|
|
|
499
526
|
* @param {{guard:boolean, self:string, home?:string}} opts
|
|
500
527
|
* @returns {string[]}
|
|
501
528
|
*/
|
|
502
|
-
export function installGrok({ guard, self, home = grokHome() }) {
|
|
529
|
+
export function installGrok({ guard, alerts = false, self, home = grokHome() }) {
|
|
503
530
|
if (!grokPresent(home)) return [];
|
|
504
531
|
const changes = [];
|
|
505
532
|
const cfgPath = join(home, 'config.toml');
|
|
@@ -518,24 +545,35 @@ export function installGrok({ guard, self, home = grokHome() }) {
|
|
|
518
545
|
);
|
|
519
546
|
}
|
|
520
547
|
}
|
|
521
|
-
|
|
522
|
-
|
|
548
|
+
const path = join(home, 'hooks', 'limitcast.json');
|
|
549
|
+
// One file holds both parts, so installing one never drops the other that an earlier install added.
|
|
550
|
+
const prev = existsSync(path) ? readFileSync(path, 'utf8') : '';
|
|
551
|
+
const mine = prev.includes(MARK) ? prev : '';
|
|
552
|
+
const wantGuard = guard || /\bsubagent-receipt\b/.test(mine);
|
|
553
|
+
const wantAlerts = alerts || /\btool-check\b/.test(mine);
|
|
554
|
+
if (wantGuard || wantAlerts) {
|
|
555
|
+
/** @type {Record<string, any[]>} */
|
|
556
|
+
const hooks = {};
|
|
557
|
+
if (wantGuard) {
|
|
558
|
+
hooks.PreToolUse = [{ matcher: 'spawn_subagent', hooks: [{ type: 'command', command: `${self} guard`, timeout: 10 }] }];
|
|
559
|
+
// A subagent's stop clears the duplicate-spawn hold (the payload carries `subagentType`, not `agent_type`).
|
|
560
|
+
hooks.SubagentStop = [{ hooks: [{ type: 'command', command: `${self} subagent-receipt`, timeout: 15 }] }];
|
|
561
|
+
}
|
|
562
|
+
if (wantAlerts) {
|
|
563
|
+
// Grok accepts Claude's tool names in a matcher (Read is read_file) and its MCP calls as mcp__server__tool.
|
|
564
|
+
(hooks.PreToolUse ??= []).push({
|
|
565
|
+
matcher: 'Read|Grep',
|
|
566
|
+
hooks: [{ type: 'command', command: `${self} tool-limit --src grok`, timeout: 10 }],
|
|
567
|
+
});
|
|
568
|
+
hooks.PostToolUse = [
|
|
569
|
+
{ matcher: 'Bash|Read|Grep|WebFetch|mcp__.*', hooks: [{ type: 'command', command: `${self} tool-check --src grok`, timeout: 10 }] },
|
|
570
|
+
];
|
|
571
|
+
hooks.SessionStart = [{ hooks: [{ type: 'command', command: `${self} drift --hook --src grok`, timeout: 15 }] }];
|
|
572
|
+
}
|
|
523
573
|
mkdirSync(dirname(path), { recursive: true });
|
|
524
|
-
writeFileSync(
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
{
|
|
528
|
-
hooks: {
|
|
529
|
-
PreToolUse: [{ matcher: 'spawn_subagent', hooks: [{ type: 'command', command: `${self} guard`, timeout: 10 }] }],
|
|
530
|
-
// A subagent's stop clears the duplicate-spawn hold (the payload carries `subagentType`, not `agent_type`).
|
|
531
|
-
SubagentStop: [{ hooks: [{ type: 'command', command: `${self} subagent-receipt`, timeout: 15 }] }],
|
|
532
|
-
},
|
|
533
|
-
},
|
|
534
|
-
null,
|
|
535
|
-
2,
|
|
536
|
-
)}\n`,
|
|
537
|
-
);
|
|
538
|
-
changes.push('added the Grok subagent guard (matcher spawn_subagent) and its subagent-stop hook');
|
|
574
|
+
writeFileSync(path, `${JSON.stringify({ hooks }, null, 2)}\n`);
|
|
575
|
+
if (guard) changes.push('added the Grok subagent guard (matcher spawn_subagent) and its subagent-stop hook');
|
|
576
|
+
if (alerts) changes.push('added the Grok starting-context alert, large tool-output notice and fat-tool limit check');
|
|
539
577
|
}
|
|
540
578
|
return changes;
|
|
541
579
|
}
|
|
@@ -782,22 +820,29 @@ function grokSessionFiles(root, since, name) {
|
|
|
782
820
|
* @param {(name:string)=>boolean} keep
|
|
783
821
|
*/
|
|
784
822
|
function newestFile(dir, keep) {
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
823
|
+
return newestFiles(dir, keep)[0] ?? null;
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
/**
|
|
827
|
+
* Every file under `dir` that `keep` accepts, newest first.
|
|
828
|
+
* @param {string} dir
|
|
829
|
+
* @param {(name:string)=>boolean} keep
|
|
830
|
+
* @returns {string[]}
|
|
831
|
+
*/
|
|
832
|
+
function newestFiles(dir, keep) {
|
|
833
|
+
if (!existsSync(dir)) return [];
|
|
834
|
+
/** @type {{p:string, m:number}[]} */
|
|
835
|
+
const found = [];
|
|
788
836
|
/** @param {string} d */
|
|
789
837
|
const walk = (d) => {
|
|
790
838
|
for (const e of readdirSync(d, { withFileTypes: true })) {
|
|
791
839
|
const p = join(d, e.name);
|
|
792
840
|
if (e.isDirectory()) walk(p);
|
|
793
|
-
else if (keep(e.name)) {
|
|
794
|
-
const m = statSync(p).mtimeMs;
|
|
795
|
-
if (m > bestM) [best, bestM] = [p, m];
|
|
796
|
-
}
|
|
841
|
+
else if (keep(e.name)) found.push({ p, m: statSync(p).mtimeMs });
|
|
797
842
|
}
|
|
798
843
|
};
|
|
799
844
|
walk(dir);
|
|
800
|
-
return
|
|
845
|
+
return found.sort((a, b) => b.m - a.m).map((f) => f.p);
|
|
801
846
|
}
|
|
802
847
|
|
|
803
848
|
/** @param {string} path @param {string} text */
|
package/src/guard.mjs
CHANGED
|
@@ -160,9 +160,15 @@ export async function runGuard(hook, now, minutes, { preview = false } = {}) {
|
|
|
160
160
|
// Not blocked, but a window is tight: run a new Claude subagent on Sonnet instead of the main (usually Opus) model.
|
|
161
161
|
const input = hook?.tool_input ?? hook?.toolInput;
|
|
162
162
|
const tight = forecasts.find((x) => x.src === 'claude' && (x.verdict === 'AT_RISK' || x.verdict === 'NEAR'));
|
|
163
|
-
const type = String(input?.subagent_type ?? input?.subagentType ?? '');
|
|
163
|
+
const type = String(input?.subagent_type ?? input?.subagentType ?? input?.agent_type ?? '');
|
|
164
164
|
const pinned = isUnset(input?.model) && type && src ? pinnedModel(type, src) : undefined;
|
|
165
165
|
if (src === 'grok') return grokPinOrNotice(input, type, pinned, forecasts, now, preview, operation);
|
|
166
|
+
if (src === 'codex') {
|
|
167
|
+
// Codex has no Sonnet switch or model pin here; it gets the same "what this kind of subagent has cost" hint.
|
|
168
|
+
if (preview) return null;
|
|
169
|
+
const notice = spawnNotice(loadSubagents(now - 30 * 86400_000), type, undefined, 'codex');
|
|
170
|
+
return notice ? { notice } : null;
|
|
171
|
+
}
|
|
166
172
|
if (src !== 'claude') return null;
|
|
167
173
|
const model = pinned ?? input?.model;
|
|
168
174
|
if (!tight || !switchable(model)) {
|
|
@@ -287,6 +293,6 @@ function grokPinOrNotice(input, type, pinned, forecasts, now, preview, operation
|
|
|
287
293
|
}
|
|
288
294
|
if (preview) return null;
|
|
289
295
|
const win = forecasts.find((x) => x.src === 'grok' && x.win === '5h' && x.verdict !== 'RESET');
|
|
290
|
-
const notice = spawnNotice(loadSubagents(now - 30 * 86400_000), type, win);
|
|
296
|
+
const notice = spawnNotice(loadSubagents(now - 30 * 86400_000), type, win, 'grok');
|
|
291
297
|
return notice ? { notice } : null;
|
|
292
298
|
}
|
package/src/inflight.mjs
CHANGED
|
@@ -10,6 +10,7 @@ import { stateDir } from './store.mjs';
|
|
|
10
10
|
// 30 minutes is forgotten anyway: a missed stop must not hold the same prompt for the rest of the day.
|
|
11
11
|
|
|
12
12
|
export const INFLIGHT_MS = 30 * 60_000;
|
|
13
|
+
const ENCRYPTED = /^gAAAA[A-Za-z0-9_=-]{40,}$/; // a Fernet token, the shape Codex gave an encrypted spawn_agent message
|
|
13
14
|
|
|
14
15
|
/** @typedef {{sid:string, type:string, hash:string, t:number}} Inflight */
|
|
15
16
|
|
|
@@ -25,12 +26,16 @@ export function spawnIdentity(hook) {
|
|
|
25
26
|
const input = hook?.tool_input ?? hook?.toolInput ?? {};
|
|
26
27
|
// Grok re-runs a finished subagent with resume_from: the same prompt again is a continuation, not a duplicate.
|
|
27
28
|
if (input?.resume_from || input?.resumeFrom) return null;
|
|
28
|
-
|
|
29
|
+
// Codex names no type when the model leaves it out, and reports such a subagent as "default" when it stops.
|
|
30
|
+
const type = String(input?.subagent_type ?? input?.subagentType ?? input?.agent_type ?? (src === 'codex' ? 'default' : '')).trim();
|
|
29
31
|
// Claude and Grok send `prompt`; Codex spawn_agent sends `message` (or `items`, a list of text parts).
|
|
30
32
|
const items = Array.isArray(input?.items) ? input.items.map((x) => (typeof x === 'string' ? x : (x?.text ?? ''))).join(' ') : '';
|
|
31
|
-
|
|
33
|
+
let prompt = String(input?.prompt || input?.message || input?.description || input?.task || items || '')
|
|
32
34
|
.replace(/\s+/g, ' ')
|
|
33
35
|
.trim();
|
|
36
|
+
// Codex encrypts spawn_agent arguments (a live call carried a `gAAAA…` token as its message), and the same prompt encrypts
|
|
37
|
+
// differently each time, so identical prompts cannot be told apart by content. The task name the model gave it still can.
|
|
38
|
+
if (src === 'codex' && (!prompt || ENCRYPTED.test(prompt)) && input?.task_name) prompt = `task ${String(input.task_name).trim()}`;
|
|
34
39
|
const sid = String(hook?.session_id ?? hook?.sessionId ?? '').trim();
|
|
35
40
|
if (!type || !prompt || !sid) return null;
|
|
36
41
|
const hash = createHash('sha256').update(`${type.toLowerCase()}\0${prompt}`).digest('hex').slice(0, 16);
|
package/src/install.mjs
CHANGED
|
@@ -120,12 +120,7 @@ export function install({
|
|
|
120
120
|
isToolCheck,
|
|
121
121
|
);
|
|
122
122
|
changes.push('added the large tool-output notice');
|
|
123
|
-
upsertHook(
|
|
124
|
-
cfg,
|
|
125
|
-
'PreToolUse',
|
|
126
|
-
{ matcher: 'Bash|Read|Grep|WebFetch|mcp__.*', hooks: [{ type: 'command', command: `${self} tool-limit`, timeout: 10 }] },
|
|
127
|
-
isToolLimit,
|
|
128
|
-
);
|
|
123
|
+
upsertHook(cfg, 'PreToolUse', { matcher: 'Read|Grep', hooks: [{ type: 'command', command: `${self} tool-limit`, timeout: 10 }] }, isToolLimit);
|
|
129
124
|
changes.push('added the fat-tool limit check');
|
|
130
125
|
}
|
|
131
126
|
if (optimize) {
|
|
@@ -139,10 +134,34 @@ export function install({
|
|
|
139
134
|
upsertGuard(codex, { matcher: CODEX_MATCHER, hooks: [{ type: 'command', command: `${self} guard`, timeout: 10 }] });
|
|
140
135
|
// A subagent's stop clears the duplicate-spawn hold; without it a finished spawn blocks its own retry for 30 minutes.
|
|
141
136
|
upsertHook(codex, 'SubagentStop', { matcher: '', hooks: [{ type: 'command', command: `${self} subagent-receipt`, timeout: 15 }] }, isReceipt);
|
|
137
|
+
// Codex has no status line, so its limit notifications (limitcast notify on) are raised from a throttled Stop hook.
|
|
138
|
+
upsertHook(codex, 'Stop', { matcher: '', hooks: [{ type: 'command', command: `${self} codex-notify --hook`, timeout: 5 }] }, isCodexNotify);
|
|
139
|
+
writeSettings(codexPath, codex);
|
|
140
|
+
changes.push(
|
|
141
|
+
'added the Codex subagent guard and limit notifications (Codex runs them after you trust them: start Codex and approve the new hooks)',
|
|
142
|
+
);
|
|
143
|
+
}
|
|
144
|
+
if (alerts && existsSync(join(codexPath, '..'))) {
|
|
145
|
+
const codex = readSettings(codexPath);
|
|
146
|
+
backup(codexPath);
|
|
147
|
+
// Codex has no native Read/Grep controls. Keep result notices and remove the legacy generic MCP pre-call hold.
|
|
148
|
+
upsertHook(
|
|
149
|
+
codex,
|
|
150
|
+
'PostToolUse',
|
|
151
|
+
{ matcher: 'Bash|mcp__.*', hooks: [{ type: 'command', command: `${self} tool-check --src codex`, timeout: 10 }] },
|
|
152
|
+
isToolCheck,
|
|
153
|
+
);
|
|
154
|
+
if (codex.hooks?.PreToolUse) codex.hooks.PreToolUse = codex.hooks.PreToolUse.filter((h) => !isToolLimit(h));
|
|
155
|
+
upsertHook(
|
|
156
|
+
codex,
|
|
157
|
+
'SessionStart',
|
|
158
|
+
{ matcher: '', hooks: [{ type: 'command', command: `${self} drift --hook --src codex`, timeout: 15 }] },
|
|
159
|
+
isAlert,
|
|
160
|
+
);
|
|
142
161
|
writeSettings(codexPath, codex);
|
|
143
|
-
changes.push('added the Codex
|
|
162
|
+
changes.push('added the Codex starting-context alert, large tool-output notice and fat-tool limit check (approve the new hooks in Codex)');
|
|
144
163
|
}
|
|
145
|
-
if (grokPresent(grokDir)) changes.push(...installGrok({ guard, self, home: grokDir }));
|
|
164
|
+
if (grokPresent(grokDir)) changes.push(...installGrok({ guard, alerts, self, home: grokDir }));
|
|
146
165
|
if (optimize && existsSync(join(codexPath, '..'))) {
|
|
147
166
|
const codex = readSettings(codexPath);
|
|
148
167
|
backup(codexPath);
|
|
@@ -241,10 +260,14 @@ export function uninstall({ path = settingsPath(), codexPath = codexHooksPath(),
|
|
|
241
260
|
if (existsSync(codexPath)) {
|
|
242
261
|
const codex = readSettings(codexPath);
|
|
243
262
|
const list = codex.hooks?.PreToolUse ?? [];
|
|
244
|
-
|
|
263
|
+
const ours = (/** @type {any} */ h) => isOptimizer(h) || isReceipt(h) || isToolCheck(h) || isToolLimit(h) || isCodexNotify(h) || isAlert(h);
|
|
264
|
+
if (list.some(isGuard) || Object.values(codex.hooks ?? {}).some((entries) => entries.some(ours))) {
|
|
245
265
|
backup(codexPath);
|
|
246
|
-
codex.hooks.PreToolUse = list.filter((/** @type {any} */ h) => !isGuard(h));
|
|
266
|
+
codex.hooks.PreToolUse = list.filter((/** @type {any} */ h) => !isGuard(h) && !isToolLimit(h));
|
|
247
267
|
if (codex.hooks.SubagentStop) codex.hooks.SubagentStop = codex.hooks.SubagentStop.filter((/** @type {any} */ h) => !isReceipt(h));
|
|
268
|
+
if (codex.hooks.PostToolUse) codex.hooks.PostToolUse = codex.hooks.PostToolUse.filter((/** @type {any} */ h) => !isToolCheck(h));
|
|
269
|
+
if (codex.hooks.Stop) codex.hooks.Stop = codex.hooks.Stop.filter((/** @type {any} */ h) => !isCodexNotify(h));
|
|
270
|
+
if (codex.hooks.SessionStart) codex.hooks.SessionStart = codex.hooks.SessionStart.filter((/** @type {any} */ h) => !isAlert(h));
|
|
248
271
|
removeOptimizerHooks(codex);
|
|
249
272
|
writeSettings(codexPath, codex);
|
|
250
273
|
changes.push('removed the Codex subagent guard');
|
|
@@ -298,6 +321,7 @@ const isPromptCheck = runs(/\bprompt-check\b/);
|
|
|
298
321
|
const isReceipt = runs(/\bsubagent-receipt\b/);
|
|
299
322
|
const isToolCheck = runs(/\btool-check\b/);
|
|
300
323
|
const isToolLimit = runs(/\btool-limit\b/);
|
|
324
|
+
const isCodexNotify = runs(/\bcodex-notify\b/);
|
|
301
325
|
const isOptimizer = runs(/\b_optimize-hook\b/);
|
|
302
326
|
|
|
303
327
|
/** @param {string} path */
|
package/src/notify.mjs
CHANGED
|
@@ -14,6 +14,23 @@ const NAMES = { claude: 'Claude', codex: 'Codex', grok: 'Grok' };
|
|
|
14
14
|
|
|
15
15
|
export const notifyEnabled = () => existsSync(flag());
|
|
16
16
|
|
|
17
|
+
/**
|
|
18
|
+
* True at most once every few minutes (Codex has no status line, so a Stop hook asks this before it starts the background check).
|
|
19
|
+
* @param {number} now epoch ms
|
|
20
|
+
* @param {number} [gapMs]
|
|
21
|
+
*/
|
|
22
|
+
export function codexNotifyDue(now, gapMs = 180_000) {
|
|
23
|
+
const mark = join(stateDir(), 'notify-codex.at');
|
|
24
|
+
try {
|
|
25
|
+
if (now - Number(readFileSync(mark, 'utf8')) < gapMs) return false;
|
|
26
|
+
} catch {
|
|
27
|
+
/* never checked */
|
|
28
|
+
}
|
|
29
|
+
mkdirSync(stateDir(), { recursive: true });
|
|
30
|
+
writeFileSync(mark, String(now));
|
|
31
|
+
return true;
|
|
32
|
+
}
|
|
33
|
+
|
|
17
34
|
/** @param {boolean} on */
|
|
18
35
|
export function setNotify(on) {
|
|
19
36
|
mkdirSync(stateDir(), { recursive: true });
|
package/src/optimize-cli.mjs
CHANGED
|
@@ -21,6 +21,13 @@ export function runOptimizationHook(hook, host) {
|
|
|
21
21
|
});
|
|
22
22
|
if (job) startModelWorker(repo, job);
|
|
23
23
|
const context = [result.context, result.map ? repositoryMap(repo) : ''].filter(Boolean).join('\n\n');
|
|
24
|
+
if (context)
|
|
25
|
+
changeOptimization(repo, (state) => {
|
|
26
|
+
const m = (state.measurements ??= { injections: 0, contextChars: 0, estimatedContextTokens: 0 });
|
|
27
|
+
m.injections++;
|
|
28
|
+
m.contextChars += context.length;
|
|
29
|
+
m.estimatedContextTokens += Math.ceil(context.length / 4);
|
|
30
|
+
});
|
|
24
31
|
if (host === 'copilot') return context ? { additionalContext: context } : result.notice ? { additionalContext: result.notice } : {};
|
|
25
32
|
return {
|
|
26
33
|
...(result.notice ? { systemMessage: result.notice } : {}),
|
|
@@ -125,6 +132,12 @@ export function runOptimize(args, cwd = process.cwd()) {
|
|
|
125
132
|
HOSTS.map((h) => [h, { completedSessions: state.hosts[h]?.completed ?? 0, proposed: capabilityProposals(state, h, configuredServers(h)) }]),
|
|
126
133
|
),
|
|
127
134
|
receipts: state.receipts,
|
|
135
|
+
measurements: {
|
|
136
|
+
injectedContext: state.measurements ?? { injections: 0, contextChars: 0, estimatedContextTokens: 0 },
|
|
137
|
+
modelCalls: state.model?.receipts ?? [],
|
|
138
|
+
taskSuccess: 'unmeasured; completed sessions are not proof of task success',
|
|
139
|
+
netSavings: 'unproven; injected context and model calls add overhead',
|
|
140
|
+
},
|
|
128
141
|
applied: Object.fromEntries(Object.entries(state.applied ?? {}).map(([h, a]) => [h, a.names])),
|
|
129
142
|
};
|
|
130
143
|
}
|
package/src/overhead.mjs
CHANGED
|
@@ -30,53 +30,79 @@ export function drift(prev, cur) {
|
|
|
30
30
|
return { delta: cur.chars - prev.chars, grew, alert: cur.chars - prev.chars >= ALERT_CHARS || grew.length > 0 };
|
|
31
31
|
}
|
|
32
32
|
|
|
33
|
-
|
|
33
|
+
/** Claude Code's record is overhead.json (`saved` and `results` read it); Codex and Grok keep their own beside it. @param {string} [host] */
|
|
34
|
+
const file = (host = 'claude') => join(stateDir(), host === 'claude' ? 'overhead.json' : `overhead-${host}.json`);
|
|
34
35
|
|
|
35
|
-
/**
|
|
36
|
-
|
|
36
|
+
/**
|
|
37
|
+
* Codex and Grok sessions have no transcript of pieces, so their starting context is the few sizes their logs hold.
|
|
38
|
+
* @param {'codex'|'grok'} host
|
|
39
|
+
* @param {{at?:number, agentsMd:number, base?:number, prompt?:number, tools?:number}} s sizes in characters
|
|
40
|
+
* @returns {Snapshot}
|
|
41
|
+
*/
|
|
42
|
+
export function hostSnapshot(host, s) {
|
|
43
|
+
/** @type {Record<string, number>} */
|
|
44
|
+
const items =
|
|
45
|
+
host === 'codex'
|
|
46
|
+
? { 'Instruction files|AGENTS.md': s.agentsMd, "Codex|Codex's own instructions": s.base ?? 0 }
|
|
47
|
+
: { 'Instruction files|AGENTS.md': s.agentsMd, 'Grok|system prompt': s.prompt ?? 0, 'Grok|tool definitions': s.tools ?? 0 };
|
|
48
|
+
return { at: s.at ?? 0, chars: Object.values(items).reduce((a, c) => a + c, 0), items };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* @param {string} [host]
|
|
53
|
+
* @returns {{first:Snapshot, last:Snapshot}|null}
|
|
54
|
+
*/
|
|
55
|
+
export function loadOverhead(host = 'claude') {
|
|
37
56
|
try {
|
|
38
|
-
return JSON.parse(readFileSync(file(), 'utf8'));
|
|
57
|
+
return JSON.parse(readFileSync(file(host), 'utf8'));
|
|
39
58
|
} catch {
|
|
40
59
|
return null;
|
|
41
60
|
}
|
|
42
61
|
}
|
|
43
62
|
|
|
44
|
-
/**
|
|
45
|
-
|
|
63
|
+
/**
|
|
64
|
+
* @param {{first:Snapshot, last:Snapshot}} s
|
|
65
|
+
* @param {string} [host]
|
|
66
|
+
*/
|
|
67
|
+
export function saveOverhead(s, host = 'claude') {
|
|
46
68
|
mkdirSync(stateDir(), { recursive: true });
|
|
47
|
-
writeFileSync(file(), JSON.stringify(s));
|
|
69
|
+
writeFileSync(file(host), JSON.stringify(s));
|
|
48
70
|
}
|
|
49
71
|
|
|
50
72
|
/**
|
|
51
73
|
* Record `cur` and return what changed since the last recorded session (null the first time).
|
|
52
74
|
* A snapshot of the same session as last time changes nothing.
|
|
53
75
|
* @param {Snapshot} cur
|
|
76
|
+
* @param {string} [host]
|
|
54
77
|
*/
|
|
55
|
-
export function recordOverhead(cur) {
|
|
56
|
-
const s = existsSync(file()) ? loadOverhead() : null;
|
|
78
|
+
export function recordOverhead(cur, host = 'claude') {
|
|
79
|
+
const s = existsSync(file(host)) ? loadOverhead(host) : null;
|
|
57
80
|
if (!s) {
|
|
58
|
-
saveOverhead({ first: cur, last: cur });
|
|
81
|
+
saveOverhead({ first: cur, last: cur }, host);
|
|
59
82
|
return null;
|
|
60
83
|
}
|
|
61
84
|
if (cur.at === s.last.at) return { delta: 0, grew: [], alert: false };
|
|
62
85
|
const d = drift(s.last, cur);
|
|
63
|
-
saveOverhead({ first: s.first, last: cur });
|
|
86
|
+
saveOverhead({ first: s.first, last: cur }, host);
|
|
64
87
|
return d;
|
|
65
88
|
}
|
|
66
89
|
|
|
67
90
|
const tok = (/** @type {number} */ chars) => Math.round(chars / 4);
|
|
68
91
|
const label = (/** @type {string} */ key) => key.replace('|', ': ').replace(/\/Users\/[^/]+/, '~');
|
|
92
|
+
const NAMES = /** @type {Record<string, string>} */ ({ claude: 'Claude Code', codex: 'Codex', grok: 'Grok' });
|
|
69
93
|
|
|
70
94
|
/**
|
|
71
95
|
* One-line alert for the user (never the model) when starting context grew.
|
|
72
96
|
* @param {ReturnType<typeof drift>} d
|
|
97
|
+
* @param {string} [host]
|
|
73
98
|
*/
|
|
74
|
-
export function driftMessage(d) {
|
|
99
|
+
export function driftMessage(d, host = 'claude') {
|
|
75
100
|
const items = d.grew
|
|
76
101
|
.slice(0, 3)
|
|
77
102
|
.map((g) => `${label(g.key)} ${g.isNew ? 'new' : '+'}~${(tok(g.delta) / 1000).toFixed(1)}k`)
|
|
78
103
|
.join(', ');
|
|
79
|
-
|
|
104
|
+
const more = host === 'claude' ? ' Run `limitcast trim` for details.' : ` Run \`limitcast trim --${host}\` for details.`;
|
|
105
|
+
return `limitcast: your ${NAMES[host] ?? host} starting context grew ~${(tok(d.delta) / 1000).toFixed(1)}k tokens since your last session${items ? ` (${items})` : ''}.${more}`;
|
|
80
106
|
}
|
|
81
107
|
|
|
82
108
|
/**
|
package/src/prices.mjs
CHANGED
|
@@ -4,13 +4,15 @@ import { join } from 'node:path';
|
|
|
4
4
|
import { stateDir } from './store.mjs';
|
|
5
5
|
|
|
6
6
|
// What your tokens would cost at the API's list prices ("API-equivalent cost"). A subscription is not billed this way:
|
|
7
|
-
// it is a yardstick for what the plan covers. Claude and
|
|
7
|
+
// it is a yardstick for what the plan covers. Claude, Grok and the OpenAI models Codex runs; any other model is left out,
|
|
8
|
+
// never priced at 0.
|
|
8
9
|
|
|
9
10
|
/**
|
|
10
11
|
* USD per million tokens. input/output: base prices; readX: cache read as a multiple of input; over: the prices that
|
|
11
12
|
* apply to a call whose whole prompt is above `above` tokens. Cache writes default to 1.25x input (5 minutes) or 2x
|
|
12
13
|
* (1 hour) for Claude; Grok sets writeX 1 (xAI lists cached input, not a write multiplier).
|
|
13
|
-
* Sources: platform.claude.com/docs/en/about-claude/pricing and docs.x.ai/developers/models, read 2026-10-26
|
|
14
|
+
* Sources: platform.claude.com/docs/en/about-claude/pricing and docs.x.ai/developers/models, read 2026-10-26 (xAI rows checked
|
|
15
|
+
* again 2026-11-13 against docs.x.ai/developers/pricing); developers.openai.com/api/docs/pricing, read 2026-11-13.
|
|
14
16
|
* Override or add models in ~/.local/state/limitcast/prices.json:
|
|
15
17
|
* {"models": {"claude-opus-4-1": {"input": 15, "output": 75, "readX": 0.1}}}.
|
|
16
18
|
* @typedef {{input:number, output:number, readX:number, writeX?:number, write1hX?:number, over?:{above:number, input:number, output:number, readX?:number}}} Price
|
|
@@ -28,6 +30,11 @@ export const PRICES = {
|
|
|
28
30
|
'grok-4.3': { input: 1.25, output: 2.5, readX: 0.16, writeX: 1, write1hX: 1, over: { above: 200_000, input: 2.5, output: 5 } },
|
|
29
31
|
'grok-4.20': { input: 1.25, output: 2.5, readX: 0.16, writeX: 1, write1hX: 1, over: { above: 200_000, input: 2.5, output: 5 } },
|
|
30
32
|
'grok-build-0.1': { input: 1, output: 2, readX: 0.2, writeX: 1, write1hX: 1, over: { above: 200_000, input: 2, output: 4 } },
|
|
33
|
+
// OpenAI (Codex): cached input is listed in $/1M and a Codex log records no cache writes. Above 272k prompt tokens the whole
|
|
34
|
+
// request bills 2x input and cache rates and 1.5x output. gpt-5.6-sol's price is promotional until 2026-11-30.
|
|
35
|
+
// `codex-auto-review` is a routing alias OpenAI lists no price for, so it stays unpriced.
|
|
36
|
+
'gpt-6.1-sol': { input: 2, output: 10, readX: 0.05, over: { above: 272_000, input: 4, output: 15 } },
|
|
37
|
+
'gpt-5.6-sol': { input: 4, output: 20, readX: 0.1, over: { above: 272_000, input: 8, output: 30 } },
|
|
31
38
|
};
|
|
32
39
|
|
|
33
40
|
const WRITE_5M = 1.25;
|