claude-memory-admin 1.9.0 → 1.10.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 +41 -6
- package/package.json +1 -1
- package/public/state.mjs +2 -2
- package/public/store.mjs +8 -4
- package/public/styles.css +1 -1
- package/public/ui.mjs +12 -0
- package/public/views/cost.mjs +231 -0
- package/public/views/environment.mjs +2 -0
- package/public/views/header.mjs +16 -0
- package/server.mjs +48 -10
- package/src/agents.mjs +268 -0
- package/src/cost.mjs +277 -0
- package/src/mutate.mjs +7 -3
- package/src/settings.mjs +30 -3
package/server.mjs
CHANGED
|
@@ -12,6 +12,8 @@ import { projectsRoot, resolveRoot } from './src/projects.mjs';
|
|
|
12
12
|
import { buildStore } from './src/model.mjs';
|
|
13
13
|
import { resolveGlobalInstructions, resolveInstructions, summarise } from './src/instructions.mjs';
|
|
14
14
|
import { settingsReport, summariseSettings } from './src/settings.mjs';
|
|
15
|
+
import { costReport, writeUserSetting } from './src/cost.mjs';
|
|
16
|
+
import { AGENTS_DIR, AGENT_FIELDS, agentsDirExists, listAgents, setAgentField } from './src/agents.mjs';
|
|
15
17
|
import { listStores } from './src/stores.mjs';
|
|
16
18
|
import { forgetPath, rememberPath } from './src/pathcache.mjs';
|
|
17
19
|
import { searchAll } from './src/search.mjs';
|
|
@@ -147,15 +149,23 @@ function storeProjectDir(store) {
|
|
|
147
149
|
|
|
148
150
|
/**
|
|
149
151
|
* The global store holds instructions, not memory, and its directory is ~/.claude
|
|
150
|
-
* itself. Every write endpoint below resolves a target inside `store.dir`,
|
|
151
|
-
* without this guard a delete aimed at it would land on the user's CLAUDE.md
|
|
152
|
-
* settings rather than on a memory file. It is
|
|
153
|
-
*
|
|
152
|
+
* itself. Every memory write endpoint below resolves a target inside `store.dir`,
|
|
153
|
+
* so without this guard a delete aimed at it would land on the user's CLAUDE.md
|
|
154
|
+
* and settings rather than on a memory file. It is refused here once rather than
|
|
155
|
+
* in each of the fifteen handlers.
|
|
156
|
+
*
|
|
157
|
+
* The Cost handlers are the two exceptions, and the only writes this app makes
|
|
158
|
+
* outside a memory store. They do not take a path from the request at all: one
|
|
159
|
+
* writes an allowlisted key to ~/.claude/settings.json, the other one of two
|
|
160
|
+
* frontmatter fields in a named file inside ~/.claude/agents. Neither can reach
|
|
161
|
+
* an instruction file, which is what the rest of this guard exists to protect.
|
|
154
162
|
*/
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
163
|
+
const GLOBAL_WRITE_ACTIONS = new Set(['cost/setting', 'cost/agent']);
|
|
164
|
+
|
|
165
|
+
export function refuseWritesToGlobal(store, method, action = null) {
|
|
166
|
+
if (store.kind !== 'global' || method === 'GET') return;
|
|
167
|
+
if (action && GLOBAL_WRITE_ACTIONS.has(action)) return;
|
|
168
|
+
throw new Error('The global store is read-only: it holds instruction files, not memory.');
|
|
159
169
|
}
|
|
160
170
|
|
|
161
171
|
/** A store with nothing to build a memory model from, in the shape the frontend expects. */
|
|
@@ -260,9 +270,9 @@ async function handleApi(req, res, url) {
|
|
|
260
270
|
}
|
|
261
271
|
|
|
262
272
|
const store = requireStore(decodeURIComponent(segments[2]));
|
|
263
|
-
refuseWritesToGlobal(store, req.method);
|
|
264
|
-
const dir = store.dir;
|
|
265
273
|
const action = segments.slice(3).join('/');
|
|
274
|
+
refuseWritesToGlobal(store, req.method, action);
|
|
275
|
+
const dir = store.dir;
|
|
266
276
|
|
|
267
277
|
if (!action && req.method === 'GET') {
|
|
268
278
|
// buildStore reads every .md in the directory as a memory file, which for
|
|
@@ -312,6 +322,34 @@ async function handleApi(req, res, url) {
|
|
|
312
322
|
return sendJson(res, 200, settingsReport({ projectDir: storeProjectDir(store) }));
|
|
313
323
|
}
|
|
314
324
|
|
|
325
|
+
// The Cost segment. User scope only: the knobs it writes are about every
|
|
326
|
+
// session on the machine, and the file it writes them to is ~/.claude/settings.json.
|
|
327
|
+
if ((action === 'cost' || action.startsWith('cost/')) && store.kind !== 'global') {
|
|
328
|
+
return sendJson(res, 400, { error: 'The cost settings are user-scope, and are edited from the Global entry.' });
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
if (action === 'cost' && req.method === 'GET') {
|
|
332
|
+
return sendJson(res, 200, {
|
|
333
|
+
settings: costReport(),
|
|
334
|
+
agents: listAgents(),
|
|
335
|
+
agentsDir: AGENTS_DIR,
|
|
336
|
+
agentsDirExists: agentsDirExists(),
|
|
337
|
+
agentFields: AGENT_FIELDS,
|
|
338
|
+
});
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
if (action === 'cost/setting' && req.method === 'POST') {
|
|
342
|
+
const body = await readBody(req);
|
|
343
|
+
writeUserSetting(body.key, body.value ?? null);
|
|
344
|
+
return sendJson(res, 200, { settings: costReport() });
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
if (action === 'cost/agent' && req.method === 'POST') {
|
|
348
|
+
const body = await readBody(req);
|
|
349
|
+
const agents = setAgentField(body.file, body.field, body.value ?? null);
|
|
350
|
+
return sendJson(res, 200, { agents, agentsDir: AGENTS_DIR, agentsDirExists: agentsDirExists() });
|
|
351
|
+
}
|
|
352
|
+
|
|
315
353
|
if (action === 'delete-preview' && req.method === 'POST') {
|
|
316
354
|
const body = await readBody(req);
|
|
317
355
|
return sendJson(res, 200, deletePreview(dir, body.file));
|
package/src/agents.mjs
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
// User-scope subagent definitions: ~/.claude/agents/*.md.
|
|
2
|
+
//
|
|
3
|
+
// Not to be confused with ~/.claude/agent-memory (src/stores.mjs), which is what
|
|
4
|
+
// those agents *remember*. This module is about what they *are*: a markdown file
|
|
5
|
+
// whose frontmatter names the agent and, optionally, pins the model and effort
|
|
6
|
+
// it runs at. Pinning a summariser to Haiku while a reviewer stays on Opus is the
|
|
7
|
+
// finer-grained version of the CLAUDE_CODE_SUBAGENT_MODEL switch in src/cost.mjs,
|
|
8
|
+
// which - worth remembering when both are set - outranks everything here.
|
|
9
|
+
//
|
|
10
|
+
// Only `model` and `effort` are writable. The prompt body, the tool lists and
|
|
11
|
+
// every other field are read and shown but never rewritten: a body is prose
|
|
12
|
+
// somebody wrote on purpose, and this tool has no view on it.
|
|
13
|
+
|
|
14
|
+
import fs from 'node:fs';
|
|
15
|
+
import os from 'node:os';
|
|
16
|
+
import path from 'node:path';
|
|
17
|
+
|
|
18
|
+
import { parseFrontmatter } from './parse.mjs';
|
|
19
|
+
import { writeFileAtomic } from './mutate.mjs';
|
|
20
|
+
|
|
21
|
+
export const AGENTS_DIR = path.join(os.homedir(), '.claude', 'agents');
|
|
22
|
+
|
|
23
|
+
const MODEL_ID = /^claude-[A-Za-z0-9._[\]-]+$/;
|
|
24
|
+
|
|
25
|
+
export const AGENT_FIELDS = {
|
|
26
|
+
model: {
|
|
27
|
+
unset: 'inherit',
|
|
28
|
+
allowModelId: true,
|
|
29
|
+
options: [
|
|
30
|
+
{ value: null, label: 'inherit', note: 'the session model' },
|
|
31
|
+
{ value: 'haiku', label: 'haiku' },
|
|
32
|
+
{ value: 'sonnet', label: 'sonnet' },
|
|
33
|
+
{ value: 'opus', label: 'opus' },
|
|
34
|
+
{ value: 'fable', label: 'fable' },
|
|
35
|
+
],
|
|
36
|
+
},
|
|
37
|
+
effort: {
|
|
38
|
+
unset: 'default',
|
|
39
|
+
allowModelId: false,
|
|
40
|
+
options: [
|
|
41
|
+
{ value: null, label: 'default', note: 'the session effort' },
|
|
42
|
+
{ value: 'low', label: 'low' },
|
|
43
|
+
{ value: 'medium', label: 'medium' },
|
|
44
|
+
{ value: 'high', label: 'high' },
|
|
45
|
+
{ value: 'xhigh', label: 'xhigh' },
|
|
46
|
+
{ value: 'max', label: 'max' },
|
|
47
|
+
],
|
|
48
|
+
},
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
export const AGENT_PROBLEM_SEVERITY = {
|
|
52
|
+
'no-frontmatter': 'bad',
|
|
53
|
+
'missing-name': 'warn',
|
|
54
|
+
'missing-description': 'warn',
|
|
55
|
+
'name-mismatch': 'warn',
|
|
56
|
+
'unknown-model': 'warn',
|
|
57
|
+
'unknown-effort': 'warn',
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
function known(field, value) {
|
|
61
|
+
const spec = AGENT_FIELDS[field];
|
|
62
|
+
if (spec.options.some((option) => option.value === value)) return true;
|
|
63
|
+
return spec.allowModelId && MODEL_ID.test(value);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* A filename this module is willing to touch, resolved inside the agents
|
|
68
|
+
* directory. The same shape as safeMemoryPath in src/mutate.mjs: a bare .md
|
|
69
|
+
* basename, no dotfiles, and a realpath check so a symlink cannot point the
|
|
70
|
+
* write somewhere else.
|
|
71
|
+
*/
|
|
72
|
+
export function safeAgentPath(dir, file) {
|
|
73
|
+
if (typeof file !== 'string' || !file || file.includes('\0')) {
|
|
74
|
+
throw new Error('Invalid filename');
|
|
75
|
+
}
|
|
76
|
+
if (file !== path.basename(file) || file.startsWith('.') || !file.endsWith('.md')) {
|
|
77
|
+
throw new Error(`Refusing to touch "${file}": must be a plain .md filename`);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const full = path.join(dir, file);
|
|
81
|
+
const rel = path.relative(dir, full);
|
|
82
|
+
if (rel.startsWith('..') || path.isAbsolute(rel)) {
|
|
83
|
+
throw new Error('Path escapes the agents directory');
|
|
84
|
+
}
|
|
85
|
+
if (fs.existsSync(full)) {
|
|
86
|
+
const realDir = fs.realpathSync(dir);
|
|
87
|
+
const realFull = fs.realpathSync(full);
|
|
88
|
+
if (path.relative(realDir, realFull).startsWith('..')) {
|
|
89
|
+
throw new Error('Path escapes the agents directory');
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return full;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function describeAgent(dir, file) {
|
|
96
|
+
const full = path.join(dir, file);
|
|
97
|
+
const stem = file.replace(/\.md$/, '');
|
|
98
|
+
|
|
99
|
+
let text;
|
|
100
|
+
try {
|
|
101
|
+
text = fs.readFileSync(full, 'utf8');
|
|
102
|
+
} catch (err) {
|
|
103
|
+
return {
|
|
104
|
+
file,
|
|
105
|
+
name: stem,
|
|
106
|
+
description: '',
|
|
107
|
+
tools: '',
|
|
108
|
+
model: null,
|
|
109
|
+
effort: null,
|
|
110
|
+
bytes: 0,
|
|
111
|
+
problems: [{ kind: 'no-frontmatter', severity: 'bad', detail: err.message }],
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const { data, hasFrontmatter } = parseFrontmatter(text);
|
|
116
|
+
const scalar = (key) => (typeof data[key] === 'string' ? data[key].trim() : '');
|
|
117
|
+
const name = scalar('name') || stem;
|
|
118
|
+
const model = scalar('model') || null;
|
|
119
|
+
const effort = scalar('effort') || null;
|
|
120
|
+
|
|
121
|
+
const problems = [];
|
|
122
|
+
const flag = (kind, detail) => problems.push({ kind, severity: AGENT_PROBLEM_SEVERITY[kind], detail });
|
|
123
|
+
|
|
124
|
+
if (!hasFrontmatter) {
|
|
125
|
+
flag('no-frontmatter', 'The file has no --- frontmatter block, so Claude Code does not read it as an agent definition.');
|
|
126
|
+
} else {
|
|
127
|
+
if (!scalar('name')) flag('missing-name', `No name: field, so the agent is addressed as "${stem}" after its file.`);
|
|
128
|
+
if (!scalar('description')) flag('missing-description', 'No description: field. Claude decides when to delegate from that description, so an agent without one is never chosen on its own.');
|
|
129
|
+
if (scalar('name') && scalar('name') !== stem) flag('name-mismatch', `Named "${scalar('name')}" in a file called "${file}".`);
|
|
130
|
+
if (model && !known('model', model)) flag('unknown-model', `model: ${model} is neither an alias nor a claude- model name.`);
|
|
131
|
+
if (effort && !known('effort', effort)) flag('unknown-effort', `effort: ${effort} is not one of low, medium, high, xhigh or max.`);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
return {
|
|
135
|
+
file,
|
|
136
|
+
name,
|
|
137
|
+
description: scalar('description'),
|
|
138
|
+
tools: scalar('tools'),
|
|
139
|
+
model,
|
|
140
|
+
effort,
|
|
141
|
+
bytes: Buffer.byteLength(text, 'utf8'),
|
|
142
|
+
problems,
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Every user-scope agent definition. A directory that is not there is the
|
|
148
|
+
* ordinary state of a machine whose owner has never written one, not a failure,
|
|
149
|
+
* so it answers with an empty list.
|
|
150
|
+
*/
|
|
151
|
+
export function listAgents({ dir = AGENTS_DIR } = {}) {
|
|
152
|
+
let entries;
|
|
153
|
+
try {
|
|
154
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
155
|
+
} catch {
|
|
156
|
+
return [];
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
return entries
|
|
160
|
+
.filter((entry) => entry.isFile() && entry.name.endsWith('.md') && !entry.name.startsWith('.'))
|
|
161
|
+
.map((entry) => describeAgent(dir, entry.name))
|
|
162
|
+
.sort((a, b) => a.name.localeCompare(b.name));
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** Whether the directory itself exists, which is what tells an empty list from a missing one. */
|
|
166
|
+
export function agentsDirExists({ dir = AGENTS_DIR } = {}) {
|
|
167
|
+
try {
|
|
168
|
+
return fs.statSync(dir).isDirectory();
|
|
169
|
+
} catch {
|
|
170
|
+
return false;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const fieldLine = (field) => new RegExp(`^${field}[ \\t]*:`);
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Where a field that is not there yet should go: straight after the name or
|
|
178
|
+
* description when that line carries its value inline, and otherwise at the end
|
|
179
|
+
* of the block. Appending is always valid - a top-level key ends whatever nested
|
|
180
|
+
* block preceded it - so the nicer placement is only taken when it is provably
|
|
181
|
+
* safe, which rules out a folded or block scalar the insertion would land inside.
|
|
182
|
+
*/
|
|
183
|
+
function inlineScalarAt(block, key) {
|
|
184
|
+
const index = block.findIndex((line) => fieldLine(key).test(line));
|
|
185
|
+
if (index === -1) return -1;
|
|
186
|
+
const rest = block[index].slice(block[index].indexOf(':') + 1).trim();
|
|
187
|
+
if (!rest || rest.startsWith('|') || rest.startsWith('>')) return -1;
|
|
188
|
+
return index;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function insertionIndex(block) {
|
|
192
|
+
const description = block.findIndex((line) => fieldLine('description').test(line));
|
|
193
|
+
const inline = inlineScalarAt(block, 'description');
|
|
194
|
+
if (inline !== -1) return inline + 1;
|
|
195
|
+
if (description !== -1) return block.length;
|
|
196
|
+
|
|
197
|
+
const name = inlineScalarAt(block, 'name');
|
|
198
|
+
return name === -1 ? block.length : name + 1;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Rewrite one frontmatter field, leaving every other byte of the file alone:
|
|
203
|
+
* the body, the other fields, their order, their spacing and any comments among
|
|
204
|
+
* them. The same principle src/parse.mjs applies to MEMORY.md - edit the line
|
|
205
|
+
* that changed, never re-emit the document from a parse of it.
|
|
206
|
+
*/
|
|
207
|
+
export function rewriteAgentField(text, field, value) {
|
|
208
|
+
const lines = text.split('\n');
|
|
209
|
+
if (lines[0]?.trim() !== '---') {
|
|
210
|
+
throw new Error('This file has no frontmatter block, so there is nothing to set.');
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
let end = -1;
|
|
214
|
+
for (let i = 1; i < lines.length; i++) {
|
|
215
|
+
if (lines[i].trim() === '---') { end = i; break; }
|
|
216
|
+
}
|
|
217
|
+
if (end === -1) {
|
|
218
|
+
throw new Error('This file has an unterminated frontmatter block.');
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
const block = lines.slice(1, end);
|
|
222
|
+
const at = block.findIndex((line) => fieldLine(field).test(line));
|
|
223
|
+
|
|
224
|
+
if (value === null) {
|
|
225
|
+
if (at === -1) return text;
|
|
226
|
+
block.splice(at, 1);
|
|
227
|
+
} else if (at === -1) {
|
|
228
|
+
block.splice(insertionIndex(block), 0, `${field}: ${value}`);
|
|
229
|
+
} else {
|
|
230
|
+
block[at] = `${field}: ${value}`;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
return [lines[0], ...block, ...lines.slice(end)].join('\n');
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function normaliseAgentValue(field, value) {
|
|
237
|
+
const spec = AGENT_FIELDS[field];
|
|
238
|
+
if (value === null || value === undefined) return null;
|
|
239
|
+
if (typeof value !== 'string') throw new Error(`${field} takes a string, not ${typeof value}.`);
|
|
240
|
+
|
|
241
|
+
const trimmed = value.trim();
|
|
242
|
+
if (!trimmed || trimmed === spec.unset) return null;
|
|
243
|
+
if (known(field, trimmed)) return trimmed;
|
|
244
|
+
|
|
245
|
+
throw new Error(`"${trimmed}" is not a value ${field} accepts.`);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* Set or clear `model` or `effort` on one agent file, atomically, and answer with
|
|
250
|
+
* the refreshed list so the caller renders what is on disk rather than what it
|
|
251
|
+
* hoped it wrote.
|
|
252
|
+
*/
|
|
253
|
+
export function setAgentField(file, field, value, { dir = AGENTS_DIR } = {}) {
|
|
254
|
+
if (!Object.prototype.hasOwnProperty.call(AGENT_FIELDS, field)) {
|
|
255
|
+
throw new Error(`"${field}" is not a field this tool writes. Only model and effort are editable here.`);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
const full = safeAgentPath(dir, file);
|
|
259
|
+
if (!fs.existsSync(full)) throw new Error(`${file} is no longer there - reload and try again.`);
|
|
260
|
+
|
|
261
|
+
const next = normaliseAgentValue(field, value);
|
|
262
|
+
const original = fs.readFileSync(full, 'utf8');
|
|
263
|
+
const rewritten = rewriteAgentField(original, field, next);
|
|
264
|
+
|
|
265
|
+
if (rewritten !== original) writeFileAtomic(dir, file, rewritten);
|
|
266
|
+
|
|
267
|
+
return listAgents({ dir });
|
|
268
|
+
}
|
package/src/cost.mjs
ADDED
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
// The two settings keys that decide what a session costs, and the only two keys
|
|
2
|
+
// this tool ever writes.
|
|
3
|
+
//
|
|
4
|
+
// Everything else in the app reports; this module changes ~/.claude/settings.json.
|
|
5
|
+
// That is a deliberate exception, so the surface is kept as narrow as it can be:
|
|
6
|
+
// a closed list of keys, a closed list of values per key, the user scope only,
|
|
7
|
+
// and a hard refusal to rewrite a settings file that did not parse - overwriting
|
|
8
|
+
// one would silently drop every setting this tool could not read.
|
|
9
|
+
//
|
|
10
|
+
// The two keys:
|
|
11
|
+
//
|
|
12
|
+
// env.CLAUDE_CODE_SUBAGENT_MODEL the model every subagent, agent-team member
|
|
13
|
+
// and workflow agent runs on. It outranks both
|
|
14
|
+
// the model asked for at the call site and the
|
|
15
|
+
// `model:` line in an agent file.
|
|
16
|
+
// outputStyle how Claude writes back in the main
|
|
17
|
+
// conversation. Subagents run their own system
|
|
18
|
+
// prompt and are untouched by it.
|
|
19
|
+
|
|
20
|
+
import fs from 'node:fs';
|
|
21
|
+
import os from 'node:os';
|
|
22
|
+
import path from 'node:path';
|
|
23
|
+
|
|
24
|
+
import { parseFrontmatter } from './parse.mjs';
|
|
25
|
+
import { writeFileAtomic } from './mutate.mjs';
|
|
26
|
+
import {
|
|
27
|
+
SETTINGS_SEVERITY,
|
|
28
|
+
USER_SETTINGS,
|
|
29
|
+
readJsonDetailed,
|
|
30
|
+
readPath,
|
|
31
|
+
settingsCandidates,
|
|
32
|
+
} from './settings.mjs';
|
|
33
|
+
|
|
34
|
+
export const OUTPUT_STYLES_DIR = path.join(os.homedir(), '.claude', 'output-styles');
|
|
35
|
+
|
|
36
|
+
// A full model name is documented as acceptable wherever an alias is, and this
|
|
37
|
+
// tool has no business deciding which ones exist. The shape is checked so a
|
|
38
|
+
// typo does not land in a settings file unnoticed; the value is not resolved.
|
|
39
|
+
const MODEL_ID = /^claude-[A-Za-z0-9._[\]-]+$/;
|
|
40
|
+
|
|
41
|
+
export const COST_KEYS = [
|
|
42
|
+
{
|
|
43
|
+
key: 'subagentModel',
|
|
44
|
+
path: ['env', 'CLAUDE_CODE_SUBAGENT_MODEL'],
|
|
45
|
+
label: 'CLAUDE_CODE_SUBAGENT_MODEL',
|
|
46
|
+
title: 'Subagent model',
|
|
47
|
+
detail: 'The model every subagent, agent-team member and workflow agent runs on. It overrides the model asked for at the call site and the model: line in an agent file both, so it is the one switch that moves all of them at once. Search and summary work rarely needs more than Haiku.',
|
|
48
|
+
envVar: 'CLAUDE_CODE_SUBAGENT_MODEL',
|
|
49
|
+
unset: 'inherit',
|
|
50
|
+
allowModelId: true,
|
|
51
|
+
custom: null,
|
|
52
|
+
options: [
|
|
53
|
+
{ value: null, label: 'inherit', note: 'unset - each agent resolves its own model' },
|
|
54
|
+
{ value: 'haiku', label: 'haiku', note: 'cheapest' },
|
|
55
|
+
{ value: 'sonnet', label: 'sonnet' },
|
|
56
|
+
{ value: 'opus', label: 'opus' },
|
|
57
|
+
{ value: 'fable', label: 'fable', note: 'dearest' },
|
|
58
|
+
],
|
|
59
|
+
},
|
|
60
|
+
{
|
|
61
|
+
key: 'outputStyle',
|
|
62
|
+
path: ['outputStyle'],
|
|
63
|
+
label: 'outputStyle',
|
|
64
|
+
title: 'Output style',
|
|
65
|
+
detail: 'How Claude writes back. Concise leads with the result and drops the narration, which cuts output tokens on every turn; Explanatory and Learning add to them by design. This is part of the system prompt, so a change lands on /clear or the next session, and it reaches the main conversation only.',
|
|
66
|
+
envVar: null,
|
|
67
|
+
unset: 'Default',
|
|
68
|
+
allowModelId: false,
|
|
69
|
+
custom: 'outputStyles',
|
|
70
|
+
options: [
|
|
71
|
+
{ value: null, label: 'Default', note: 'unset' },
|
|
72
|
+
{ value: 'Concise', label: 'Concise', note: 'fewest output tokens' },
|
|
73
|
+
{ value: 'Proactive', label: 'Proactive' },
|
|
74
|
+
{ value: 'Explanatory', label: 'Explanatory', note: 'longer answers' },
|
|
75
|
+
{ value: 'Learning', label: 'Learning', note: 'longer answers' },
|
|
76
|
+
],
|
|
77
|
+
},
|
|
78
|
+
];
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Custom output styles in the user scope. The file name is the style name unless
|
|
82
|
+
* the frontmatter overrides it, which is the rule Claude Code applies, and a
|
|
83
|
+
* directory that is not there is the normal case rather than a failure.
|
|
84
|
+
*/
|
|
85
|
+
export function listOutputStyles({ dir = OUTPUT_STYLES_DIR } = {}) {
|
|
86
|
+
let entries;
|
|
87
|
+
try {
|
|
88
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
89
|
+
} catch {
|
|
90
|
+
return [];
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
return entries
|
|
94
|
+
.filter((entry) => entry.isFile() && entry.name.endsWith('.md'))
|
|
95
|
+
.map((entry) => {
|
|
96
|
+
const file = path.join(dir, entry.name);
|
|
97
|
+
let named = '';
|
|
98
|
+
try {
|
|
99
|
+
named = String(parseFrontmatter(fs.readFileSync(file, 'utf8')).data.name || '').trim();
|
|
100
|
+
} catch { /* an unreadable style still has a name: its file */ }
|
|
101
|
+
return { name: named || entry.name.replace(/\.md$/, ''), file };
|
|
102
|
+
})
|
|
103
|
+
.sort((a, b) => a.name.localeCompare(b.name));
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** The descriptor's own options, plus any custom output styles found on disk. */
|
|
107
|
+
function optionsFor(descriptor, outputStyles) {
|
|
108
|
+
const options = descriptor.options.map((option) => ({ ...option }));
|
|
109
|
+
if (descriptor.custom === 'outputStyles') {
|
|
110
|
+
for (const style of outputStyles) {
|
|
111
|
+
if (!options.some((option) => option.value === style.name)) {
|
|
112
|
+
options.push({ value: style.name, label: style.name, note: 'custom' });
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
return options;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* What a value means once it is checked: a string to write, or null to remove
|
|
121
|
+
* the key. Anything the key does not accept throws rather than being coerced,
|
|
122
|
+
* because a coerced value would be written to the user's settings file.
|
|
123
|
+
*/
|
|
124
|
+
export function normaliseCostValue(descriptor, value, outputStyles = []) {
|
|
125
|
+
if (value === null || value === undefined) return null;
|
|
126
|
+
if (typeof value !== 'string') {
|
|
127
|
+
throw new Error(`${descriptor.label} takes a string, not ${Array.isArray(value) ? 'a list' : typeof value}.`);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const trimmed = value.trim();
|
|
131
|
+
if (!trimmed || trimmed === descriptor.unset) return null;
|
|
132
|
+
|
|
133
|
+
const allowed = optionsFor(descriptor, outputStyles)
|
|
134
|
+
.map((option) => option.value)
|
|
135
|
+
.filter((option) => option !== null);
|
|
136
|
+
if (allowed.includes(trimmed)) return trimmed;
|
|
137
|
+
if (descriptor.allowModelId && MODEL_ID.test(trimmed)) return trimmed;
|
|
138
|
+
|
|
139
|
+
throw new Error(`"${trimmed}" is not a value ${descriptor.label} accepts.`);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Set or remove a nested key, pruning a parent object the removal emptied. A
|
|
144
|
+
* leftover `"env": {}` is harmless but reads as a setting that is still there,
|
|
145
|
+
* which is exactly the confusion this panel exists to remove.
|
|
146
|
+
*/
|
|
147
|
+
function setPath(data, keyPath, value) {
|
|
148
|
+
const [head, ...rest] = keyPath;
|
|
149
|
+
|
|
150
|
+
if (!rest.length) {
|
|
151
|
+
if (value === null) delete data[head];
|
|
152
|
+
else data[head] = value;
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const child = data[head];
|
|
157
|
+
const usable = child && typeof child === 'object' && !Array.isArray(child);
|
|
158
|
+
|
|
159
|
+
if (value === null) {
|
|
160
|
+
if (!usable) return;
|
|
161
|
+
setPath(child, rest, null);
|
|
162
|
+
if (!Object.keys(child).length) delete data[head];
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
if (!usable) data[head] = {};
|
|
167
|
+
setPath(data[head], rest, value);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Every layer's value for both keys, strongest first, in the same shape the
|
|
172
|
+
* Settings report uses so the two render identically.
|
|
173
|
+
*
|
|
174
|
+
* `shadowedByStronger` is the one thing this adds: the user file is the weakest
|
|
175
|
+
* of the five, so a value set anywhere else means a write here changes nothing.
|
|
176
|
+
* Saying so beforehand is cheaper than letting someone watch a setting not take.
|
|
177
|
+
*/
|
|
178
|
+
export function costReport(options = {}) {
|
|
179
|
+
const {
|
|
180
|
+
styleDir = OUTPUT_STYLES_DIR,
|
|
181
|
+
env = process.env,
|
|
182
|
+
userFile = USER_SETTINGS,
|
|
183
|
+
...target
|
|
184
|
+
} = options;
|
|
185
|
+
|
|
186
|
+
const reads = settingsCandidates({ ...target, userFile }).map((candidate) => ({
|
|
187
|
+
...candidate,
|
|
188
|
+
...readJsonDetailed(candidate.file),
|
|
189
|
+
}));
|
|
190
|
+
const layers = reads.map(({ scope, file, status, error }) => ({ scope, file, status, error }));
|
|
191
|
+
const outputStyles = listOutputStyles({ dir: styleDir });
|
|
192
|
+
|
|
193
|
+
const keys = COST_KEYS.map((descriptor) => {
|
|
194
|
+
const values = reads
|
|
195
|
+
.filter((read) => read.status === 'ok' && readPath(read.data, descriptor.path) !== undefined)
|
|
196
|
+
.map((read) => ({
|
|
197
|
+
scope: read.scope,
|
|
198
|
+
file: read.file,
|
|
199
|
+
value: readPath(read.data, descriptor.path),
|
|
200
|
+
wins: false,
|
|
201
|
+
}));
|
|
202
|
+
if (values.length) values[0].wins = true;
|
|
203
|
+
const winner = values[0] || null;
|
|
204
|
+
|
|
205
|
+
const choices = optionsFor(descriptor, outputStyles);
|
|
206
|
+
// A value the picker cannot offer would be silently replaced the moment
|
|
207
|
+
// anyone touched the control, so it is pinned into the list instead.
|
|
208
|
+
if (winner && typeof winner.value === 'string' && winner.value.trim()
|
|
209
|
+
&& !choices.some((option) => option.value === winner.value)) {
|
|
210
|
+
choices.push({ value: winner.value, label: winner.value, note: 'set in your settings' });
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const envValue = descriptor.envVar ? env[descriptor.envVar] ?? null : null;
|
|
214
|
+
|
|
215
|
+
return {
|
|
216
|
+
key: descriptor.key,
|
|
217
|
+
label: descriptor.label,
|
|
218
|
+
title: descriptor.title,
|
|
219
|
+
detail: descriptor.detail,
|
|
220
|
+
unset: descriptor.unset,
|
|
221
|
+
options: choices,
|
|
222
|
+
values,
|
|
223
|
+
effective: winner ? { value: winner.value, scope: winner.scope, file: winner.file } : null,
|
|
224
|
+
shadowedByStronger: Boolean(winner && winner.scope !== 'user'),
|
|
225
|
+
envVar: descriptor.envVar,
|
|
226
|
+
envValue,
|
|
227
|
+
};
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
const userRead = reads.find((read) => read.file === userFile);
|
|
231
|
+
const problems = layers
|
|
232
|
+
.filter((layer) => layer.status !== 'ok' && layer.status !== 'absent')
|
|
233
|
+
.map((layer) => ({
|
|
234
|
+
kind: layer.status,
|
|
235
|
+
severity: SETTINGS_SEVERITY[layer.status] || 'warn',
|
|
236
|
+
scope: layer.scope,
|
|
237
|
+
file: layer.file,
|
|
238
|
+
detail: layer.error,
|
|
239
|
+
}));
|
|
240
|
+
|
|
241
|
+
return {
|
|
242
|
+
keys,
|
|
243
|
+
layers,
|
|
244
|
+
problems,
|
|
245
|
+
outputStyles,
|
|
246
|
+
userFile,
|
|
247
|
+
// False when the file this panel would write is there but unusable. The
|
|
248
|
+
// controls are disabled rather than allowed to fail on save.
|
|
249
|
+
writable: !userRead || userRead.status === 'ok' || userRead.status === 'absent',
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* Write one key to the user settings file, atomically, and answer with the value
|
|
255
|
+
* that landed. A file that exists but does not parse is refused outright.
|
|
256
|
+
*/
|
|
257
|
+
export function writeUserSetting(key, value, options = {}) {
|
|
258
|
+
const { file = USER_SETTINGS, styleDir = OUTPUT_STYLES_DIR } = options;
|
|
259
|
+
|
|
260
|
+
const descriptor = COST_KEYS.find((entry) => entry.key === key);
|
|
261
|
+
if (!descriptor) throw new Error(`"${key}" is not a setting this tool writes.`);
|
|
262
|
+
|
|
263
|
+
const next = normaliseCostValue(descriptor, value, listOutputStyles({ dir: styleDir }));
|
|
264
|
+
|
|
265
|
+
const read = readJsonDetailed(file);
|
|
266
|
+
if (read.status !== 'ok' && read.status !== 'absent') {
|
|
267
|
+
throw new Error(`Refusing to write ${file}: ${read.error || read.status}. Rewriting a file this tool cannot parse would drop the settings it cannot see, so fix the file by hand first.`);
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
const data = read.status === 'ok' ? read.data : {};
|
|
271
|
+
setPath(data, descriptor.path, next);
|
|
272
|
+
|
|
273
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
274
|
+
writeFileAtomic(path.dirname(file), path.basename(file), `${JSON.stringify(data, null, 2)}\n`);
|
|
275
|
+
|
|
276
|
+
return next;
|
|
277
|
+
}
|
package/src/mutate.mjs
CHANGED
|
@@ -78,11 +78,15 @@ function readIndex(dir) {
|
|
|
78
78
|
}
|
|
79
79
|
|
|
80
80
|
/**
|
|
81
|
-
* Replace
|
|
81
|
+
* Replace a file atomically: write a sibling temp file, fsync it, rename over
|
|
82
82
|
* the target. A .backup copy is kept for the duration and restored if anything
|
|
83
|
-
* throws, so a crash can never leave a truncated
|
|
83
|
+
* throws, so a crash can never leave a truncated file behind.
|
|
84
|
+
*
|
|
85
|
+
* Exported because the settings and agent writers outside this module need the
|
|
86
|
+
* same guarantee, and a second implementation of it is a second chance to get
|
|
87
|
+
* the crash path wrong.
|
|
84
88
|
*/
|
|
85
|
-
function writeFileAtomic(dir, name, text) {
|
|
89
|
+
export function writeFileAtomic(dir, name, text) {
|
|
86
90
|
const target = path.join(dir, name);
|
|
87
91
|
const tmp = path.join(dir, `.${name}.tmp-${process.pid}`);
|
|
88
92
|
const backup = path.join(dir, `.${name}.backup`);
|