@knolo/cli 6.2.10 → 6.2.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.
package/bin/mount.mjs ADDED
@@ -0,0 +1,508 @@
1
+ import { createHash } from 'node:crypto';
2
+ import {
3
+ access,
4
+ mkdir,
5
+ readFile,
6
+ rename,
7
+ stat,
8
+ unlink,
9
+ writeFile,
10
+ } from 'node:fs/promises';
11
+ import { homedir } from 'node:os';
12
+ import path from 'node:path';
13
+ import { cachePath } from './registry/lockfile.mjs';
14
+
15
+ const MAX_IMAGE_BYTES = 512 * 1024 * 1024;
16
+ const SHA256_PATTERN = /^[a-f0-9]{64}$/;
17
+ const ROOT_PATTERN = /^sha256-[a-f0-9]{64}$/;
18
+ const ID_PATTERN = /^[a-zA-Z0-9_.-]+$/;
19
+ const DIGEST_PATTERN = /^sha256:([a-f0-9]{64})$/;
20
+ const PACK_PATTERN = /^([a-z0-9-]+)\/([a-z0-9-]+)@([^@\s]+)$/;
21
+
22
+ export async function runMountCli(args, options = {}) {
23
+ const action = args[0];
24
+ if (!action) throw new Error(usage());
25
+ if (action === 'list') return listMounts(args.slice(1), options);
26
+ if (action === 'remove') return removeMount(args.slice(1), options);
27
+ if (action === 'add') return addMount(args.slice(1), options);
28
+ throw new Error(`Unknown mount command ${action}.\n${usage()}`);
29
+ }
30
+
31
+ function usage() {
32
+ return `Usage: knolo mount add <publisher/slug@version | sha256:hex> --config <knolo-mcp.json> --policy <policy.json> [--path <image>] [--id <id>] [--agent <id>] [--audit-dir <dir>]
33
+ knolo mount list --config <knolo-mcp.json>
34
+ knolo mount remove <id> --config <knolo-mcp.json>`;
35
+ }
36
+
37
+ async function addMount(args, options) {
38
+ const { positional, flags } = parseFlags(args);
39
+ const ref = positional[0];
40
+ if (!ref || positional.length !== 1) throw new Error(usage());
41
+ if (!flags.config) throw new Error('--config requires a path.');
42
+ if (!flags.policy) throw new Error('--policy requires a path.');
43
+ const core = requiredCore(options.core);
44
+ const cwd = options.cwd ?? process.cwd();
45
+ const homeDir = options.homeDir ?? homedir();
46
+ const configPath = path.resolve(cwd, flags.config);
47
+ const policyPath = path.resolve(cwd, flags.policy);
48
+ const loaded = await readConfig(configPath);
49
+ const resolved = await resolveImage({
50
+ ref,
51
+ flags,
52
+ cwd,
53
+ homeDir,
54
+ lock: await readLock(cwd),
55
+ addPack: options.addPack ?? ((spec) => defaultAddPack(spec, options)),
56
+ });
57
+ const bytes = await readImage(resolved.filePath);
58
+ const sha256 = digest(bytes);
59
+ if (sha256 !== resolved.sha256) {
60
+ throw new Error('Image bytes do not match the pin. Nothing was written.');
61
+ }
62
+ let image;
63
+ try {
64
+ core.verifyKnowledgeImageV5(bytes);
65
+ image = core.mountKnowledgeImageV5(bytes);
66
+ } catch (error) {
67
+ throw new Error(
68
+ `Image failed V5 verification: ${messageOf(error)} Nothing was written.`
69
+ );
70
+ }
71
+ if (!ROOT_PATTERN.test(image.stateRoot)) {
72
+ throw new Error('Image has no stateRoot pin. Nothing was written.');
73
+ }
74
+ if (resolved.stateRoot && resolved.stateRoot !== image.stateRoot) {
75
+ throw new Error(
76
+ 'Image stateRoot does not match the pin. Nothing was written.'
77
+ );
78
+ }
79
+ const policy = await readPolicy(policyPath);
80
+ let policyRoot;
81
+ try {
82
+ policyRoot = core.knowledgePolicyRootV5(policy);
83
+ } catch (error) {
84
+ throw new Error(
85
+ `Policy is invalid: ${messageOf(error)} Nothing was written.`
86
+ );
87
+ }
88
+ if (policyRoot !== image.commit.policyRoot) {
89
+ throw new Error(
90
+ 'Policy root does not match the image. Nothing was written.'
91
+ );
92
+ }
93
+ const principal = readerPrincipal(policy);
94
+ const identity = mountIdentity(loaded.value, flags.agent);
95
+ const id = flags.id ?? resolved.id;
96
+ assertId(id, 'mount id');
97
+ const mount = {
98
+ id,
99
+ path: resolved.filePath,
100
+ sha256,
101
+ stateRoot: image.stateRoot,
102
+ policyPath,
103
+ agents: identity.agents,
104
+ principal,
105
+ };
106
+ const next = loaded.existed
107
+ ? replaceMount(loaded.value, mount)
108
+ : newConfig(identity.agentId, flags.auditDir, cwd, mount);
109
+ await writeConfig(configPath, next);
110
+ const report = {
111
+ ok: true,
112
+ action: 'add',
113
+ id,
114
+ path: mount.path,
115
+ sha256,
116
+ stateRoot: image.stateRoot,
117
+ principal,
118
+ config: configPath,
119
+ };
120
+ (options.print ?? console.log)(JSON.stringify(report, null, 2));
121
+ return report;
122
+ }
123
+
124
+ async function listMounts(args, options) {
125
+ const { positional, flags } = parseFlags(args);
126
+ if (positional.length !== 0) throw new Error(usage());
127
+ if (!flags.config) throw new Error('--config requires a path.');
128
+ const cwd = options.cwd ?? process.cwd();
129
+ const configPath = path.resolve(cwd, flags.config);
130
+ const loaded = await readConfig(configPath);
131
+ if (!loaded.existed) throw new Error(`Config not found: ${configPath}`);
132
+ const mounts = mountsOf(loaded.value).map((mount) => ({
133
+ id: mount.id,
134
+ path: mount.path,
135
+ sha256: mount.sha256,
136
+ stateRoot: mount.stateRoot,
137
+ principal: mount.principal,
138
+ }));
139
+ const report = { ok: true, action: 'list', config: configPath, mounts };
140
+ (options.print ?? console.log)(JSON.stringify(report, null, 2));
141
+ return report;
142
+ }
143
+
144
+ async function removeMount(args, options) {
145
+ const { positional, flags } = parseFlags(args);
146
+ const id = positional[0];
147
+ if (!id || positional.length !== 1) throw new Error(usage());
148
+ if (!flags.config) throw new Error('--config requires a path.');
149
+ const cwd = options.cwd ?? process.cwd();
150
+ const configPath = path.resolve(cwd, flags.config);
151
+ const loaded = await readConfig(configPath);
152
+ if (!loaded.existed) throw new Error(`Config not found: ${configPath}`);
153
+ const mounts = mountsOf(loaded.value);
154
+ if (!mounts.some((mount) => mount.id === id)) {
155
+ throw new Error(`Mount ${id} is not in the config. Nothing was written.`);
156
+ }
157
+ const remaining = mounts.filter((mount) => mount.id !== id);
158
+ if (remaining.length === 0) {
159
+ throw new Error('Refusing to remove the last mount. Nothing was written.');
160
+ }
161
+ await writeConfig(configPath, { ...loaded.value, mounts: remaining });
162
+ const report = { ok: true, action: 'remove', id, config: configPath };
163
+ (options.print ?? console.log)(JSON.stringify(report, null, 2));
164
+ return report;
165
+ }
166
+
167
+ async function resolveImage({ ref, flags, cwd, homeDir, lock, addPack }) {
168
+ const digestMatch = DIGEST_PATTERN.exec(ref);
169
+ if (digestMatch) {
170
+ const sha256 = digestMatch[1];
171
+ const filePath = flags.path
172
+ ? path.resolve(cwd, flags.path)
173
+ : cachePath(homeDir, sha256);
174
+ await assertPresent(
175
+ filePath,
176
+ 'Digest is not in the local cache. Pass --path to the image file. Nothing was written.'
177
+ );
178
+ return {
179
+ filePath,
180
+ sha256,
181
+ stateRoot: lockStateRoot(lock, sha256),
182
+ id: 'pack',
183
+ };
184
+ }
185
+ const packMatch = PACK_PATTERN.exec(ref);
186
+ if (!packMatch) {
187
+ throw new Error(
188
+ 'Reference must be publisher/slug@version or sha256:<64 hex>. Nothing was written.'
189
+ );
190
+ }
191
+ const name = `${packMatch[1]}/${packMatch[2]}`;
192
+ const version = packMatch[3];
193
+ const entry = lock.packs[name];
194
+ if (entry && String(entry.version) !== version) {
195
+ throw new Error(
196
+ `Lockfile pins ${name} at ${entry.version}. Nothing was written.`
197
+ );
198
+ }
199
+ if (flags.path) {
200
+ if (!entry?.sha256) {
201
+ throw new Error(
202
+ `Pack ${ref} is not in knolo.lock.json. Nothing was written.`
203
+ );
204
+ }
205
+ return {
206
+ filePath: path.resolve(cwd, flags.path),
207
+ sha256: entry.sha256,
208
+ stateRoot: typeof entry.stateRoot === 'string' ? entry.stateRoot : null,
209
+ id: packMatch[2],
210
+ };
211
+ }
212
+ if (entry?.sha256) {
213
+ const cached = cachePath(homeDir, entry.sha256);
214
+ try {
215
+ await access(cached);
216
+ return {
217
+ filePath: cached,
218
+ sha256: entry.sha256,
219
+ stateRoot: typeof entry.stateRoot === 'string' ? entry.stateRoot : null,
220
+ id: packMatch[2],
221
+ };
222
+ } catch (error) {
223
+ if (error?.code !== 'ENOENT') throw error;
224
+ }
225
+ }
226
+ const added = await addPack(ref);
227
+ if (!added?.path || !SHA256_PATTERN.test(added.sha256 ?? '')) {
228
+ throw new Error(
229
+ 'knolo add did not return a pinned image. Nothing was written.'
230
+ );
231
+ }
232
+ return {
233
+ filePath: path.resolve(added.path),
234
+ sha256: added.sha256,
235
+ stateRoot: typeof added.stateRoot === 'string' ? added.stateRoot : null,
236
+ id: packMatch[2],
237
+ };
238
+ }
239
+
240
+ function lockStateRoot(lock, sha256) {
241
+ let found = null;
242
+ for (const entry of Object.values(lock.packs)) {
243
+ if (entry?.sha256 !== sha256 || typeof entry.stateRoot !== 'string')
244
+ continue;
245
+ if (found && found !== entry.stateRoot) {
246
+ throw new Error(
247
+ 'knolo.lock.json has two state roots for this digest. Nothing was written.'
248
+ );
249
+ }
250
+ found = entry.stateRoot;
251
+ }
252
+ return found;
253
+ }
254
+
255
+ async function defaultAddPack(ref, options) {
256
+ const { runHubAdd } = await import('./registry/commands.mjs');
257
+ return runHubAdd([ref], {
258
+ core: options.core,
259
+ cwd: options.cwd ?? process.cwd(),
260
+ homeDir: options.homeDir ?? homedir(),
261
+ env: options.env ?? process.env,
262
+ print: options.print ?? console.log,
263
+ });
264
+ }
265
+
266
+ function requiredCore(core) {
267
+ if (
268
+ !core?.verifyKnowledgeImageV5 ||
269
+ !core?.mountKnowledgeImageV5 ||
270
+ !core?.knowledgePolicyRootV5
271
+ ) {
272
+ throw new Error('Could not load @knolo/core for the mount check.');
273
+ }
274
+ return core;
275
+ }
276
+
277
+ function readerPrincipal(policy) {
278
+ const named = new Set();
279
+ for (const rule of policy.rules ?? []) {
280
+ if (typeof rule?.principal === 'string' && rule.principal)
281
+ named.add(rule.principal);
282
+ }
283
+ if (named.size === 0 && policy.default === 'allow') named.add('mcp:reader');
284
+ const matches = [...named]
285
+ .filter(
286
+ (principal) =>
287
+ allows(policy, principal, 'query') && allows(policy, principal, 'read')
288
+ )
289
+ .sort();
290
+ if (matches.length === 0) {
291
+ throw new Error(
292
+ 'Policy allows no principal for query and read. Nothing was written.'
293
+ );
294
+ }
295
+ return matches[0];
296
+ }
297
+
298
+ function allows(policy, principal, action) {
299
+ const matches = (policy.rules ?? []).filter(
300
+ (rule) =>
301
+ rule?.action === action &&
302
+ (rule.principal === undefined || rule.principal === principal) &&
303
+ (rule.kind === undefined || String(rule.kind).toLowerCase() === 'chunk')
304
+ );
305
+ if (matches.some((rule) => rule.effect === 'deny')) return false;
306
+ if (matches.some((rule) => rule.effect === 'allow')) return true;
307
+ return policy.default === 'allow';
308
+ }
309
+
310
+ function mountIdentity(existing, requested) {
311
+ const agents = [...requested];
312
+ for (const agent of agents) assertId(agent, 'agent');
313
+ if (!existing) {
314
+ const selected = agents.length > 0 ? agents : ['mcp'];
315
+ return { agentId: selected[0], agents: unique(selected) };
316
+ }
317
+ if (typeof existing.agentId !== 'string') {
318
+ throw new Error('Config agentId is missing. Nothing was written.');
319
+ }
320
+ assertId(existing.agentId, 'agentId');
321
+ return {
322
+ agentId: existing.agentId,
323
+ agents: unique([existing.agentId, ...agents]),
324
+ };
325
+ }
326
+
327
+ function newConfig(agentId, auditDir, cwd, mount) {
328
+ if (!auditDir)
329
+ throw new Error(
330
+ '--audit-dir is required for a new config. Nothing was written.'
331
+ );
332
+ const resolved = path.resolve(cwd, auditDir);
333
+ if (!path.isAbsolute(resolved)) {
334
+ throw new Error(
335
+ '--audit-dir must be an absolute path. Nothing was written.'
336
+ );
337
+ }
338
+ return { agentId, auditDir: resolved, mounts: [mount] };
339
+ }
340
+
341
+ function replaceMount(config, mount) {
342
+ const mounts = mountsOf(config);
343
+ const next = mounts.filter((item) => item.id !== mount.id);
344
+ next.push(mount);
345
+ return { ...config, mounts: next };
346
+ }
347
+
348
+ function mountsOf(config) {
349
+ if (!Array.isArray(config.mounts)) {
350
+ throw new Error('Config mounts must be an array. Nothing was written.');
351
+ }
352
+ return config.mounts;
353
+ }
354
+
355
+ async function readPolicy(policyPath) {
356
+ let text;
357
+ try {
358
+ text = await readFile(policyPath, 'utf8');
359
+ } catch (error) {
360
+ throw new Error(
361
+ `Could not read policy: ${messageOf(error)} Nothing was written.`
362
+ );
363
+ }
364
+ try {
365
+ const policy = JSON.parse(text);
366
+ if (!policy || typeof policy !== 'object' || Array.isArray(policy)) {
367
+ throw new Error('policy must be a JSON object');
368
+ }
369
+ return policy;
370
+ } catch (error) {
371
+ throw new Error(
372
+ `Policy is invalid: ${messageOf(error)} Nothing was written.`
373
+ );
374
+ }
375
+ }
376
+
377
+ async function readImage(filePath) {
378
+ let metadata;
379
+ try {
380
+ metadata = await stat(filePath);
381
+ } catch (error) {
382
+ throw new Error(
383
+ `Could not read image: ${messageOf(error)} Nothing was written.`
384
+ );
385
+ }
386
+ if (!metadata.isFile() || metadata.size > MAX_IMAGE_BYTES) {
387
+ throw new Error(
388
+ 'Image must be a file no larger than 512 MB. Nothing was written.'
389
+ );
390
+ }
391
+ return new Uint8Array(await readFile(filePath));
392
+ }
393
+
394
+ async function assertPresent(filePath, missingMessage) {
395
+ try {
396
+ await access(filePath);
397
+ } catch (error) {
398
+ if (error?.code === 'ENOENT') throw new Error(missingMessage);
399
+ throw error;
400
+ }
401
+ }
402
+
403
+ async function readConfig(configPath) {
404
+ let text;
405
+ try {
406
+ text = await readFile(configPath, 'utf8');
407
+ } catch (error) {
408
+ if (error?.code === 'ENOENT') return { existed: false, value: null };
409
+ throw error;
410
+ }
411
+ try {
412
+ const value = JSON.parse(text);
413
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
414
+ throw new Error('not an object');
415
+ }
416
+ return { existed: true, value };
417
+ } catch {
418
+ throw new Error('knolo-mcp.json is invalid JSON. Nothing was written.');
419
+ }
420
+ }
421
+
422
+ async function readLock(cwd) {
423
+ const filePath = path.resolve(cwd, 'knolo.lock.json');
424
+ let text;
425
+ try {
426
+ text = await readFile(filePath, 'utf8');
427
+ } catch (error) {
428
+ if (error?.code === 'ENOENT') return { packs: {} };
429
+ throw error;
430
+ }
431
+ let value;
432
+ try {
433
+ value = JSON.parse(text);
434
+ } catch {
435
+ throw new Error('knolo.lock.json is invalid JSON. Nothing was written.');
436
+ }
437
+ const packs =
438
+ value?.packs &&
439
+ typeof value.packs === 'object' &&
440
+ !Array.isArray(value.packs)
441
+ ? value.packs
442
+ : {};
443
+ return { packs };
444
+ }
445
+
446
+ async function writeConfig(configPath, value) {
447
+ const directory = path.dirname(configPath);
448
+ await mkdir(directory, { recursive: true, mode: 0o700 });
449
+ const tempPath = path.join(
450
+ directory,
451
+ `.${path.basename(configPath)}.${process.pid}.next`
452
+ );
453
+ await writeFile(tempPath, `${JSON.stringify(value, null, 2)}\n`, {
454
+ mode: 0o600,
455
+ });
456
+ try {
457
+ await rename(tempPath, configPath);
458
+ } catch (error) {
459
+ await unlink(tempPath).catch(() => {});
460
+ throw error;
461
+ }
462
+ }
463
+
464
+ function parseFlags(args) {
465
+ const positional = [];
466
+ const flags = { agent: [] };
467
+ for (let index = 0; index < args.length; index += 1) {
468
+ const arg = args[index];
469
+ if (
470
+ arg === '--config' ||
471
+ arg === '--policy' ||
472
+ arg === '--path' ||
473
+ arg === '--id' ||
474
+ arg === '--audit-dir' ||
475
+ arg === '--agent'
476
+ ) {
477
+ const value = args[index + 1];
478
+ if (!value || value.startsWith('--'))
479
+ throw new Error(`${arg} requires a value.`);
480
+ index += 1;
481
+ if (arg === '--agent') flags.agent.push(value);
482
+ else if (arg === '--audit-dir') flags.auditDir = value;
483
+ else flags[arg.slice(2)] = value;
484
+ continue;
485
+ }
486
+ if (arg.startsWith('--')) throw new Error(`Unknown option ${arg}.`);
487
+ positional.push(arg);
488
+ }
489
+ return { positional, flags };
490
+ }
491
+
492
+ function assertId(value, label) {
493
+ if (!ID_PATTERN.test(value)) {
494
+ throw new Error(`${label} must match ${ID_PATTERN}. Nothing was written.`);
495
+ }
496
+ }
497
+
498
+ function unique(values) {
499
+ return [...new Set(values)];
500
+ }
501
+
502
+ function digest(bytes) {
503
+ return createHash('sha256').update(bytes).digest('hex');
504
+ }
505
+
506
+ function messageOf(error) {
507
+ return error instanceof Error ? error.message : String(error);
508
+ }