@knolo/cli 6.2.8 → 6.2.9

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 CHANGED
@@ -19,8 +19,8 @@ reader.
19
19
 
20
20
  `knolo compose`, `knolo attest`, and `knolo verify-attestation` cite local
21
21
  Knowledge Images and write an attestation sidecar. This tree's `@knolo/cli`
22
- package file is `6.2.7` and depends on `@knolo/core` `^6.2.3` and
23
- `@knolo/exchange` `^0.1.0`. npm `latest` is `6.2.7`. `knolo kite` is in this
22
+ package file is `6.2.8` and depends on `@knolo/core` `^6.2.3` and
23
+ `@knolo/exchange` `^0.1.1`. npm `latest` is `6.2.8`. `knolo kite`, `knolo research verify`, and `knolo exchange relay` are in this
24
24
  package and in that release. It is not in published `@knolo/cli@6.2.5`. `knolo exchange` hands
25
25
  a verified V5 image to another agent. Shipped configs keep `adopt: deny`.
26
26
  Discover reads a public advertisement and does not download a pack. They do
@@ -91,8 +91,28 @@ changing the local pack workflow:
91
91
  knolo search "refund policy"
92
92
  knolo search "refund policy" --research
93
93
  knolo info acme/refund-policy
94
+ knolo ask "what is the refund window?" --category business --model llama3.2
95
+ knolo ask "how does rust ownership work" --category coding --category math --evidence
96
+ knolo ask "what changed overnight" --all --model llama3.2
94
97
  ```
95
98
 
99
+ `knolo ask` posts the question to `POST /api/v1/knowledge/query`, checks each
100
+ excerpt sha256, and sends the verified excerpts and skill instructions to an
101
+ OpenAI-compatible chat endpoint. The default is Ollama at
102
+ `http://127.0.0.1:11434/v1`. Set `KNOLO_MODEL_BASE_URL` and `KNOLO_MODEL` for
103
+ another local server or a cloud gateway such as `https://api.x.ai/v1`.
104
+ `KNOLO_MODEL_API_KEY` is sent only to that endpoint. Hub does not receive the
105
+ key or the answer, and it does not install a matched skill. Pass `--category`
106
+ one or more times, or pass `--all` to search the entire hub. With neither,
107
+ the command exits before the network call. `--evidence` prints skills first,
108
+ then excerpts, and does not call a model. A `402` plan limit does not call
109
+ the model. With no remaining evidence the command exits 1 and does not call
110
+ the model. If only a skill remains, the model still runs with that skill text.
111
+
112
+ `knolo publish` and `knolo skill publish` take the same repeatable
113
+ `--category`. A new pack and every skill publish use 1 to 3 of `coding`,
114
+ `math`, `science`, `news`, `business`, `security`, `writing`, `general`.
115
+
96
116
  `--research` asks for packs whose image metadata role is `research-pack`.
97
117
  `--agents` remains the agent-definition namespace.
98
118
 
@@ -390,7 +410,7 @@ This ensures:
390
410
  ## 🗺 Roadmap
391
411
 
392
412
  The active roadmap is maintained in [`../../docs/ROADMAP.md`](../../docs/ROADMAP.md).
393
- The published npm release is `6.2.7`. This tree's package file is `6.2.7` and adds `knolo kite`. `@knolo/cli@6.2.5` does not include that command. The published release preserves the V4 CLI, keeps V5 verification,
413
+ The published npm release is `6.2.8`. This tree's package file is `6.2.8` and adds `knolo research verify` and `knolo exchange relay`. `@knolo/cli@6.2.7` does not include those commands. `@knolo/cli@6.2.5` does not include `knolo kite`. The published release preserves the V4 CLI, keeps V5 verification,
394
414
  migration, diagnostics, and read-only Studio management, and adds offline
395
415
  composition, attestation, and `knolo cortex`. Cortex verification does not
396
416
  mean an answer is true.
package/bin/knolo.mjs CHANGED
@@ -31,6 +31,7 @@ import {
31
31
  runHubWhoami,
32
32
  runHubYank,
33
33
  } from './registry/commands.mjs';
34
+ import { runHubAsk } from './registry/ask.mjs';
34
35
 
35
36
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
36
37
  const require = createRequire(import.meta.url);
