@aisac/cli 0.4.0-beta.1 → 0.4.0-beta.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,486 @@
1
+ // @ts-check
2
+ /**
3
+ * `aisac hooks` and `aisac mcp` (spec aisac-engineering-extensions FR4): list,
4
+ * enable, disable and reset catalog entries, offline. On a TTY without
5
+ * arguments each opens a checklist. `aisac mcp info` describes one server, and
6
+ * `aisac mcp login` runs Codex's own login for it. Choices apply to the next
7
+ * session; running sessions keep their set.
8
+ */
9
+ import { spawn } from 'node:child_process';
10
+ import { emitKeypressEvents } from 'node:readline';
11
+ import { hookById, hookIds, mcpById, mcpIds } from './extensions-catalog.mjs';
12
+ import {
13
+ readPreferences,
14
+ resolveHooks,
15
+ resolveServers,
16
+ unknownHookIds,
17
+ unknownServerIds,
18
+ writePreferences,
19
+ } from './extensions-preferences.mjs';
20
+ import { readLastLaunch, readStoredLocale, resolvePackLocale } from './engineering-pack.mjs';
21
+ import { codexLoginArgs, serverName, supportsHostLogin } from './mcp-servers.mjs';
22
+ import { resolveNative } from './platform.mjs';
23
+ import { stateRoot } from './state.mjs';
24
+
25
+ /** @typedef {import('./extensions-catalog.mjs').CatalogLocale} CatalogLocale */
26
+ /** @typedef {import('./extensions-catalog.mjs').McpEntry} McpEntry */
27
+ /** @typedef {import('./extensions-preferences.mjs').ExtensionPreferences} ExtensionPreferences */
28
+ /**
29
+ * @typedef {object} CatalogItem
30
+ * @property {{ id: string, description: Readonly<Record<CatalogLocale, string>> }} entry
31
+ * @property {boolean} enabled
32
+ * @property {'default' | 'choice'} source
33
+ */
34
+ /**
35
+ * @typedef {object} ExtensionKind
36
+ * @property {'hooks' | 'mcp'} key The command name and the preferences key.
37
+ * @property {string} title
38
+ * @property {() => string[]} ids
39
+ * @property {(preferences: ExtensionPreferences) => CatalogItem[]} resolve
40
+ * @property {(preferences: ExtensionPreferences) => string[]} unknown
41
+ * @property {(id: string) => string} column The second column: hook mode or server login.
42
+ * @property {string} nextSession
43
+ */
44
+
45
+ const USAGE_EXIT_CODE = 2;
46
+ const IO_EXIT_CODE = 1;
47
+ const LICENSE_NOTE = 'Extensions load only with an active AISAC Engineering license.';
48
+ const DEFAULT_COLUMNS = 80;
49
+ const MIN_COLUMNS = 20;
50
+ const ELLIPSIS = '…';
51
+ /** @type {Readonly<Record<McpEntry['login'], string>>} */
52
+ const LOGIN_LABEL = Object.freeze({
53
+ 'host-oauth': 'oauth',
54
+ 'optional-oauth': 'oauth-opt',
55
+ 'env-token': 'env-token',
56
+ none: 'no-login',
57
+ });
58
+
59
+ /** @type {ExtensionKind} */
60
+ const HOOKS = {
61
+ key: 'hooks',
62
+ title: 'AISAC Engineering hooks (Claude Code)',
63
+ ids: hookIds,
64
+ resolve: resolveHooks,
65
+ unknown: unknownHookIds,
66
+ column: (id) => hookById(id)?.mode ?? '',
67
+ nextSession:
68
+ 'Applies to the next `aisac claude` session; running sessions keep their current set.',
69
+ };
70
+
71
+ /** @type {ExtensionKind} */
72
+ const MCP = {
73
+ key: 'mcp',
74
+ title: 'AISAC Engineering MCP servers (Claude Code and Codex)',
75
+ ids: mcpIds,
76
+ resolve: resolveServers,
77
+ unknown: unknownServerIds,
78
+ column: (id) => {
79
+ const entry = mcpById(id);
80
+ return entry === undefined ? '' : LOGIN_LABEL[entry.login];
81
+ },
82
+ nextSession:
83
+ 'Applies to the next `aisac claude` or `aisac codex` session; running sessions keep their current set.',
84
+ };
85
+
86
+ /**
87
+ * Cut a checklist row to the terminal width. The redraw moves the cursor up one
88
+ * row per item, which only holds while no row wraps; one column stays free so
89
+ * no terminal wraps at the last column either.
90
+ * @param {string} line
91
+ * @param {number | undefined} columns
92
+ */
93
+ export function fitLine(line, columns) {
94
+ const total =
95
+ typeof columns === 'number' && Number.isInteger(columns) && columns > 0
96
+ ? columns
97
+ : DEFAULT_COLUMNS;
98
+ const width = Math.max(MIN_COLUMNS, total) - 1;
99
+ const characters = [...line];
100
+ if (characters.length <= width) return line;
101
+ return `${characters.slice(0, width - 1).join('')}${ELLIPSIS}`;
102
+ }
103
+
104
+ /**
105
+ * @typedef {object} ChecklistState
106
+ * @property {number} cursor
107
+ * @property {boolean[]} enabled
108
+ */
109
+
110
+ /**
111
+ * One key press in the checklist (pure, tested without a TTY).
112
+ * @param {ChecklistState} state
113
+ * @param {{ name?: string, ctrl?: boolean, sequence?: string }} key
114
+ * @returns {{ state: ChecklistState, done: 'save' | 'cancel' | null }}
115
+ */
116
+ export function checklistStep(state, key) {
117
+ const last = state.enabled.length - 1;
118
+ if ((key.ctrl === true && key.name === 'c') || key.name === 'escape' || key.name === 'q')
119
+ return { state, done: 'cancel' };
120
+ if (key.name === 'return' || key.name === 'enter') return { state, done: 'save' };
121
+ if (key.name === 'up' || key.name === 'k')
122
+ return { state: { ...state, cursor: Math.max(0, state.cursor - 1) }, done: null };
123
+ if (key.name === 'down' || key.name === 'j')
124
+ return { state: { ...state, cursor: Math.min(last, state.cursor + 1) }, done: null };
125
+ if (key.name === 'space' || key.sequence === ' ') {
126
+ const enabled = state.enabled.map((value, index) => (index === state.cursor ? !value : value));
127
+ return { state: { ...state, enabled }, done: null };
128
+ }
129
+ return { state, done: null };
130
+ }
131
+
132
+ /**
133
+ * @param {ExtensionKind} kind @param {CatalogLocale} locale
134
+ * @param {CatalogItem[]} items @param {ChecklistState} [state]
135
+ */
136
+ function renderLines(kind, locale, items, state) {
137
+ const idWidth = Math.max(...items.map((item) => item.entry.id.length));
138
+ const columnWidth = Math.max(...items.map((item) => kind.column(item.entry.id).length)) + 1;
139
+ return items.map((item, index) => {
140
+ const enabled = state === undefined ? item.enabled : state.enabled[index];
141
+ const pointer = state === undefined ? ' ' : index === state.cursor ? '>' : ' ';
142
+ const source = state === undefined ? ` ${item.source.padEnd(7)}` : '';
143
+ const column = kind.column(item.entry.id).padEnd(columnWidth);
144
+ return `${pointer} [${enabled ? 'x' : ' '}] ${item.entry.id.padEnd(idWidth)} ${column}${source} ${item.entry.description[locale]}`;
145
+ });
146
+ }
147
+
148
+ /** @param {string} root */
149
+ async function licensedLastLaunch(root) {
150
+ const last = await readLastLaunch(root);
151
+ return last?.state === 'loaded';
152
+ }
153
+
154
+ /**
155
+ * Store one kind's explicit choices, keeping the other kind's as they are.
156
+ * @param {ExtensionKind} kind @param {Record<string, boolean>} choices
157
+ */
158
+ async function saveChoices(kind, choices) {
159
+ const current = await readPreferences(stateRoot());
160
+ const valid = current.status === 'valid';
161
+ await writePreferences({
162
+ hooks: kind.key === 'hooks' ? choices : valid ? current.hooks : {},
163
+ mcp: kind.key === 'mcp' ? choices : valid ? current.mcp : {},
164
+ });
165
+ if (current.status === 'invalid')
166
+ console.log('The previous extensions file was invalid and was replaced.');
167
+ }
168
+
169
+ /** @param {ExtensionKind} kind @param {boolean} licensed */
170
+ function afterChange(kind, licensed) {
171
+ console.log(kind.nextSession);
172
+ if (!licensed) console.log(LICENSE_NOTE);
173
+ }
174
+
175
+ /**
176
+ * Interactive checklist. Resolves to the new enabled flags, or null on cancel.
177
+ * @param {ExtensionKind} kind @param {CatalogLocale} locale @param {CatalogItem[]} items
178
+ * @returns {Promise<boolean[] | null>}
179
+ */
180
+ function runChecklist(kind, locale, items) {
181
+ return new Promise((resolve) => {
182
+ let state = { cursor: 0, enabled: items.map((item) => item.enabled) };
183
+ const draw = (/** @type {boolean} */ first) => {
184
+ if (!first) process.stdout.write(`\u001b[${items.length}A\u001b[J`);
185
+ const rows = renderLines(kind, locale, items, state).map((line) =>
186
+ fitLine(line, process.stdout.columns),
187
+ );
188
+ process.stdout.write(`${rows.join('\n')}\n`);
189
+ };
190
+ console.log(`${kind.title}: up/down moves, space toggles, enter saves, q cancels.`);
191
+ draw(true);
192
+ emitKeypressEvents(process.stdin);
193
+ process.stdin.setRawMode(true);
194
+ process.stdin.resume();
195
+ /** @param {string} _text @param {{ name?: string, ctrl?: boolean, sequence?: string }} key */
196
+ const onKey = (_text, key) => {
197
+ const step = checklistStep(state, key ?? {});
198
+ state = step.state;
199
+ if (step.done === null) return draw(false);
200
+ process.stdin.off('keypress', onKey);
201
+ process.stdin.setRawMode(false);
202
+ process.stdin.pause();
203
+ resolve(step.done === 'save' ? state.enabled : null);
204
+ };
205
+ process.stdin.on('keypress', onKey);
206
+ });
207
+ }
208
+
209
+ /**
210
+ * The JSON row of one item.
211
+ * @param {ExtensionKind} kind @param {CatalogLocale} locale @param {CatalogItem} item
212
+ */
213
+ function jsonItem(kind, locale, item) {
214
+ const base = {
215
+ id: item.entry.id,
216
+ enabled: item.enabled,
217
+ source: item.source,
218
+ description: item.entry.description[locale],
219
+ };
220
+ if (kind.key === 'hooks') {
221
+ const hook = hookById(item.entry.id);
222
+ return { ...base, mode: hook?.mode, clients: hook?.clients };
223
+ }
224
+ const server = mcpById(item.entry.id);
225
+ return {
226
+ ...base,
227
+ server: serverName(item.entry.id),
228
+ login: server?.login,
229
+ transport: server?.transport.type === 'stdio' ? 'local' : 'remote',
230
+ clients: server?.clients,
231
+ };
232
+ }
233
+
234
+ /**
235
+ * What one server reaches and how to log in (FR4 `aisac mcp info`).
236
+ * @param {McpEntry} entry @param {CatalogLocale} locale @param {CatalogItem | undefined} item
237
+ */
238
+ export function serverInfo(entry, locale, item) {
239
+ const name = serverName(entry.id);
240
+ const { transport } = entry;
241
+ const variable = transport.type === 'http' ? transport.bearerEnv : undefined;
242
+ /** @type {{ claude: string, codex: string }} */
243
+ const login =
244
+ entry.login === 'none'
245
+ ? { claude: 'No login.', codex: 'No login.' }
246
+ : variable !== undefined
247
+ ? {
248
+ claude: `Set ${variable} in the shell that runs aisac claude; without it the server is skipped.`,
249
+ codex: `Set ${variable} in the shell that runs aisac codex; without it the server is skipped.`,
250
+ }
251
+ : {
252
+ claude: `${entry.login === 'optional-oauth' ? 'Optional: ' : ''}in the session, /mcp, choose ${name}, then Authenticate.`,
253
+ codex: `${entry.login === 'optional-oauth' ? 'Optional: ' : ''}aisac mcp login ${entry.id} (runs Codex's own login with the session settings).`,
254
+ };
255
+ return {
256
+ id: entry.id,
257
+ server: name,
258
+ enabled: item?.enabled ?? false,
259
+ choice: item?.source ?? 'default',
260
+ publisher: entry.publisher,
261
+ sourceUrl: entry.source,
262
+ description: entry.description[locale],
263
+ transport:
264
+ transport.type === 'stdio'
265
+ ? {
266
+ type: 'local',
267
+ command: [transport.command, ...transport.args].join(' '),
268
+ note: 'Pinned to an exact package version; npx downloads it on first use.',
269
+ }
270
+ : {
271
+ type: 'remote',
272
+ url: transport.url,
273
+ note: 'Hosted by the vendor: its tools can change without a client release, so keep the confirmation of each call on.',
274
+ },
275
+ reaches: entry.reaches[locale],
276
+ // Tools that spend money, removed whatever the permission mode is (FR7.2).
277
+ blockedTools: [...(entry.blockedTools ?? [])],
278
+ ...(entry.blockedToolPrefixes === undefined
279
+ ? {}
280
+ : { blockedToolPrefixes: [...entry.blockedToolPrefixes] }),
281
+ login,
282
+ ...(variable === undefined ? {} : { tokenVariable: variable }),
283
+ ...(entry.loginNote === undefined ? {} : { loginNote: entry.loginNote[locale] }),
284
+ ...(entry.setup === undefined ? {} : { setup: entry.setup }),
285
+ credentials:
286
+ 'Logins stay in the host’s own credential store (Claude Code or Codex). AISAC never sees them: no token goes to ~/.aibrain or to AISAC.',
287
+ duplicate: `If you already run your own server for this service, keep one of them (aisac mcp disable ${entry.id}, or remove yours).`,
288
+ trifecta:
289
+ 'Private data (GitHub, Supabase, Vercel) plus untrusted content (web pages, issues) plus a way out in one session lets injected text reach your data: keep the confirmation of each call on.',
290
+ };
291
+ }
292
+
293
+ /** @param {ReturnType<typeof serverInfo>} info */
294
+ function printInfo(info) {
295
+ console.log(`${info.server}: ${info.description}`);
296
+ console.log(`State: ${info.enabled ? 'on' : 'off'} (${info.choice})`);
297
+ console.log(`Publisher: ${info.publisher} (${info.sourceUrl})`);
298
+ const where = info.transport.type === 'local' ? info.transport.command : info.transport.url;
299
+ console.log(`Transport: ${info.transport.type}, ${where}. ${info.transport.note}`);
300
+ console.log(`Reaches: ${info.reaches}`);
301
+ if (info.blockedTools.length > 0) {
302
+ const prefixes = info.blockedToolPrefixes ?? [];
303
+ const claudeOnly =
304
+ prefixes.length === 0
305
+ ? ''
306
+ : ` In Claude Code, also any tool whose name starts with ${prefixes.join(', ')}.`;
307
+ console.log(
308
+ `Blocked by AISAC, because they spend money: ${info.blockedTools.join(', ')}.${claudeOnly} They stay blocked even if you allow every tool or skip permission prompts.`,
309
+ );
310
+ }
311
+ if (info.loginNote !== undefined) console.log(`Login: ${info.loginNote}`);
312
+ console.log(`Log in from Claude Code: ${info.login.claude}`);
313
+ console.log(`Log in from Codex: ${info.login.codex}`);
314
+ if (info.setup !== undefined) console.log(`Before the first use, run once: ${info.setup}`);
315
+ console.log(info.credentials);
316
+ console.log(info.trifecta);
317
+ console.log(info.duplicate);
318
+ }
319
+
320
+ /**
321
+ * `aisac mcp login <id>`: Codex's own login, with the session's settings, so
322
+ * the next `aisac codex` session finds it. AISAC never sees the credential.
323
+ * @param {McpEntry} entry
324
+ */
325
+ async function codexLogin(entry) {
326
+ const name = serverName(entry.id);
327
+ if (!supportsHostLogin(entry)) {
328
+ const variable = entry.transport.type === 'http' ? entry.transport.bearerEnv : undefined;
329
+ console.error(
330
+ variable === undefined
331
+ ? `aisac: ${name} needs no login.`
332
+ : `aisac: ${name} has no host login; set ${variable} instead (aisac mcp info ${entry.id}).`,
333
+ );
334
+ process.exitCode = USAGE_EXIT_CODE;
335
+ return;
336
+ }
337
+ const codex = resolveNative('codex');
338
+ if (codex === null) {
339
+ console.error('aisac: codex was not found on PATH.');
340
+ process.exitCode = IO_EXIT_CODE;
341
+ return;
342
+ }
343
+ console.log(
344
+ `Logging in to ${name} with Codex; the login stays in Codex's own store. Claude Code logs in inside the session: /mcp, choose ${name}, then Authenticate.`,
345
+ );
346
+ process.exitCode = await new Promise((resolve) => {
347
+ const child = spawn(codex, codexLoginArgs(entry), { stdio: 'inherit' });
348
+ child.on('error', () => resolve(IO_EXIT_CODE));
349
+ child.on('exit', (code) => resolve(code ?? IO_EXIT_CODE));
350
+ });
351
+ }
352
+
353
+ /**
354
+ * @param {ExtensionKind} kind @param {string[]} ids
355
+ * @returns {boolean} true when every id is in the catalog
356
+ */
357
+ function checkIds(kind, ids) {
358
+ const known = new Set(kind.ids());
359
+ const unknown = ids.filter((id) => !known.has(id));
360
+ if (unknown.length === 0) return true;
361
+ const noun = kind.key === 'hooks' ? 'hook' : 'MCP server';
362
+ console.error(
363
+ `aisac: unknown ${noun} id: ${unknown.join(', ')}. Valid: ${kind.ids().join(', ')}.`,
364
+ );
365
+ process.exitCode = USAGE_EXIT_CODE;
366
+ return false;
367
+ }
368
+
369
+ /** @param {ExtensionKind} kind */
370
+ function usage(kind) {
371
+ const extra = kind.key === 'mcp' ? ' | aisac mcp info <id> | aisac mcp login <id>' : '';
372
+ console.error(
373
+ `aisac: usage: aisac ${kind.key} [--json] | aisac ${kind.key} enable <id>... | aisac ${kind.key} disable <id>... | aisac ${kind.key} reset${extra}`,
374
+ );
375
+ process.exitCode = USAGE_EXIT_CODE;
376
+ }
377
+
378
+ /**
379
+ * `aisac hooks|mcp [list|enable|disable|reset|info|login] [ids...] [--json]`.
380
+ * @param {ExtensionKind} kind @param {string[]} args
381
+ */
382
+ async function extensionCommand(kind, args) {
383
+ const json = args.includes('--json');
384
+ const words = args.filter((arg) => arg !== '--json');
385
+ const [action = 'list', ...ids] = words;
386
+ const root = stateRoot();
387
+ const locale = resolvePackLocale(await readStoredLocale(root));
388
+ const preferences = await readPreferences(root);
389
+ const items = kind.resolve(preferences);
390
+ const licensed = await licensedLastLaunch(root);
391
+
392
+ if (action === 'list' && ids.length === 0) {
393
+ if (json) {
394
+ console.log(
395
+ JSON.stringify({
396
+ preferences: preferences.status,
397
+ licensedLastLaunch: licensed,
398
+ [kind.key === 'hooks' ? 'hooks' : 'servers']: items.map((item) =>
399
+ jsonItem(kind, locale, item),
400
+ ),
401
+ unknown: kind.unknown(preferences),
402
+ }),
403
+ );
404
+ return;
405
+ }
406
+ if (args.length === 0 && process.stdin.isTTY && process.stdout.isTTY) {
407
+ const chosen = await runChecklist(kind, locale, items);
408
+ if (chosen === null) return console.log('No change.');
409
+ /** @type {Record<string, boolean>} */
410
+ const choices = preferences.status === 'valid' ? { ...preferences[kind.key] } : {};
411
+ items.forEach((item, index) => {
412
+ if (chosen[index] !== item.enabled) choices[item.entry.id] = chosen[index] === true;
413
+ });
414
+ await saveChoices(kind, choices);
415
+ return afterChange(kind, licensed);
416
+ }
417
+ console.log(`${kind.title}:`);
418
+ console.log(renderLines(kind, locale, items).join('\n'));
419
+ if (preferences.status === 'invalid')
420
+ console.log(
421
+ `The extensions file is invalid: ${kind.key === 'hooks' ? 'the defaults apply' : 'every server is off'}. Run \`aisac ${kind.key} reset\`.`,
422
+ );
423
+ console.log(
424
+ `Change with \`aisac ${kind.key} enable <id>\`, \`aisac ${kind.key} disable <id>\` or \`aisac ${kind.key} reset\`.${kind.key === 'mcp' ? ' Details: `aisac mcp info <id>`.' : ''}`,
425
+ );
426
+ if (!licensed) console.log(LICENSE_NOTE);
427
+ return;
428
+ }
429
+ if (action === 'reset' && ids.length === 0) {
430
+ await saveChoices(kind, {});
431
+ console.log(`${kind.key === 'hooks' ? 'Hooks' : 'MCP servers'} reset to the defaults.`);
432
+ return afterChange(kind, licensed);
433
+ }
434
+ if ((action === 'enable' || action === 'disable') && ids.length > 0) {
435
+ if (!checkIds(kind, ids)) return;
436
+ /** @type {Record<string, boolean>} */
437
+ const choices = preferences.status === 'valid' ? { ...preferences[kind.key] } : {};
438
+ for (const id of ids) choices[id] = action === 'enable';
439
+ await saveChoices(kind, choices);
440
+ console.log(`${action === 'enable' ? 'Enabled' : 'Disabled'}: ${ids.join(', ')}.`);
441
+ return afterChange(kind, licensed);
442
+ }
443
+ const [id] = ids;
444
+ if (kind.key === 'mcp' && action === 'info' && ids.length === 1 && id !== undefined) {
445
+ if (!checkIds(kind, ids)) return;
446
+ const entry = /** @type {McpEntry} */ (mcpById(id));
447
+ const info = serverInfo(
448
+ entry,
449
+ locale,
450
+ items.find((item) => item.entry.id === id),
451
+ );
452
+ if (json) console.log(JSON.stringify(info));
453
+ else printInfo(info);
454
+ return;
455
+ }
456
+ if (kind.key === 'mcp' && action === 'login' && ids.length === 1 && id !== undefined && !json) {
457
+ if (!checkIds(kind, ids)) return;
458
+ return codexLogin(/** @type {McpEntry} */ (mcpById(id)));
459
+ }
460
+ usage(kind);
461
+ }
462
+
463
+ /** @param {string[]} args */
464
+ export function hooksCommand(args) {
465
+ return extensionCommand(HOOKS, args);
466
+ }
467
+
468
+ /** @param {string[]} args */
469
+ export function mcpCommand(args) {
470
+ return extensionCommand(MCP, args);
471
+ }
472
+
473
+ /** Offline extension summary for `status` and `doctor`. @param {string} root */
474
+ export async function extensionsSummary(root) {
475
+ const preferences = await readPreferences(root);
476
+ return {
477
+ preferences: preferences.status,
478
+ hooks: resolveHooks(preferences)
479
+ .filter((hook) => hook.enabled)
480
+ .map((hook) => hook.entry.id),
481
+ mcp: resolveServers(preferences)
482
+ .filter((server) => server.enabled)
483
+ .map((server) => server.entry.id),
484
+ unknown: [...unknownHookIds(preferences), ...unknownServerIds(preferences)],
485
+ };
486
+ }
@@ -0,0 +1,151 @@
1
+ // @ts-check
2
+ /**
3
+ * The user's extension choices (spec aisac-engineering-extensions FR3):
4
+ * `<state>/extensions.json`, mode 0600, written atomically, at most 16 KiB.
5
+ * Only explicit choices are stored; a missing id means the catalog default.
6
+ * An invalid file never fails a launch: hooks fall back to the defaults and
7
+ * every MCP server stays off.
8
+ */
9
+ import { lstat, readFile } from 'node:fs/promises';
10
+ import { join } from 'node:path';
11
+ import { atomicJson, ensureStateRoot } from './state.mjs';
12
+ import { CATALOG_ID, HOOK_CATALOG, MCP_CATALOG, hookById, mcpById } from './extensions-catalog.mjs';
13
+
14
+ export const EXTENSIONS_FILE = 'extensions.json';
15
+ const SCHEMA_VERSION = 1;
16
+ const MAX_PREFERENCES_BYTES = 16 * 1024;
17
+ const MAX_CHOICES = 64;
18
+ const TOP_LEVEL_KEYS = ['hooks', 'mcp', 'schemaVersion'];
19
+
20
+ /**
21
+ * @typedef {object} ExtensionPreferences
22
+ * @property {'missing' | 'valid' | 'invalid'} status
23
+ * @property {Record<string, boolean>} hooks
24
+ * @property {Record<string, boolean>} mcp
25
+ */
26
+
27
+ /** @param {unknown} value @returns {value is Record<string, unknown>} */
28
+ function isRecord(value) {
29
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
30
+ }
31
+
32
+ /** @param {unknown} value @returns {Record<string, boolean> | null} */
33
+ function choices(value) {
34
+ if (!isRecord(value)) return null;
35
+ const entries = Object.entries(value);
36
+ if (entries.length > MAX_CHOICES) return null;
37
+ /** @type {Record<string, boolean>} */
38
+ const result = {};
39
+ for (const [id, enabled] of entries) {
40
+ if (!CATALOG_ID.test(id) || typeof enabled !== 'boolean') return null;
41
+ result[id] = enabled;
42
+ }
43
+ return result;
44
+ }
45
+
46
+ /**
47
+ * Validate a parsed preferences document. @param {unknown} value
48
+ * @returns {{ hooks: Record<string, boolean>, mcp: Record<string, boolean> } | null}
49
+ */
50
+ export function parsePreferences(value) {
51
+ if (!isRecord(value)) return null;
52
+ const keys = Object.keys(value).sort();
53
+ if (keys.length !== TOP_LEVEL_KEYS.length || keys.some((key, i) => key !== TOP_LEVEL_KEYS[i]))
54
+ return null;
55
+ if (value.schemaVersion !== SCHEMA_VERSION) return null;
56
+ const hooks = choices(value.hooks);
57
+ const mcp = choices(value.mcp);
58
+ return hooks === null || mcp === null ? null : { hooks, mcp };
59
+ }
60
+
61
+ /** @param {string} root @returns {string} */
62
+ export function preferencesPath(root) {
63
+ return join(root, EXTENSIONS_FILE);
64
+ }
65
+
66
+ /** @param {string} root @returns {Promise<ExtensionPreferences>} */
67
+ export async function readPreferences(root) {
68
+ const path = preferencesPath(root);
69
+ try {
70
+ const info = await lstat(path);
71
+ if (!info.isFile() || info.size > MAX_PREFERENCES_BYTES)
72
+ return { status: 'invalid', hooks: {}, mcp: {} };
73
+ const parsed = parsePreferences(JSON.parse(await readFile(path, 'utf8')));
74
+ return parsed === null
75
+ ? { status: 'invalid', hooks: {}, mcp: {} }
76
+ : { status: 'valid', ...parsed };
77
+ } catch (error) {
78
+ const missing = error instanceof Error && 'code' in error && error.code === 'ENOENT';
79
+ return { status: missing ? 'missing' : 'invalid', hooks: {}, mcp: {} };
80
+ }
81
+ }
82
+
83
+ /**
84
+ * Store choices. Only valid catalog ids reach this point (the CLI checks).
85
+ * @param {{ hooks: Record<string, boolean>, mcp: Record<string, boolean> }} value
86
+ */
87
+ export async function writePreferences(value) {
88
+ const root = await ensureStateRoot();
89
+ await atomicJson(preferencesPath(root), {
90
+ schemaVersion: SCHEMA_VERSION,
91
+ hooks: value.hooks,
92
+ mcp: value.mcp,
93
+ });
94
+ }
95
+
96
+ /**
97
+ * Each catalog hook with its effective state. An invalid file means defaults.
98
+ * @param {ExtensionPreferences} preferences
99
+ */
100
+ export function resolveHooks(preferences) {
101
+ const chosen = preferences.status === 'valid' ? preferences.hooks : {};
102
+ return HOOK_CATALOG.map((entry) => {
103
+ const choice = chosen[entry.id];
104
+ return {
105
+ entry,
106
+ enabled: choice ?? entry.defaultOn,
107
+ source: /** @type {'default' | 'choice'} */ (choice === undefined ? 'default' : 'choice'),
108
+ };
109
+ });
110
+ }
111
+
112
+ /** @param {ExtensionPreferences} preferences @returns {string[]} */
113
+ export function enabledHookIds(preferences) {
114
+ return resolveHooks(preferences)
115
+ .filter((hook) => hook.enabled)
116
+ .map((hook) => hook.entry.id);
117
+ }
118
+
119
+ /** Ids stored in the file that this client's catalog does not know. @param {ExtensionPreferences} preferences */
120
+ export function unknownHookIds(preferences) {
121
+ return Object.keys(preferences.hooks).filter((id) => hookById(id) === undefined);
122
+ }
123
+
124
+ /**
125
+ * Each catalog MCP server with its effective state. Every server defaults to
126
+ * off, and an invalid file switches them all off (FR3).
127
+ * @param {ExtensionPreferences} preferences
128
+ */
129
+ export function resolveServers(preferences) {
130
+ const chosen = preferences.status === 'valid' ? preferences.mcp : {};
131
+ return MCP_CATALOG.map((entry) => {
132
+ const choice = chosen[entry.id];
133
+ return {
134
+ entry,
135
+ enabled: choice ?? entry.defaultOn,
136
+ source: /** @type {'default' | 'choice'} */ (choice === undefined ? 'default' : 'choice'),
137
+ };
138
+ });
139
+ }
140
+
141
+ /** @param {ExtensionPreferences} preferences @returns {string[]} */
142
+ export function enabledServerIds(preferences) {
143
+ return resolveServers(preferences)
144
+ .filter((server) => server.enabled)
145
+ .map((server) => server.entry.id);
146
+ }
147
+
148
+ /** Server ids stored in the file that this client's catalog does not know. @param {ExtensionPreferences} preferences */
149
+ export function unknownServerIds(preferences) {
150
+ return Object.keys(preferences.mcp).filter((id) => mcpById(id) === undefined);
151
+ }