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/capabilities.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { execFileSync } from 'node:child_process';
|
|
2
|
-
import { existsSync, lstatSync, mkdirSync, readFileSync, statSync, unlinkSync } from 'node:fs';
|
|
2
|
+
import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, statSync, unlinkSync } from 'node:fs';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
3
4
|
import { dirname, join, relative, sep } from 'node:path';
|
|
4
5
|
import { codexConfigPath, codexServers } from './codex.mjs';
|
|
5
6
|
import { grokServers } from './grok.mjs';
|
|
@@ -22,16 +23,23 @@ export function configuredServers(host) {
|
|
|
22
23
|
}
|
|
23
24
|
|
|
24
25
|
/**
|
|
25
|
-
* Add `[mcp_servers.<name>] enabled = false` tables to a project config.toml.
|
|
26
|
-
*
|
|
26
|
+
* Add `[mcp_servers.<name>] enabled = false` tables to a project config.toml. Refuses a server the file already configures.
|
|
27
|
+
* Codex merges the table into the user-level definition, which stays where it is (command, env). Grok replaces the server
|
|
28
|
+
* with the project's entry whole, and ignores one that has no command; `stub` writes a command that never runs, because the
|
|
29
|
+
* server is disabled, so nothing of the user's definition (arguments, tokens, headers) is copied into the repository.
|
|
30
|
+
* @param {string} text
|
|
31
|
+
* @param {string[]} names
|
|
32
|
+
* @param {boolean} [stub]
|
|
27
33
|
*/
|
|
28
|
-
export function patchMcpServers(text, names) {
|
|
34
|
+
export function patchMcpServers(text, names, stub = false) {
|
|
29
35
|
const existing = codexServers(text);
|
|
30
36
|
for (const name of names) {
|
|
31
37
|
if (!/^[A-Za-z0-9_-]{1,64}$/.test(name)) throw new Error(`unsupported MCP server name ${name}`);
|
|
32
38
|
if (existing.some((s) => s.name === name)) throw new Error(`preserve explicit ${name} server setting; change it yourself`);
|
|
33
39
|
}
|
|
34
|
-
const tables = names
|
|
40
|
+
const tables = names
|
|
41
|
+
.map((name) => `[mcp_servers.${name}]\n${stub ? 'command = "true" # never runs: the server is off\n' : ''}enabled = false # limitcast optimizer`)
|
|
42
|
+
.join('\n\n');
|
|
35
43
|
const body = text.trimEnd();
|
|
36
44
|
return `${body ? `${body}\n\n` : ''}${tables}\n`;
|
|
37
45
|
}
|
|
@@ -100,6 +108,11 @@ export function applyCapabilities(repo, host, names, { validate = host === 'grok
|
|
|
100
108
|
throw new Error('choose proposed Claude tools, or Codex or Grok capabilities and MCP servers');
|
|
101
109
|
const file = configPath(repo, host);
|
|
102
110
|
safePath(repo, file);
|
|
111
|
+
if (host !== 'claude' && [homedir(), realpathSync(homedir())].includes(repo.root))
|
|
112
|
+
// In the home directory the "project" file is the user's own config, which already holds every server it could turn off.
|
|
113
|
+
throw new Error(
|
|
114
|
+
`this repository is your home directory, so ${CONFIG[host]} is your own ${host === 'codex' ? 'Codex' : 'Grok'} config; use \`limitcast trim --${host} --apply\` to turn servers off everywhere`,
|
|
115
|
+
);
|
|
103
116
|
if (host === 'codex') validate(repo);
|
|
104
117
|
const servers = configuredServers(host);
|
|
105
118
|
const result = changeOptimization(repo, (state) => {
|
|
@@ -115,7 +128,7 @@ export function applyCapabilities(repo, host, names, { validate = host === 'grok
|
|
|
115
128
|
after = before ?? '';
|
|
116
129
|
if (features.length) after = patchCodexCapabilities(after, features);
|
|
117
130
|
if (mcp.length) after = patchMcpServers(after, mcp);
|
|
118
|
-
} else if (host === 'grok') after = patchMcpServers(before ?? '', names);
|
|
131
|
+
} else if (host === 'grok') after = patchMcpServers(before ?? '', names, true);
|
|
119
132
|
else {
|
|
120
133
|
const cfg = JSON.parse(before ?? '{}');
|
|
121
134
|
if (!cfg || typeof cfg !== 'object' || Array.isArray(cfg)) throw new Error('settings must be an object');
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
import { spawn } from 'node:child_process';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { createInterface } from 'node:readline';
|
|
5
|
+
|
|
6
|
+
// Codex trusts a hook by a hash of its definition (`trusted_hash` in config.toml), which cannot be recomputed from outside:
|
|
7
|
+
// a hook that was edited keeps its key and still fails the hash. So ask Codex itself, the way its own /hooks screen does:
|
|
8
|
+
// the app server's `hooks/list` says each hook's trust status.
|
|
9
|
+
|
|
10
|
+
/** @typedef {{key:string, trustStatus:string, enabled:boolean, command:string}} HookRow */
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Every hook Codex has configured for `cwd`, with its trust status. Null when Codex does not answer.
|
|
14
|
+
* @param {{cwd?:string, timeoutMs?:number, command?:string[]}} [o] command: the app-server command line, `codex app-server` by default
|
|
15
|
+
* @returns {Promise<HookRow[]|null>}
|
|
16
|
+
*/
|
|
17
|
+
export function codexHooks({ cwd = homedir(), timeoutMs = 15_000, command = ['codex', 'app-server'] } = {}) {
|
|
18
|
+
return new Promise((resolve) => {
|
|
19
|
+
let child;
|
|
20
|
+
try {
|
|
21
|
+
child = spawn(command[0], command.slice(1), { cwd, stdio: ['pipe', 'pipe', 'ignore'] });
|
|
22
|
+
} catch {
|
|
23
|
+
resolve(null);
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
let done = false;
|
|
27
|
+
/** @param {HookRow[]|null} rows */
|
|
28
|
+
const finish = (rows) => {
|
|
29
|
+
if (done) return;
|
|
30
|
+
done = true;
|
|
31
|
+
clearTimeout(timer);
|
|
32
|
+
child.kill();
|
|
33
|
+
resolve(rows);
|
|
34
|
+
};
|
|
35
|
+
const timer = setTimeout(() => finish(null), timeoutMs);
|
|
36
|
+
child.on('error', () => finish(null));
|
|
37
|
+
child.on('exit', () => finish(null));
|
|
38
|
+
/** @param {unknown} msg */
|
|
39
|
+
const send = (msg) => child.stdin.write(`${JSON.stringify(msg)}\n`);
|
|
40
|
+
createInterface({ input: child.stdout }).on('line', (line) => {
|
|
41
|
+
let msg;
|
|
42
|
+
try {
|
|
43
|
+
msg = JSON.parse(line);
|
|
44
|
+
} catch {
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
if (msg?.id === 1) {
|
|
48
|
+
send({ method: 'initialized' });
|
|
49
|
+
send({ id: 2, method: 'hooks/list', params: { cwds: [cwd] } });
|
|
50
|
+
} else if (msg?.id === 2) {
|
|
51
|
+
if (msg.error) return finish(null);
|
|
52
|
+
const rows = (msg.result?.data ?? []).flatMap((/** @type {any} */ entry) => entry?.hooks ?? []);
|
|
53
|
+
finish(
|
|
54
|
+
rows.map((/** @type {any} */ h) => ({
|
|
55
|
+
key: String(h.key ?? ''),
|
|
56
|
+
trustStatus: String(h.trustStatus ?? ''),
|
|
57
|
+
enabled: h.enabled !== false,
|
|
58
|
+
command: String(h.command ?? ''),
|
|
59
|
+
})),
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
});
|
|
63
|
+
send({ id: 1, method: 'initialize', params: { clientInfo: { name: 'limitcast-doctor', title: 'limitcast doctor', version: '1' } } });
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Doctor line for limitcast's own hooks, from what Codex says about them. Null when none of them is configured.
|
|
69
|
+
* @param {HookRow[]} rows
|
|
70
|
+
* @returns {{ok:boolean, line:string}|null}
|
|
71
|
+
*/
|
|
72
|
+
export function trustLine(rows) {
|
|
73
|
+
const mine = rows.filter((h) => /limitcast/i.test(h.command));
|
|
74
|
+
if (!mine.length) return null;
|
|
75
|
+
const waiting = mine.filter((h) => h.trustStatus !== 'trusted');
|
|
76
|
+
if (!waiting.length) return { ok: true, line: `Codex hooks: all ${mine.length} limitcast hooks are trusted` };
|
|
77
|
+
const what = waiting
|
|
78
|
+
.map((h) => h.key.replace(/^.*[\\/]/, '').replace(/^hooks\.json:/, ''))
|
|
79
|
+
.slice(0, 4)
|
|
80
|
+
.join(', ');
|
|
81
|
+
return {
|
|
82
|
+
ok: false,
|
|
83
|
+
line: `Codex hooks: ${waiting.length} of ${mine.length} limitcast hooks are not trusted (${what}): start Codex, open /hooks and approve them. Codex skips an unreviewed hook`,
|
|
84
|
+
};
|
|
85
|
+
}
|
package/src/codex.mjs
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
// @ts-check
|
|
2
|
-
import {
|
|
2
|
+
import { copyFileSync, createReadStream, existsSync, statSync } from 'node:fs';
|
|
3
3
|
import { homedir } from 'node:os';
|
|
4
4
|
import { join } from 'node:path';
|
|
5
5
|
import { createInterface } from 'node:readline';
|
|
6
|
-
import { stateDir } from './store.mjs';
|
|
6
|
+
import { stateDir, withStateLock } from './store.mjs';
|
|
7
|
+
import { commitTransaction, editText, readLedger, recoverTransaction } from './transaction.mjs';
|
|
7
8
|
import { jsonlFiles } from './usage.mjs';
|
|
8
9
|
|
|
9
10
|
// `limitcast trim --codex`: what Codex loads before you type (AGENTS.md, MCP servers) and which servers you never use.
|
|
@@ -71,19 +72,30 @@ export function setEnabled(toml, changes) {
|
|
|
71
72
|
*/
|
|
72
73
|
export async function codexUsedServers(since, root = join(codexHome(), 'sessions')) {
|
|
73
74
|
const used = new Set();
|
|
75
|
+
used.observed = false;
|
|
76
|
+
used.complete = true;
|
|
74
77
|
for (const f of jsonlFiles(root, since, (n) => n.startsWith('rollout-'))) {
|
|
75
78
|
const rl = createInterface({ input: createReadStream(f), crlfDelay: Infinity });
|
|
76
79
|
for await (const line of rl) {
|
|
77
|
-
if (line.
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
80
|
+
if (!line.trim()) continue;
|
|
81
|
+
try {
|
|
82
|
+
const row = JSON.parse(line);
|
|
83
|
+
const p = row.payload;
|
|
84
|
+
const item = p?.item;
|
|
85
|
+
if (row.type === 'response_item' && ['function_call', 'custom_tool_call'].includes(p?.type)) {
|
|
86
|
+
used.observed = true;
|
|
87
|
+
const server = /^mcp__(.+?)(?:__|$)/.exec(p.namespace ?? '')?.[1] ?? /^mcp__(.+?)__/.exec(p.name ?? '')?.[1];
|
|
88
|
+
if (server) used.add(norm(server));
|
|
89
|
+
if (typeof p.name !== 'string') used.complete = false;
|
|
90
|
+
if ([p.name, p.namespace].some((n) => typeof n === 'string' && n.startsWith('mcp__')) && !server) used.complete = false;
|
|
91
|
+
} else if (item?.type === 'McpToolCall') {
|
|
92
|
+
used.observed = true;
|
|
93
|
+
if (typeof item.server === 'string') used.add(norm(item.server));
|
|
94
|
+
else used.complete = false;
|
|
95
|
+
} else if (item?.type === 'CommandExecution') used.observed = true;
|
|
96
|
+
else if (/ToolCall$/.test(item?.type ?? '')) used.complete = false;
|
|
97
|
+
} catch {
|
|
98
|
+
used.complete = false;
|
|
87
99
|
}
|
|
88
100
|
}
|
|
89
101
|
}
|
|
@@ -91,34 +103,64 @@ export async function codexUsedServers(since, root = join(codexHome(), 'sessions
|
|
|
91
103
|
}
|
|
92
104
|
|
|
93
105
|
/**
|
|
94
|
-
*
|
|
95
|
-
*
|
|
106
|
+
* What a rollout's head shows of how the session started. A subagent's rollout is its own thread (forked, with its own
|
|
107
|
+
* instructions), so it says nothing about what your interactive sessions load.
|
|
108
|
+
* @param {string} file
|
|
109
|
+
* @returns {Promise<{subagent:boolean, agentsMd:number, base:number, first?:number, at?:number}>}
|
|
96
110
|
*/
|
|
97
|
-
|
|
98
|
-
const files = jsonlFiles(root, 0, (n) => n.startsWith('rollout-'))
|
|
99
|
-
.map((p) => ({ p, m: statSync(p).mtimeMs }))
|
|
100
|
-
.sort((a, b) => b.m - a.m);
|
|
101
|
-
if (!files.length) return null;
|
|
111
|
+
async function rolloutHead(file) {
|
|
102
112
|
let agentsMd = 0;
|
|
103
113
|
let base = 0;
|
|
114
|
+
let subagent = false;
|
|
115
|
+
/** @type {number|undefined} */
|
|
116
|
+
let first;
|
|
117
|
+
/** @type {number|undefined} */
|
|
118
|
+
let at;
|
|
104
119
|
let n = 0;
|
|
105
|
-
const rl = createInterface({ input: createReadStream(
|
|
120
|
+
const rl = createInterface({ input: createReadStream(file), crlfDelay: Infinity });
|
|
106
121
|
for await (const line of rl) {
|
|
107
|
-
if (++n >
|
|
122
|
+
if (++n > 400) break;
|
|
108
123
|
try {
|
|
109
124
|
const ev = JSON.parse(line);
|
|
110
|
-
if (ev.type === 'session_meta')
|
|
125
|
+
if (ev.type === 'session_meta') {
|
|
126
|
+
base = String(ev.payload?.base_instructions?.text ?? '').length;
|
|
127
|
+
subagent = ev.payload?.thread_source === 'subagent' || Boolean(ev.payload?.source?.subagent);
|
|
128
|
+
const started = Date.parse(ev.payload?.timestamp ?? ev.timestamp);
|
|
129
|
+
if (Number.isFinite(started)) at = started;
|
|
130
|
+
}
|
|
111
131
|
if (ev.type === 'world_state') agentsMd = String(ev.payload?.state?.agents_md?.text ?? '').length;
|
|
132
|
+
const total = ev?.payload?.info?.total_token_usage;
|
|
133
|
+
if (total?.input_tokens) {
|
|
134
|
+
first = total.input_tokens; // the first model call's whole prompt: what a session starts with, measured
|
|
135
|
+
break;
|
|
136
|
+
}
|
|
112
137
|
} catch {
|
|
113
138
|
/* skip */
|
|
114
139
|
}
|
|
115
140
|
}
|
|
116
141
|
rl.close();
|
|
117
|
-
return { agentsMd, base };
|
|
142
|
+
return { subagent, agentsMd, base, ...(first ? { first } : {}), ...(at ? { at } : {}) };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Sizes from the newest interactive rollout's head: the AGENTS.md chain Codex loaded and its own base instructions
|
|
147
|
+
* (characters), `first`, the tokens of its first model call when the log reaches one, and `at`, when it started.
|
|
148
|
+
* @returns {Promise<{agentsMd:number, base:number, first?:number, at?:number}|null>}
|
|
149
|
+
*/
|
|
150
|
+
export async function codexStartup(root = join(codexHome(), 'sessions')) {
|
|
151
|
+
const files = jsonlFiles(root, 0, (n) => n.startsWith('rollout-'))
|
|
152
|
+
.map((p) => ({ p, m: statSync(p).mtimeMs }))
|
|
153
|
+
.sort((a, b) => b.m - a.m)
|
|
154
|
+
.slice(0, 40);
|
|
155
|
+
for (const f of files) {
|
|
156
|
+
const { subagent, ...sizes } = await rolloutHead(f.p);
|
|
157
|
+
if (!subagent) return sizes;
|
|
158
|
+
}
|
|
159
|
+
return null;
|
|
118
160
|
}
|
|
119
161
|
|
|
120
162
|
/**
|
|
121
|
-
* @param {{servers:{name:string, enabled:boolean|undefined}[], used:Set<string>, usedMonth?:Set<string>|null, startup:{agentsMd:number, base:number}|null, days:number, pro:boolean, keep?:string[]}} r
|
|
163
|
+
* @param {{servers:{name:string, enabled:boolean|undefined}[], used:Set<string>, usedMonth?:Set<string>|null, startup:{agentsMd:number, base:number, first?:number}|null, days:number, pro:boolean, keep?:string[]}} r
|
|
122
164
|
* keep: the `trim keep` list; unused servers on it are reported as kept and left out of `unused`.
|
|
123
165
|
* usedMonth: normalized names used in 30 days. Servers in it stay out of `unused`.
|
|
124
166
|
*/
|
|
@@ -126,19 +168,28 @@ export function codexTrimReport({ servers, used, usedMonth = null, startup, days
|
|
|
126
168
|
const on = servers.filter((s) => s.enabled !== false);
|
|
127
169
|
const idle = on.filter((s) => !used.has(norm(s.name)));
|
|
128
170
|
const kept = idle.filter((s) => keep.some((k) => norm(k) === norm(s.name)));
|
|
171
|
+
const history = usedMonth ?? used;
|
|
172
|
+
const unknown = history.complete === false || history.observed === false ? idle.filter((s) => !kept.includes(s)) : [];
|
|
129
173
|
const standing = usedMonth ? idle.filter((s) => !kept.includes(s) && usedMonth.has(norm(s.name))) : [];
|
|
130
|
-
const unused = idle.filter((s) => !kept.includes(s) && !standing.includes(s));
|
|
174
|
+
const unused = idle.filter((s) => !kept.includes(s) && !standing.includes(s) && !unknown.includes(s));
|
|
131
175
|
const tok = (/** @type {number} */ c) => `${(c / 4000).toFixed(1)}k`;
|
|
132
176
|
const out = ['# limitcast trim --codex', ''];
|
|
133
177
|
if (startup)
|
|
134
178
|
out.push(
|
|
135
|
-
|
|
179
|
+
startup.first
|
|
180
|
+
? `Your latest Codex session started with ${(startup.first / 1000).toFixed(1)}k tokens on its first call (measured): ~${tok(startup.agentsMd)} of AGENTS.md (your instruction files), ~${tok(startup.base)} of Codex's own instructions, and the rest tool definitions and environment context, all re-sent on every turn.`
|
|
181
|
+
: `Codex sessions start with ~${tok(startup.agentsMd)} tokens of AGENTS.md (your instruction files) and ~${tok(startup.base)} of Codex's own instructions, re-sent on every turn.`,
|
|
136
182
|
'',
|
|
137
183
|
);
|
|
138
184
|
out.push(`## MCP servers: ${on.length} on, ${unused.length + standing.length} not used in ${days} days`);
|
|
185
|
+
if (unknown.length)
|
|
186
|
+
out.push(
|
|
187
|
+
'',
|
|
188
|
+
`Usage history is missing or incomplete; leaving ${unknown.length} unverified servers on. No pruning is authorized by missing telemetry.`,
|
|
189
|
+
);
|
|
139
190
|
if (standing.length)
|
|
140
191
|
out.push('', `${standing.length} used in the last 30 days, so \`trim --apply\` leaves them on:`, ...standing.map((s) => `- ${s.name}`));
|
|
141
|
-
if (!unused.length) out.push(kept.length || standing.length ? 'Nothing else to turn off.' : 'Every server that is on was used.');
|
|
192
|
+
if (!unused.length) out.push(kept.length || standing.length || unknown.length ? 'Nothing else to turn off.' : 'Every server that is on was used.');
|
|
142
193
|
else if (pro)
|
|
143
194
|
out.push(
|
|
144
195
|
...unused.map((s) => `- ${s.name}`),
|
|
@@ -156,25 +207,15 @@ export function codexTrimReport({ servers, used, usedMonth = null, startup, days
|
|
|
156
207
|
unused: unused.map((s) => s.name),
|
|
157
208
|
standing: standing.map((s) => s.name),
|
|
158
209
|
kept: kept.map((s) => s.name),
|
|
210
|
+
unknown: unknown.map((s) => s.name),
|
|
159
211
|
};
|
|
160
212
|
}
|
|
161
213
|
|
|
162
|
-
/** @param {string} path @param {string} text */
|
|
163
|
-
function writeText(path, text) {
|
|
164
|
-
const tmp = `${path}.limitcast-tmp`;
|
|
165
|
-
const mode = existsSync(path) ? statSync(path).mode & 0o777 : 0o600;
|
|
166
|
-
writeFileSync(tmp, text, { mode });
|
|
167
|
-
chmodSync(tmp, mode);
|
|
168
|
-
renameSync(tmp, path);
|
|
169
|
-
}
|
|
170
|
-
|
|
171
214
|
/** @returns {{at:number, servers:{name:string, prev:boolean|null}[]}[]} */
|
|
172
215
|
function loadLedger() {
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
return [];
|
|
177
|
-
}
|
|
216
|
+
const entries = readLedger(ledgerPath());
|
|
217
|
+
if (entries.some((e) => !Array.isArray(e.servers))) throw new Error('invalid Codex trim ledger');
|
|
218
|
+
return entries;
|
|
178
219
|
}
|
|
179
220
|
|
|
180
221
|
/**
|
|
@@ -182,31 +223,41 @@ function loadLedger() {
|
|
|
182
223
|
* @param {string[]} names
|
|
183
224
|
*/
|
|
184
225
|
export function applyCodexTrim(names, { now = Date.now(), path = codexConfigPath() } = {}) {
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
226
|
+
return withStateLock(() => {
|
|
227
|
+
recoverTransaction(ledgerPath());
|
|
228
|
+
const ledger = loadLedger();
|
|
229
|
+
if (!names.length || !existsSync(path)) return [];
|
|
230
|
+
let toml;
|
|
231
|
+
const update = editText(path, (text) => {
|
|
232
|
+
toml = text;
|
|
233
|
+
return setEnabled(text, Object.fromEntries(names.map((n) => [n, false])));
|
|
234
|
+
});
|
|
235
|
+
const before = new Map(codexServers(toml).map((s) => [s.name, s.enabled]));
|
|
236
|
+
copyFileSync(path, `${path}.limitcast-backup-${new Date(now).toISOString().replace(/[:.]/g, '-')}`);
|
|
237
|
+
const servers = names.map((name) => ({ name, prev: before.get(name) ?? null }));
|
|
238
|
+
commitTransaction(ledgerPath(), [...ledger, { at: now, servers }], [update]);
|
|
239
|
+
return servers;
|
|
240
|
+
});
|
|
194
241
|
}
|
|
195
242
|
|
|
196
243
|
/** Reverse the last --apply: each server goes back to its previous setting (or no `enabled` key). */
|
|
197
244
|
export function undoCodexTrim({ path = codexConfigPath() } = {}) {
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
245
|
+
return withStateLock(() => {
|
|
246
|
+
recoverTransaction(ledgerPath());
|
|
247
|
+
const ledger = loadLedger();
|
|
248
|
+
const last = ledger.pop();
|
|
249
|
+
if (!last || !existsSync(path)) return null;
|
|
250
|
+
const update = editText(path, (toml) => {
|
|
251
|
+
// Only servers still off: anything turned back on since is left as the user set it.
|
|
252
|
+
const off = new Set(
|
|
253
|
+
codexServers(toml)
|
|
254
|
+
.filter((s) => s.enabled === false)
|
|
255
|
+
.map((s) => s.name),
|
|
256
|
+
);
|
|
257
|
+
return setEnabled(toml, Object.fromEntries(last.servers.filter((s) => off.has(s.name)).map((s) => [s.name, s.prev])));
|
|
258
|
+
});
|
|
259
|
+
copyFileSync(path, `${path}.limitcast-backup-${new Date().toISOString().replace(/[:.]/g, '-')}`);
|
|
260
|
+
commitTransaction(ledgerPath(), ledger, [update]);
|
|
261
|
+
return last;
|
|
262
|
+
});
|
|
212
263
|
}
|