claude-memory-admin 1.9.0 → 1.10.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.
@@ -15,6 +15,7 @@ const PANELS = {
15
15
  };
16
16
 
17
17
  const installed = () => state.tools.filter((tool) => tool.found && PANELS[tool.id]);
18
+ const missing = () => state.tools.filter((tool) => !tool.found && PANELS[tool.id]);
18
19
 
19
20
  const openKey = (id) => `toolOpen:${id}`;
20
21
  const isOpen = (id) => localStorage.getItem(openKey(id)) === '1';
@@ -126,19 +127,46 @@ function accordion(container, tool, slot) {
126
127
  container.append(panel);
127
128
  }
128
129
 
130
+ function notInstalled(container, tool) {
131
+ container.append(node('div', { class: ui.contextRowStatic }, [
132
+ node('div', { class: ui.contextMain }, [
133
+ node('div', { class: ui.contextFile, text: tool.label }),
134
+ ]),
135
+ node('div', { class: ui.contextSize, text: 'not installed' }),
136
+ ]));
137
+
138
+ container.append(node('div', { class: ui.toolMissingBody }, [
139
+ node('p', { class: ui.noteTight, text: tool.blurb }),
140
+ node('a', {
141
+ class: ui.linkButton,
142
+ href: tool.repo,
143
+ target: '_blank',
144
+ rel: 'noopener noreferrer',
145
+ text: 'View on GitHub \u2197',
146
+ }),
147
+ ]));
148
+ }
149
+
129
150
  export function renderTools(container) {
130
- const tools = installed();
131
- if (!tools.length) return;
151
+ const found = installed();
152
+ const absent = missing();
153
+ if (!found.length && !absent.length) return;
132
154
 
133
- if (!state.aux.tools && localStorage.getItem(OPT_IN) === '1') start({ remember: false });
134
- if (!state.aux.tools) return gate(container, tools);
155
+ if (found.length && !state.aux.tools && localStorage.getItem(OPT_IN) === '1') start({ remember: false });
156
+ const opted = Boolean(state.aux.tools);
135
157
 
136
- container.append(node('div', { class: ui.listBar }, [
158
+ const bar = [
137
159
  node('span', { class: ui.sectionLabelInline, text: 'Companion tools' }),
138
160
  node('span', { class: ui.listSpacer }),
139
- node('button', { class: ui.buttonSmall, text: 'Re-read', onclick: readAll }),
140
- node('button', { class: ui.buttonSmall, text: 'Turn off', onclick: turnOff }),
141
- ]));
161
+ ];
162
+ if (found.length && opted) {
163
+ bar.push(node('button', { class: ui.buttonSmall, text: 'Re-read', onclick: readAll }));
164
+ bar.push(node('button', { class: ui.buttonSmall, text: 'Turn off', onclick: turnOff }));
165
+ }
166
+ container.append(node('div', { class: ui.listBar }, bar));
167
+
168
+ if (found.length && !opted) gate(container, found);
169
+ else for (const tool of found) accordion(container, tool, state.aux.tools[tool.id]);
142
170
 
143
- for (const tool of tools) accordion(container, tool, state.aux.tools[tool.id]);
171
+ for (const tool of absent) notInstalled(container, tool);
144
172
  }
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`, so
151
- * without this guard a delete aimed at it would land on the user's CLAUDE.md and
152
- * settings rather than on a memory file. It is read-only, and refused here once
153
- * rather than in each of the fifteen handlers.
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
- export function refuseWritesToGlobal(store, method) {
156
- if (store.kind === 'global' && method !== 'GET') {
157
- throw new Error('The global store is read-only: it holds instruction files, not memory.');
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
+ }