@@ -63,6 +64,7 @@ const SUBCOMMANDS = new Set([
63
64
  'dev',
64
65
  'v5',
65
66
  'search',
67
+ 'ask',
66
68
  'info',
67
69
  'login',
68
70
  'whoami',
@@ -162,6 +164,7 @@ Commands:
162
164
  init Initialize knolo.config.json and starter docs
163
165
  add <name> <path> Add or update a local source entry, or install a Hub pack
164
166
  search <query> Search the Knolo Hub registry
167
+ ask "<question>" Answer from Hub excerpts with your model
165
168
  info <publisher>/<slug> Show a Hub registry pack
166
169
  login Store a Hub token locally
167
170
  whoami Show the stored Hub token prefix
@@ -203,13 +206,15 @@ function printCommandHelp(command) {
203
206
  add: 'Usage: knolo add <name> <path> | <publisher>/<slug>[@<version>] [--out <path>] [--force] [--json] [--registry <url>]',
204
207
  search:
205
208
  'Usage: knolo search <query> [--format V4|V5] [--license <id>] [--official] [--agents] [--research] [--json] [--registry <url>]',
209
+ ask:
210
+ 'Usage: knolo ask "<question>" [--category <id>] [--all] [--model <name>] [--base-url <url>] [--limit <n>] [--evidence] [--hub <url>]\n\nPosts the question to Hub and sends the verified excerpts and skill instructions to an OpenAI-compatible chat endpoint. The default base URL is http://127.0.0.1:11434/v1 (Ollama). Set KNOLO_MODEL_BASE_URL and KNOLO_MODEL for another engine, including a cloud gateway such as https://api.x.ai/v1. KNOLO_MODEL_API_KEY is sent only to that endpoint.\nPass --category one or more times, or pass --all to search the entire hub. With neither, ask exits before the network call. --evidence prints skills first, then excerpts, and does not call a model. A plan limit does not call a model. --hub is the same registry override as --registry.',
206
211
  info: 'Usage: knolo info <publisher>/<slug> [--json] [--registry <url>]',
207
212
  login:
208
213
  'Usage: knolo login [--token kno_…] [--stdin] [--registry <url>]\n\nStores the raw token locally. Hub write calls send Authorization: Bearer kno_….\nMint tokens at https://hub.knolo.dev/dashboard/tokens; login does not call POST /api/v1/tokens.',
209
214
  whoami: 'Usage: knolo whoami',
210
215
  logout: 'Usage: knolo logout',
211
216
  publish:
212
- 'Usage: knolo publish <pack.knolo> --slug <slug> --version <version> --license <SPDX> [--publisher <handle>] [--readme <text>] [--sources <text>] [--intended-use <text>] [--private] [--json] [--registry <url>]\n\nUses the stored dashboard token as Authorization: Bearer kno_…. Hub issues a public Blob PUT grant; the CLI never needs PACKS_READ_WRITE_TOKEN.\nUploads go to the grant URL without the kno_ token. Complete sends the public Blob URL, then Hub verifies before release.\n--private releases an owner-only pack on a Business or Enterprise plan. The success text omits the Blob URL.',
217
+ 'Usage: knolo publish <pack.knolo> --slug <slug> --version <version> --license <SPDX> [--publisher <handle>] [--readme <text>] [--sources <text>] [--intended-use <text>] [--category <id>] [--private] [--json] [--registry <url>]\n\nUses the stored dashboard token as Authorization: Bearer kno_…. Hub issues a public Blob PUT grant; the CLI never needs PACKS_READ_WRITE_TOKEN.\nUploads go to the grant URL without the kno_ token. Complete sends the public Blob URL, then Hub verifies before release.\n--category is repeatable, from 1 to 3 of coding, math, science, news, business, security, writing, general. A new pack needs at least one. --private releases an owner-only pack on a Business or Enterprise plan. The success text omits the Blob URL.',
213
218
  yank: 'Usage: knolo yank <publisher>/<slug>@<version> [--json] [--registry <url>]\n\nUses the stored token as Authorization: Bearer kno_…. Yank is owner-only and leaves the public Blob in place.',
214
219
  build: 'Usage: knolo build',
215
220
  query:
@@ -269,7 +274,7 @@ and it is not Knolo Hub. offer --via uploads to that relay instead of serve.`,
269
274
  knolo skill init <name> [--dir <parent>]
270
275
  knolo skill check [<dir>] [--query <text>] [--json]
271
276
  knolo skill pack [<dir>] [--out <dir>] [--json]
272
- knolo skill publish <pack> [--registry <url>] [--json]
277
+ knolo skill publish <pack> [--category <id>] [--registry <url>] [--json]
273
278
  knolo skill publish <pack> --hub <dir> [--json]
274
279
  knolo skill install <publisher>/<name> [--dir <path>] [--registry <url>] [--json]
275
280
  knolo skill install <name> --hub <dir> [--dir <path>] [--json]
@@ -1971,6 +1976,11 @@ async function main() {
1971
1976
  if (command === 'init') return await cmdInit();
1972
1977
  if (command === 'add') return await cmdAdd(commandArgs);
1973
1978
  if (command === 'search') return await runHubSearch(commandArgs);
1979
+ if (command === 'ask') {
1980
+ const result = await runHubAsk(commandArgs);
1981
+ if (result.exitCode) process.exit(result.exitCode);
1982
+ return;
1983
+ }
1974
1984
  if (command === 'info') return await runHubInfo(commandArgs);
1975
1985
  if (command === 'login') return await runHubLogin(commandArgs);
1976
1986
  if (command === 'whoami') return await runHubWhoami(commandArgs);
@@ -0,0 +1,334 @@
1
+ import { createHash } from 'node:crypto';
2
+ import {
3
+ normalizeRegistryUrl,
4
+ registryApiUrl,
5
+ resolveRegistryUrl,
6
+ } from './config.mjs';
7
+ import { normalizeCategories } from './categories.mjs';
8
+ import { loadCredentials } from './credentials.mjs';
9
+ import { RegistryError, RegistryNetworkError } from './errors.mjs';
10
+ import { postJson } from './http.mjs';
11
+
12
+ export const DEFAULT_MODEL_BASE_URL = 'http://127.0.0.1:11434/v1';
13
+ export const ASK_SYSTEM_PROMPT =
14
+ 'Answer only from the excerpts and any skill instructions in the prompt. Cite each knowledge claim with publisher/slug@version and the object id. Cite a skill as publisher/name. Do not use outside knowledge.';
15
+
16
+ const SHA256_HEX = /^[0-9a-f]{64}$/;
17
+
18
+ export function excerptDigest(excerpt) {
19
+ return createHash('sha256').update(excerpt, 'utf8').digest('hex');
20
+ }
21
+
22
+ export function citation(hit) {
23
+ return `${hit.publisher}/${hit.slug}@${hit.version} ${hit.objectId}`;
24
+ }
25
+
26
+ export function normalizeModelBaseUrl(value) {
27
+ if (typeof value !== 'string' || !value.trim()) {
28
+ throw new Error('Model base URL must be an HTTP(S) URL.');
29
+ }
30
+ let url;
31
+ try {
32
+ url = new URL(value.trim());
33
+ } catch {
34
+ throw new Error(`Invalid model base URL: ${value}`);
35
+ }
36
+ if (!['http:', 'https:'].includes(url.protocol)) {
37
+ throw new Error('Model base URL must use http or https.');
38
+ }
39
+ if (url.username || url.password) {
40
+ throw new Error('Model base URL must not include credentials.');
41
+ }
42
+ url.search = '';
43
+ url.hash = '';
44
+ const pathname = url.pathname.replace(/\/+$/, '');
45
+ return `${url.origin}${pathname === '/' ? '' : pathname}`;
46
+ }
47
+
48
+ export function chatCompletionsUrl(baseUrl) {
49
+ return `${normalizeModelBaseUrl(baseUrl)}/chat/completions`;
50
+ }
51
+
52
+ export function parseAskArgs(args) {
53
+ const positional = [];
54
+ const flags = {};
55
+ for (let i = 0; i < args.length; i += 1) {
56
+ const arg = args[i];
57
+ if (arg === '--evidence') {
58
+ flags.evidence = true;
59
+ continue;
60
+ }
61
+ if (arg === '--all') {
62
+ flags.all = true;
63
+ continue;
64
+ }
65
+ if (arg === '--category') {
66
+ const value = args[++i];
67
+ if (value === undefined || value.startsWith('--')) {
68
+ throw new Error('Missing value for --category');
69
+ }
70
+ flags.categories = [...(flags.categories ?? []), value];
71
+ continue;
72
+ }
73
+ if (['--model', '--base-url', '--limit', '--hub', '--registry'].includes(arg)) {
74
+ const value = args[++i];
75
+ if (value === undefined || value.startsWith('--')) {
76
+ throw new Error(`Missing value for ${arg}`);
77
+ }
78
+ if (arg === '--hub' || arg === '--registry') flags.hub = value;
79
+ else flags[arg.slice(2)] = value;
80
+ continue;
81
+ }
82
+ if (arg.startsWith('--')) throw new Error(`Unknown flag for ask: ${arg}`);
83
+ positional.push(arg);
84
+ }
85
+
86
+ const question = positional.join(' ').trim();
87
+ if (!question) {
88
+ throw new Error(
89
+ 'Usage: knolo ask "<question>" [--category <id>] [--all] [--model <name>] [--base-url <url>] [--limit <n>] [--evidence] [--hub <url>]'
90
+ );
91
+ }
92
+ if (flags.all && flags.categories) {
93
+ throw new Error('Use either --all or --category, not both.');
94
+ }
95
+ if (!flags.all && !flags.categories) {
96
+ throw new Error('Pick one category with --category, or pass --all to search the entire hub.');
97
+ }
98
+ if (flags.categories) {
99
+ flags.categories = normalizeCategories(flags.categories, { min: 1, max: 8 });
100
+ }
101
+ if (flags.limit !== undefined) {
102
+ if (!/^[1-9]\d*$/.test(flags.limit)) {
103
+ throw new Error('--limit must be an integer from 1 to 20.');
104
+ }
105
+ const limit = Number(flags.limit);
106
+ if (limit < 1 || limit > 20) {
107
+ throw new Error('--limit must be an integer from 1 to 20.');
108
+ }
109
+ flags.limit = limit;
110
+ }
111
+ return { question, flags };
112
+ }
113
+
114
+ function modelName(flags, env) {
115
+ const name = flags.model || env.KNOLO_MODEL;
116
+ return typeof name === 'string' && name.trim() ? name.trim() : '';
117
+ }
118
+
119
+ function modelBase(flags, env) {
120
+ return normalizeModelBaseUrl(
121
+ flags['base-url'] || env.KNOLO_MODEL_BASE_URL || DEFAULT_MODEL_BASE_URL
122
+ );
123
+ }
124
+
125
+ async function hubToken(registry, { env, homeDir }) {
126
+ try {
127
+ const credentials = await loadCredentials({ env, homeDir });
128
+ if (normalizeRegistryUrl(credentials.registry) !== normalizeRegistryUrl(registry)) {
129
+ return undefined;
130
+ }
131
+ return credentials.token;
132
+ } catch (error) {
133
+ if (error instanceof Error && error.message.startsWith('Not logged in')) {
134
+ return undefined;
135
+ }
136
+ throw error;
137
+ }
138
+ }
139
+
140
+ function asHit(value) {
141
+ if (!value || typeof value !== 'object') return null;
142
+ const hit = value;
143
+ if (typeof hit.publisher !== 'string' || !hit.publisher.trim()) return null;
144
+ if (typeof hit.slug !== 'string' || !hit.slug.trim()) return null;
145
+ if (typeof hit.version !== 'string' || !hit.version.trim()) return null;
146
+ if (typeof hit.objectId !== 'string' || !hit.objectId.trim()) return null;
147
+ if (typeof hit.excerpt !== 'string' || !hit.excerpt) return null;
148
+ if (typeof hit.excerptSha256 !== 'string' || !SHA256_HEX.test(hit.excerptSha256.toLowerCase())) {
149
+ return null;
150
+ }
151
+ if (excerptDigest(hit.excerpt) !== hit.excerptSha256.toLowerCase()) return null;
152
+ return {
153
+ publisher: hit.publisher,
154
+ slug: hit.slug,
155
+ version: hit.version,
156
+ objectId: hit.objectId,
157
+ heading: typeof hit.heading === 'string' ? hit.heading : '',
158
+ excerpt: hit.excerpt,
159
+ excerptSha256: hit.excerptSha256.toLowerCase(),
160
+ };
161
+ }
162
+
163
+ export function verifiedHits(hits) {
164
+ if (!Array.isArray(hits)) return [];
165
+ return hits.map(asHit).filter((hit) => hit !== null);
166
+ }
167
+
168
+ function asSkill(value) {
169
+ if (!value || typeof value !== 'object') return null;
170
+ const skill = value;
171
+ if (typeof skill.publisher !== 'string' || !skill.publisher.trim()) return null;
172
+ if (typeof skill.name !== 'string' || !skill.name.trim()) return null;
173
+ if (typeof skill.excerpt !== 'string' || !skill.excerpt) return null;
174
+ if (typeof skill.excerptSha256 !== 'string' || !SHA256_HEX.test(skill.excerptSha256.toLowerCase())) {
175
+ return null;
176
+ }
177
+ if (excerptDigest(skill.excerpt) !== skill.excerptSha256.toLowerCase()) return null;
178
+ if (typeof skill.skillSha256 !== 'string' || !SHA256_HEX.test(skill.skillSha256.toLowerCase())) {
179
+ return null;
180
+ }
181
+ return {
182
+ publisher: skill.publisher,
183
+ name: skill.name,
184
+ description: typeof skill.description === 'string' ? skill.description : '',
185
+ excerpt: skill.excerpt,
186
+ excerptSha256: skill.excerptSha256.toLowerCase(),
187
+ skillSha256: skill.skillSha256.toLowerCase(),
188
+ };
189
+ }
190
+
191
+ export function verifiedSkills(skills) {
192
+ if (!Array.isArray(skills)) return [];
193
+ return skills.map(asSkill).filter((skill) => skill !== null);
194
+ }
195
+
196
+ function printEvidence(skills, hits, print) {
197
+ for (const skill of skills) {
198
+ print(`${skill.publisher}/${skill.name}`);
199
+ if (skill.description) print(skill.description);
200
+ print(skill.excerpt);
201
+ print(skill.excerptSha256);
202
+ print('');
203
+ }
204
+ for (const hit of hits) {
205
+ print(citation(hit));
206
+ if (hit.heading) print(hit.heading);
207
+ print(hit.excerpt);
208
+ print(hit.excerptSha256);
209
+ print('');
210
+ }
211
+ }
212
+
213
+ function answerText(body) {
214
+ const content = body?.choices?.[0]?.message?.content;
215
+ return typeof content === 'string' ? content.trim() : '';
216
+ }
217
+
218
+ /**
219
+ * Queries Hub, checks excerpt hashes, then asks the user's chat endpoint.
220
+ * The model key is sent only to that endpoint. Hub never receives it.
221
+ */
222
+ export async function runHubAsk(
223
+ args,
224
+ {
225
+ env = process.env,
226
+ fetchImpl = globalThis.fetch,
227
+ homeDir,
228
+ print = console.log,
229
+ printError = console.error,
230
+ } = {}
231
+ ) {
232
+ const { question, flags } = parseAskArgs(args);
233
+ const model = modelName(flags, env);
234
+ if (!flags.evidence && !model) {
235
+ throw new Error(
236
+ 'Set --model or KNOLO_MODEL. Use --evidence to print Hub excerpts without a model.'
237
+ );
238
+ }
239
+
240
+ const registry = resolveRegistryUrl({ value: flags.hub, env });
241
+ const url = registryApiUrl(registry, ['knowledge', 'query']);
242
+ const token = await hubToken(registry, { env, homeDir });
243
+ const headers = token ? { Authorization: `Bearer ${token}` } : {};
244
+ const body = { q: question };
245
+ if (flags.limit !== undefined) body.limit = flags.limit;
246
+ if (flags.categories) body.categories = flags.categories;
247
+
248
+ let response;
249
+ try {
250
+ response = await postJson(url, body, { fetchImpl, headers });
251
+ } catch (error) {
252
+ // A 402 plan_limit is a RegistryError. Do not call the model.
253
+ const message = error instanceof RegistryNetworkError || error instanceof RegistryError
254
+ ? error.message
255
+ : 'Could not query Hub.';
256
+ printError(message);
257
+ return { exitCode: 1, registry, calls: 1 };
258
+ }
259
+
260
+ const hits = verifiedHits(response?.hits);
261
+ const skills = verifiedSkills(response?.skills);
262
+ if (!hits.length && !skills.length) {
263
+ printError('Hub has no matching evidence.');
264
+ return { exitCode: 1, registry, calls: 1 };
265
+ }
266
+
267
+ if (flags.evidence) {
268
+ printEvidence(skills, hits, print);
269
+ return { exitCode: 0, registry, hits, skills, calls: 1 };
270
+ }
271
+
272
+ const baseUrl = modelBase(flags, env);
273
+ const endpoint = chatCompletionsUrl(baseUrl);
274
+ const apiKey = typeof env.KNOLO_MODEL_API_KEY === 'string' ? env.KNOLO_MODEL_API_KEY.trim() : '';
275
+ const modelHeaders = { 'content-type': 'application/json' };
276
+ if (apiKey) modelHeaders.authorization = `Bearer ${apiKey}`;
277
+ const promptParts = [`Question: ${question}`, ''];
278
+ if (skills.length) {
279
+ promptParts.push(
280
+ 'Skills:',
281
+ ...skills.map((skill) => `Skill: ${skill.publisher}/${skill.name}\n${skill.description}\n${skill.excerpt}`),
282
+ ''
283
+ );
284
+ }
285
+ if (hits.length) {
286
+ promptParts.push(
287
+ 'Excerpts:',
288
+ ...hits.map((hit) => `Source: ${citation(hit)}\nHeading: ${hit.heading}\n${hit.excerpt}`)
289
+ );
290
+ }
291
+ const prompt = promptParts.join('\n');
292
+
293
+ let modelResponse;
294
+ try {
295
+ modelResponse = await fetchImpl(endpoint, {
296
+ method: 'POST',
297
+ headers: modelHeaders,
298
+ body: JSON.stringify({
299
+ model,
300
+ messages: [
301
+ { role: 'system', content: ASK_SYSTEM_PROMPT },
302
+ { role: 'user', content: prompt },
303
+ ],
304
+ }),
305
+ });
306
+ } catch {
307
+ printError('Model endpoint is unavailable. Excerpts follow.');
308
+ printEvidence(skills, hits, print);
309
+ return { exitCode: 2, registry, hits, skills, calls: 2 };
310
+ }
311
+
312
+ let modelBody;
313
+ try {
314
+ const text = typeof modelResponse?.text === 'function' ? await modelResponse.text() : '';
315
+ modelBody = text ? JSON.parse(text) : undefined;
316
+ } catch {
317
+ modelBody = undefined;
318
+ }
319
+
320
+ const answer = modelResponse?.ok ? answerText(modelBody) : '';
321
+ if (!answer) {
322
+ const status = typeof modelResponse?.status === 'number' ? modelResponse.status : 'error';
323
+ printError(`Model endpoint returned HTTP ${status}. Excerpts follow.`);
324
+ printEvidence(skills, hits, print);
325
+ return { exitCode: 2, registry, hits, skills, calls: 2 };
326
+ }
327
+
328
+ print(answer);
329
+ print('');
330
+ print('Citations:');
331
+ for (const skill of skills) print(`${skill.publisher}/${skill.name}`);
332
+ for (const hit of hits) print(citation(hit));
333
+ return { exitCode: 0, registry, hits, skills, calls: 2 };
334
+ }
@@ -0,0 +1,31 @@
1
+ export const KNOWLEDGE_CATEGORIES = [
2
+ 'coding',
3
+ 'math',
4
+ 'science',
5
+ 'news',
6
+ 'business',
7
+ 'security',
8
+ 'writing',
9
+ 'general',
10
+ ];
11
+
12
+ const IDS = new Set(KNOWLEDGE_CATEGORIES);
13
+
14
+ export function normalizeCategories(values, { min = 1, max = KNOWLEDGE_CATEGORIES.length } = {}) {
15
+ if (values == null) return null;
16
+ const list = Array.isArray(values) ? values : [values];
17
+ if (list.length === 0) {
18
+ throw new Error(`Choose ${min} to ${max} categories.`);
19
+ }
20
+ const seen = [];
21
+ for (const value of list) {
22
+ if (typeof value !== 'string' || !IDS.has(value)) {
23
+ throw new Error(`--category must be one of ${KNOWLEDGE_CATEGORIES.join(', ')}.`);
24
+ }
25
+ if (!seen.includes(value)) seen.push(value);
26
+ }
27
+ if (seen.length < min || seen.length > max) {
28
+ throw new Error(`Choose ${min} to ${max} categories.`);
29
+ }
30
+ return seen;
31
+ }
@@ -22,6 +22,7 @@ import {
22
22
  readArtifact,
23
23
  stageCachedArtifact,
24
24
  } from './artifacts.mjs';
25
+ import { normalizeCategories } from './categories.mjs';
25
26
  import { RegistryError } from './errors.mjs';
26
27
  import { getJson, postJson, putBytes } from './http.mjs';
27
28
  import {
@@ -445,6 +446,7 @@ export async function runHubPublish(
445
446
  ...(flags.intendedUse !== undefined
446
447
  ? { intendedUse: flags.intendedUse }
447
448
  : {}),
449
+ ...(flags.categories ? { categories: flags.categories } : {}),
448
450
  };
449
451
  const draftResponse = await postHubJson(
450
452
  registryApiUrl(registry, ['publish', 'drafts']),
@@ -561,6 +563,14 @@ export function parsePublishArgs(args) {
561
563
  flags.private = true;
562
564
  continue;
563
565
  }
566
+ if (arg === '--category') {
567
+ const value = args[++i];
568
+ if (value === undefined || value.startsWith('--')) {
569
+ throw new Error('Missing value for --category');
570
+ }
571
+ flags.categories = [...(flags.categories ?? []), value];
572
+ continue;
573
+ }
564
574
  if (valueFlags.has(arg)) {
565
575
  const value = args[++i];
566
576
  if (value === undefined || value.startsWith('--'))
@@ -580,7 +590,7 @@ export function parsePublishArgs(args) {
580
590
  !flags.license
581
591
  ) {
582
592
  throw new Error(
583
- 'Usage: knolo publish <pack.knolo> --slug <slug> --version <version> --license <SPDX> [--publisher <handle>] [--readme <text>] [--sources <text>] [--intended-use <text>] [--private] [--json] [--registry <url>]'
593
+ 'Usage: knolo publish <pack.knolo> --slug <slug> --version <version> --license <SPDX> [--publisher <handle>] [--readme <text>] [--sources <text>] [--intended-use <text>] [--category <id>] [--private] [--json] [--registry <url>]'
584
594
  );
585
595
  }
586
596
  if (!/^[a-z0-9-]+$/.test(flags.slug))
@@ -594,6 +604,9 @@ export function parsePublishArgs(args) {
594
604
  throw new Error(
595
605
  'Publish publisher must contain lowercase letters, numbers, and hyphens.'
596
606
  );
607
+ if (flags.categories) {
608
+ flags.categories = normalizeCategories(flags.categories, { min: 1, max: 3 });
609
+ }
597
610
  return { packPath: positional[0], flags };
598
611
  }
599
612
 
package/bin/skill.mjs CHANGED
@@ -22,6 +22,7 @@ import {
22
22
  import { homedir, tmpdir } from 'node:os';
23
23
  import path from 'node:path';
24
24
  import { fileURLToPath, pathToFileURL } from 'node:url';
25
+ import { normalizeCategories } from './registry/categories.mjs';
25
26
  import {
26
27
  normalizeRegistryUrl,
27
28
  registryApiUrl,
@@ -44,7 +45,7 @@ const USAGE = `Usage: knolo skill <init|check|pack|publish|install|search|info|l
44
45
  knolo skill init <name> [--dir <parent>]
45
46
  knolo skill check [<dir>] [--query <text>] [--json]
46
47
  knolo skill pack [<dir>] [--out <dir>] [--json]
47
- knolo skill publish <pack> [--registry <url>] [--json]
48
+ knolo skill publish <pack> [--category <id>] [--registry <url>] [--json]
48
49
  knolo skill publish <pack> --hub <dir> [--json]
49
50
  knolo skill install <publisher>/<name> [--dir <path>] [--registry <url>] [--json]
50
51
  knolo skill install <name> --hub <dir> [--dir <path>] [--json]
@@ -216,6 +217,14 @@ async function packSkill(dirArg, flags) {
216
217
 
217
218
  async function publishSkill(packArg, flags) {
218
219
  if (!packArg) throw new Error('SKILL_HUB: pass the pack directory.');
220
+ const categories = flags.category
221
+ ? normalizeCategories(flags.category, { min: 1, max: 3 })
222
+ : null;
223
+ if (!flags.hub && !categories) {
224
+ throw new Error(
225
+ 'Pass --category at least once. Choose 1 to 3 of coding, math, science, news, business, security, writing, general.'
226
+ );
227
+ }
219
228
  if (flags.hub) {
220
229
  if (flags.registry) {
221
230
  throw new Error(
@@ -228,7 +237,7 @@ async function publishSkill(packArg, flags) {
228
237
  const registry = resolveSkillRegistry(flags.registry, credentials.registry);
229
238
  const summary = await publishSkillToRegistry(
230
239
  path.resolve(process.cwd(), packArg),
231
- { registry, token: credentials.token }
240
+ { registry, token: credentials.token, categories }
232
241
  );
233
242
  if (flags.json) console.log(JSON.stringify(summary));
234
243
  else if (summary.unchanged) console.log(`unchanged ${summary.name}`);
@@ -982,8 +991,14 @@ export function decodeSkillArchive(bytes) {
982
991
 
983
992
  export async function publishSkillToRegistry(
984
993
  packDir,
985
- { fetchImpl = globalThis.fetch, registry, token }
994
+ { fetchImpl = globalThis.fetch, registry, token, categories }
986
995
  ) {
996
+ const shelf = normalizeCategories(categories, { min: 1, max: 3 });
997
+ if (!shelf) {
998
+ throw new Error(
999
+ 'Pass --category at least once. Choose 1 to 3 of coding, math, science, news, business, security, writing, general.'
1000
+ );
1001
+ }
987
1002
  const pack = await readVerifiedPack(packDir);
988
1003
  const archive = encodeSkillArchive(pack);
989
1004
  const archiveSha256 = sha256(archive);
@@ -1016,7 +1031,7 @@ export async function publishSkillToRegistry(
1016
1031
  try {
1017
1032
  listed = await postJson(
1018
1033
  registryApiUrl(registry, ['skills']),
1019
- { archiveSha256, url: blobUrl, sizeBytes: archive.length },
1034
+ { archiveSha256, url: blobUrl, sizeBytes: archive.length, categories: shelf },
1020
1035
  { fetchImpl, headers: auth }
1021
1036
  );
1022
1037
  } catch (error) {
@@ -1360,7 +1375,15 @@ function parseArgs(argv) {
1360
1375
  const arg = argv[index];
1361
1376
  if (arg === '--json') flags.json = true;
1362
1377
  else if (arg === '--help' || arg === '-h') flags.help = true;
1363
- else if (arg.startsWith('--')) {
1378
+ else if (arg === '--category') {
1379
+ const value = argv[index + 1];
1380
+ if (value === undefined || value.startsWith('--')) {
1381
+ throw new Error('Missing value for --category');
1382
+ }
1383
+ const current = Array.isArray(flags.category) ? flags.category : [];
1384
+ flags.category = [...current, value];
1385
+ index += 1;
1386
+ } else if (arg.startsWith('--')) {
1364
1387
  const key = arg.slice(2);
1365
1388
  const value = argv[index + 1];
1366
1389
  if (value === undefined || value.startsWith('--')) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@knolo/cli",
3
- "version": "6.2.8",
3
+ "version": "6.2.9",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "knolo": "bin/knolo.mjs"
@@ -28,7 +28,7 @@
28
28
  },
29
29
  "scripts": {
30
30
  "build": "node -e \"console.log('cli is executable via bin/knolo.mjs')\"",
31
- "test": "npm run build --prefix ../core && npm run build --prefix ../exchange && node --test test/cli.test.mjs test/kar.test.mjs test/kar-graph.test.mjs test/kar-produce.test.mjs test/hub.integration.test.mjs test/compose.test.mjs test/cortex.test.mjs test/flight.test.mjs test/skill.test.mjs test/setup.test.mjs test/exchange.test.mjs test/research.test.mjs test/kite.test.mjs",
31
+ "test": "npm run build --prefix ../core && npm run build --prefix ../exchange && node --test test/cli.test.mjs test/ask.test.mjs test/kar.test.mjs test/kar-graph.test.mjs test/kar-produce.test.mjs test/hub.integration.test.mjs test/compose.test.mjs test/cortex.test.mjs test/flight.test.mjs test/skill.test.mjs test/setup.test.mjs test/exchange.test.mjs test/research.test.mjs test/kite.test.mjs",
32
32
  "test:hub": "node --test test/hub.integration.test.mjs"
33
33
  },
34
34
  "dependencies": {