@agent-nexus/csreg 0.1.5 → 0.1.7

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,725 @@
1
+ // src/commands/push.ts
2
+ import { Command as Command2 } from "commander";
3
+ import { resolve as resolve3, join as join6, basename as basename3 } from "path";
4
+ import { existsSync as existsSync5, readFileSync as readFileSync3, statSync as statSync3, readdirSync as readdirSync3, lstatSync as lstatSync2 } from "fs";
5
+ import { createHash as createHash2 } from "crypto";
6
+
7
+ // src/commands/validate.ts
8
+ import { Command } from "commander";
9
+ import { resolve as resolve2, join as join3, basename } from "path";
10
+ import { existsSync as existsSync3, statSync, readdirSync as readdirSync2, lstatSync } from "fs";
11
+
12
+ // src/lib/manifest.ts
13
+ import { readFileSync, existsSync } from "fs";
14
+ import { join } from "path";
15
+ import { parse as parseYaml } from "yaml";
16
+
17
+ // src/lib/errors.ts
18
+ import chalk from "chalk";
19
+ var CliError = class extends Error {
20
+ suggestions;
21
+ constructor(message, suggestions = []) {
22
+ super(message);
23
+ this.name = "CliError";
24
+ this.suggestions = suggestions;
25
+ }
26
+ };
27
+ function handleError(err) {
28
+ if (err instanceof CliError) {
29
+ console.error(chalk.red("Error:") + " " + err.message);
30
+ if (err.suggestions.length > 0) {
31
+ console.error("");
32
+ console.error(chalk.yellow("Suggestions:"));
33
+ for (const suggestion of err.suggestions) {
34
+ console.error(" " + chalk.dim("-") + " " + suggestion);
35
+ }
36
+ }
37
+ } else if (err instanceof Error) {
38
+ console.error(chalk.red("Error:") + " " + err.message);
39
+ } else {
40
+ console.error(chalk.red("Error:") + " " + String(err));
41
+ }
42
+ process.exit(1);
43
+ }
44
+
45
+ // src/lib/manifest.ts
46
+ var SKILL_FILE = "SKILL.md";
47
+ function parseManifest(dir) {
48
+ const skillPath = join(dir, SKILL_FILE);
49
+ if (!existsSync(skillPath)) {
50
+ throw new CliError(`No ${SKILL_FILE} found in ${dir}`, [
51
+ "Run `csreg init` to create a new skill.",
52
+ "A valid skill requires a SKILL.md file with YAML frontmatter."
53
+ ]);
54
+ }
55
+ const raw = readFileSync(skillPath, "utf-8");
56
+ const frontmatterMatch = raw.match(/^---\s*\n([\s\S]*?)\n---\s*\n?([\s\S]*)$/);
57
+ if (!frontmatterMatch) {
58
+ throw new CliError(`${SKILL_FILE} is missing YAML frontmatter.`, [
59
+ "SKILL.md must start with --- delimited YAML frontmatter.",
60
+ "Example:\n ---\n name: my-skill\n description: Does something\n ---\n \n Your instructions here."
61
+ ]);
62
+ }
63
+ const [, frontmatterRaw, body] = frontmatterMatch;
64
+ let parsed;
65
+ try {
66
+ parsed = parseYaml(frontmatterRaw);
67
+ } catch (err) {
68
+ throw new CliError(`Failed to parse ${SKILL_FILE} frontmatter: ${String(err)}`, [
69
+ "Check that the YAML between --- delimiters is valid."
70
+ ]);
71
+ }
72
+ if (!parsed || typeof parsed !== "object") {
73
+ throw new CliError(`${SKILL_FILE} frontmatter is empty or not an object.`, [
74
+ 'Add at least a "name" and "description" field.'
75
+ ]);
76
+ }
77
+ return { ...parsed, _body: body.trim() };
78
+ }
79
+ function validateManifest(manifest) {
80
+ const errors = [];
81
+ if (!manifest.name || typeof manifest.name !== "string") {
82
+ errors.push('Missing or invalid "name" field in frontmatter.');
83
+ } else {
84
+ if (manifest.name.length > 64) {
85
+ errors.push('"name" must be at most 64 characters.');
86
+ }
87
+ if (!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(manifest.name)) {
88
+ errors.push('"name" must be lowercase alphanumeric with hyphens, not starting or ending with a hyphen.');
89
+ }
90
+ if (manifest.name.includes("--")) {
91
+ errors.push('"name" must not contain consecutive hyphens (--).');
92
+ }
93
+ }
94
+ if (!manifest.description || typeof manifest.description !== "string") {
95
+ errors.push('Missing "description" field. Claude uses this to decide when to invoke the skill.');
96
+ } else if (manifest.description.length > 1024) {
97
+ errors.push('"description" must be at most 1024 characters.');
98
+ }
99
+ if (manifest.version !== void 0) {
100
+ const semverRegex = /^\d+\.\d+\.\d+(-[a-zA-Z0-9.]+)?(\+[a-zA-Z0-9.]+)?$/;
101
+ if (!semverRegex.test(manifest.version)) {
102
+ errors.push('"version" must be valid semver (e.g., 1.0.0).');
103
+ }
104
+ }
105
+ if (manifest.scope !== void 0 && typeof manifest.scope === "string") {
106
+ if (!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(manifest.scope)) {
107
+ errors.push('"scope" must be lowercase alphanumeric with hyphens.');
108
+ }
109
+ }
110
+ if (manifest["allowed-tools"] !== void 0 && typeof manifest["allowed-tools"] !== "string") {
111
+ errors.push('"allowed-tools" must be a string (space-delimited list of tools).');
112
+ }
113
+ if (manifest["disable-model-invocation"] !== void 0 && typeof manifest["disable-model-invocation"] !== "boolean") {
114
+ errors.push('"disable-model-invocation" must be a boolean.');
115
+ }
116
+ if (manifest["user-invocable"] !== void 0 && typeof manifest["user-invocable"] !== "boolean") {
117
+ errors.push('"user-invocable" must be a boolean.');
118
+ }
119
+ return errors;
120
+ }
121
+
122
+ // src/lib/discovery.ts
123
+ import { resolve, join as join2, dirname } from "path";
124
+ import { existsSync as existsSync2, readdirSync } from "fs";
125
+ function findClaudeSkillsDir() {
126
+ let dir = resolve(".");
127
+ const parts = dir.split("/");
128
+ const claudeIdx = parts.lastIndexOf(".claude");
129
+ if (claudeIdx >= 0) {
130
+ const claudeRoot = parts.slice(0, claudeIdx + 1).join("/");
131
+ return join2(claudeRoot, "skills");
132
+ }
133
+ while (dir !== dirname(dir)) {
134
+ const claudeDir = join2(dir, ".claude");
135
+ if (existsSync2(claudeDir)) {
136
+ return join2(claudeDir, "skills");
137
+ }
138
+ dir = dirname(dir);
139
+ }
140
+ return null;
141
+ }
142
+ function discoverSkillDirs(parentDir) {
143
+ if (!existsSync2(parentDir)) return [];
144
+ const dirs = [];
145
+ const entries = readdirSync(parentDir, { withFileTypes: true });
146
+ for (const entry of entries) {
147
+ if (!entry.isDirectory()) continue;
148
+ if (entry.name.startsWith(".")) continue;
149
+ const skillMd = join2(parentDir, entry.name, "SKILL.md");
150
+ if (existsSync2(skillMd)) {
151
+ dirs.push(join2(parentDir, entry.name));
152
+ }
153
+ }
154
+ return dirs.sort();
155
+ }
156
+
157
+ // src/lib/output.ts
158
+ import chalk2 from "chalk";
159
+ import ora from "ora";
160
+ import Table from "cli-table3";
161
+ function formatTable(headers, rows) {
162
+ const table = new Table({
163
+ head: headers.map((h) => chalk2.bold.cyan(h)),
164
+ style: { head: [], border: [] }
165
+ });
166
+ for (const row of rows) {
167
+ table.push(row);
168
+ }
169
+ return table.toString();
170
+ }
171
+ function spinner(text) {
172
+ return ora({ text, color: "cyan" }).start();
173
+ }
174
+ function success(msg) {
175
+ console.log(chalk2.green("\u2713") + " " + msg);
176
+ }
177
+ function error(msg) {
178
+ console.error(chalk2.red("\u2717") + " " + msg);
179
+ }
180
+ function warn(msg) {
181
+ console.log(chalk2.yellow("!") + " " + msg);
182
+ }
183
+ function info(msg) {
184
+ console.log(chalk2.blue("i") + " " + msg);
185
+ }
186
+
187
+ // src/commands/validate.ts
188
+ var MAX_FILE_COUNT = 100;
189
+ var MAX_FILE_SIZE = 500 * 1024;
190
+ var MAX_TOTAL_SIZE = 2 * 1024 * 1024;
191
+ function collectFiles(dir, prefix = "") {
192
+ const files = [];
193
+ const entries = readdirSync2(dir, { withFileTypes: true });
194
+ for (const entry of entries) {
195
+ if (entry.name === "node_modules" || entry.name === ".git") continue;
196
+ const fullPath = join3(dir, entry.name);
197
+ const lstat = lstatSync(fullPath);
198
+ if (lstat.isSymbolicLink()) continue;
199
+ const relativePath = prefix ? `${prefix}/${entry.name}` : entry.name;
200
+ if (entry.isDirectory()) {
201
+ files.push(...collectFiles(fullPath, relativePath));
202
+ } else {
203
+ const stat = statSync(fullPath);
204
+ files.push({ path: relativePath, size: stat.size });
205
+ }
206
+ }
207
+ return files;
208
+ }
209
+ function runValidation(dir) {
210
+ const errors = [];
211
+ const warnings = [];
212
+ if (!existsSync3(join3(dir, "SKILL.md"))) {
213
+ errors.push("Missing SKILL.md \u2014 every skill must have a SKILL.md file with YAML frontmatter.");
214
+ return { valid: false, errors, warnings };
215
+ }
216
+ const manifest = parseManifest(dir);
217
+ const manifestErrors = validateManifest(manifest);
218
+ errors.push(...manifestErrors);
219
+ if (!manifest._body) {
220
+ warnings.push("SKILL.md has no instructions body after the frontmatter. Add skill instructions below the --- delimiter.");
221
+ }
222
+ if (!manifest.version) {
223
+ warnings.push('No "version" in frontmatter. Required for publishing to the registry (e.g., version: "1.0.0").');
224
+ }
225
+ if (!manifest.scope) {
226
+ warnings.push('No "scope" in frontmatter. Required for publishing to the registry (e.g., scope: my-team).');
227
+ }
228
+ const dirName = dir.split("/").pop();
229
+ if (manifest.name && dirName && dirName !== manifest.name) {
230
+ warnings.push(`Directory name "${dirName}" doesn't match skill name "${manifest.name}". They should match per the Agent Skills spec.`);
231
+ }
232
+ const files = collectFiles(dir);
233
+ if (files.length > MAX_FILE_COUNT) {
234
+ errors.push(`Too many files: ${files.length} (max ${MAX_FILE_COUNT}).`);
235
+ }
236
+ let totalSize = 0;
237
+ for (const file of files) {
238
+ totalSize += file.size;
239
+ if (file.size > MAX_FILE_SIZE) {
240
+ errors.push(`File too large: ${file.path} (${(file.size / 1024).toFixed(1)}KB, max 500KB).`);
241
+ }
242
+ }
243
+ if (totalSize > MAX_TOTAL_SIZE) {
244
+ errors.push(`Total size too large: ${(totalSize / 1024 / 1024).toFixed(2)}MB (max 2MB).`);
245
+ }
246
+ return { valid: errors.length === 0, errors, warnings };
247
+ }
248
+ var validateCommand = new Command("validate").description("Validate a skill package").argument("[dir]", "Skill directory", ".").option("--all", "Validate all skills in .claude/skills/").action(async (dir, opts) => {
249
+ try {
250
+ if (opts.all) {
251
+ const skillsDir = findClaudeSkillsDir();
252
+ if (!skillsDir) {
253
+ throw new CliError("Cannot find .claude/skills/ directory.", [
254
+ "Run this from a project with a .claude/ directory."
255
+ ]);
256
+ }
257
+ const skillDirs = discoverSkillDirs(skillsDir);
258
+ if (skillDirs.length === 0) {
259
+ throw new CliError(`No skills found in ${skillsDir}/`, [
260
+ "Skills must be directories containing a SKILL.md file."
261
+ ]);
262
+ }
263
+ console.log(`Validating ${skillDirs.length} skill(s) in ${skillsDir}/
264
+ `);
265
+ let passed = 0;
266
+ let failed = 0;
267
+ for (const skillDir of skillDirs) {
268
+ const name = basename(skillDir);
269
+ const result2 = runValidation(skillDir);
270
+ if (result2.valid) {
271
+ success(`${name}`);
272
+ passed++;
273
+ } else {
274
+ error(`${name}`);
275
+ for (const e of result2.errors) {
276
+ console.error(` ${e}`);
277
+ }
278
+ failed++;
279
+ }
280
+ for (const w of result2.warnings) {
281
+ warn(` ${name}: ${w}`);
282
+ }
283
+ }
284
+ console.log("");
285
+ if (failed === 0) {
286
+ success(`All ${passed} skill(s) are valid.`);
287
+ } else {
288
+ throw new CliError(`${failed}/${passed + failed} skill(s) failed validation.`);
289
+ }
290
+ return;
291
+ }
292
+ const resolved = resolve2(dir);
293
+ if (!existsSync3(resolved)) {
294
+ throw new CliError(`Directory not found: ${resolved}`);
295
+ }
296
+ const result = runValidation(resolved);
297
+ for (const w of result.warnings) {
298
+ warn(w);
299
+ }
300
+ if (result.valid) {
301
+ success("Skill is valid.");
302
+ } else {
303
+ for (const e of result.errors) {
304
+ error(e);
305
+ }
306
+ throw new CliError("Validation failed.", [
307
+ "Fix the errors above and try again."
308
+ ]);
309
+ }
310
+ } catch (err) {
311
+ handleError(err);
312
+ }
313
+ });
314
+
315
+ // src/lib/archive.ts
316
+ import { statSync as statSync2 } from "fs";
317
+ import { readFile } from "fs/promises";
318
+ import { createHash } from "crypto";
319
+ import { join as join4, basename as basename2 } from "path";
320
+ import { create as tarCreate, extract as tarExtract } from "tar";
321
+ var MAX_ARCHIVE_SIZE = 10 * 1024 * 1024;
322
+ async function computeSha256(filePath) {
323
+ const data = await readFile(filePath);
324
+ return createHash("sha256").update(data).digest("hex");
325
+ }
326
+ async function pack(dir, outputPath) {
327
+ const dirName = basename2(dir);
328
+ const archivePath = outputPath ?? join4(dir, "..", `${dirName}.tar.gz`);
329
+ await tarCreate(
330
+ {
331
+ gzip: true,
332
+ file: archivePath,
333
+ cwd: join4(dir, "..")
334
+ },
335
+ [dirName]
336
+ );
337
+ const sha256 = await computeSha256(archivePath);
338
+ const stat = statSync2(archivePath);
339
+ if (stat.size > MAX_ARCHIVE_SIZE) {
340
+ throw new CliError(
341
+ `Archive size ${(stat.size / 1024 / 1024).toFixed(1)}MB exceeds the 10MB limit.`,
342
+ ["Remove unnecessary files or assets to reduce the package size."]
343
+ );
344
+ }
345
+ return {
346
+ path: archivePath,
347
+ sha256,
348
+ size: stat.size
349
+ };
350
+ }
351
+ async function extract(archivePath, outputDir, expectedSha256) {
352
+ const actualSha256 = await computeSha256(archivePath);
353
+ if (actualSha256 !== expectedSha256) {
354
+ throw new CliError(
355
+ `SHA-256 mismatch: expected ${expectedSha256}, got ${actualSha256}`,
356
+ ["The archive may be corrupted or tampered with.", "Try downloading again."]
357
+ );
358
+ }
359
+ await tarExtract({
360
+ file: archivePath,
361
+ cwd: outputDir,
362
+ filter: (path) => !path.includes("..")
363
+ });
364
+ }
365
+
366
+ // src/config.ts
367
+ import { readFileSync as readFileSync2, writeFileSync, mkdirSync, existsSync as existsSync4 } from "fs";
368
+ import { join as join5 } from "path";
369
+ import { homedir } from "os";
370
+ var CONFIG_DIR = join5(homedir(), ".config", "csreg");
371
+ var CONFIG_PATH = join5(CONFIG_DIR, "config.json");
372
+ function getConfig() {
373
+ if (!existsSync4(CONFIG_PATH)) {
374
+ return {};
375
+ }
376
+ try {
377
+ const raw = readFileSync2(CONFIG_PATH, "utf-8");
378
+ return JSON.parse(raw);
379
+ } catch {
380
+ return {};
381
+ }
382
+ }
383
+ function setConfig(updates) {
384
+ const current = getConfig();
385
+ const merged = { ...current, ...updates };
386
+ mkdirSync(CONFIG_DIR, { recursive: true, mode: 448 });
387
+ writeFileSync(CONFIG_PATH, JSON.stringify(merged, null, 2) + "\n", { encoding: "utf-8", mode: 384 });
388
+ }
389
+ function getApiUrl() {
390
+ return process.env.CSREG_API_URL ?? getConfig().apiUrl ?? "https://www.csreg.nexus";
391
+ }
392
+ function getAuthToken() {
393
+ return process.env.CSREG_TOKEN ?? getConfig().token;
394
+ }
395
+
396
+ // src/api-client.ts
397
+ var MAX_RETRIES = 3;
398
+ var BASE_DELAY_MS = 500;
399
+ var ApiClient = class {
400
+ baseUrl;
401
+ token;
402
+ constructor() {
403
+ this.baseUrl = getApiUrl();
404
+ this.token = getAuthToken();
405
+ }
406
+ buildUrl(path, query) {
407
+ const url = new URL(path, this.baseUrl);
408
+ if (query) {
409
+ for (const [key, value] of Object.entries(query)) {
410
+ url.searchParams.set(key, value);
411
+ }
412
+ }
413
+ return url.toString();
414
+ }
415
+ buildHeaders(extra) {
416
+ const headers = {
417
+ "Content-Type": "application/json",
418
+ "Accept": "application/json",
419
+ ...extra
420
+ };
421
+ if (this.token) {
422
+ headers["Authorization"] = `Bearer ${this.token}`;
423
+ }
424
+ return headers;
425
+ }
426
+ async handleResponse(response) {
427
+ if (response.ok) {
428
+ if (response.status === 204) {
429
+ return void 0;
430
+ }
431
+ return response.json();
432
+ }
433
+ let errorBody;
434
+ try {
435
+ errorBody = await response.json();
436
+ } catch {
437
+ }
438
+ const detail = errorBody?.detail ?? response.statusText;
439
+ const title = errorBody?.title ?? `HTTP ${response.status}`;
440
+ const suggestions = [];
441
+ if (response.status === 401) {
442
+ suggestions.push("Run `csreg login` to authenticate.");
443
+ } else if (response.status === 403) {
444
+ suggestions.push("You may not have permission for this action.");
445
+ } else if (response.status === 404) {
446
+ suggestions.push("Check that the skill name and scope are correct.");
447
+ }
448
+ throw new CliError(`${title}: ${detail}`, suggestions);
449
+ }
450
+ async requestWithRetry(method, path, opts) {
451
+ const url = this.buildUrl(path, opts?.query);
452
+ const headers = this.buildHeaders(opts?.headers);
453
+ let lastError;
454
+ for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
455
+ try {
456
+ const response = await fetch(url, {
457
+ method,
458
+ headers,
459
+ body: opts?.body !== void 0 ? JSON.stringify(opts.body) : void 0
460
+ });
461
+ if (response.status >= 500 && attempt < MAX_RETRIES - 1) {
462
+ const delay = BASE_DELAY_MS * Math.pow(2, attempt);
463
+ await new Promise((resolve4) => setTimeout(resolve4, delay));
464
+ continue;
465
+ }
466
+ return await this.handleResponse(response);
467
+ } catch (error2) {
468
+ lastError = error2;
469
+ if (error2 instanceof CliError) {
470
+ throw error2;
471
+ }
472
+ if (attempt < MAX_RETRIES - 1) {
473
+ const delay = BASE_DELAY_MS * Math.pow(2, attempt);
474
+ await new Promise((resolve4) => setTimeout(resolve4, delay));
475
+ continue;
476
+ }
477
+ }
478
+ }
479
+ throw lastError instanceof CliError ? lastError : new CliError(`Request failed: ${String(lastError)}`, [
480
+ "Check your internet connection.",
481
+ "The API server may be unavailable."
482
+ ]);
483
+ }
484
+ async get(path, opts) {
485
+ return this.requestWithRetry("GET", path, opts);
486
+ }
487
+ async post(path, opts) {
488
+ return this.requestWithRetry("POST", path, opts);
489
+ }
490
+ async put(path, opts) {
491
+ return this.requestWithRetry("PUT", path, opts);
492
+ }
493
+ async patch(path, opts) {
494
+ return this.requestWithRetry("PATCH", path, opts);
495
+ }
496
+ async delete(path, opts) {
497
+ return this.requestWithRetry("DELETE", path, opts);
498
+ }
499
+ };
500
+
501
+ // src/commands/push.ts
502
+ function collectFileTree(dir, prefix = "") {
503
+ const files = [];
504
+ const entries = readdirSync3(dir, { withFileTypes: true });
505
+ for (const entry of entries) {
506
+ if (entry.name === "node_modules" || entry.name === ".git") continue;
507
+ const fullPath = join6(dir, entry.name);
508
+ const lstat = lstatSync2(fullPath);
509
+ if (lstat.isSymbolicLink()) continue;
510
+ const relativePath = prefix ? `${prefix}/${entry.name}` : entry.name;
511
+ if (entry.isDirectory()) {
512
+ files.push(...collectFileTree(fullPath, relativePath));
513
+ } else {
514
+ const stat = statSync3(fullPath);
515
+ const content = readFileSync3(fullPath);
516
+ const sha256 = createHash2("sha256").update(content).digest("hex");
517
+ files.push({ path: relativePath, size: stat.size, sha256 });
518
+ }
519
+ }
520
+ return files;
521
+ }
522
+ async function pushSingle(resolved) {
523
+ const spin = spinner("Validating skill...");
524
+ const validation = runValidation(resolved);
525
+ if (!validation.valid) {
526
+ spin.fail("Validation failed.");
527
+ for (const e of validation.errors) {
528
+ console.error(" " + e);
529
+ }
530
+ throw new CliError("Fix validation errors before pushing.");
531
+ }
532
+ spin.succeed("Validation passed.");
533
+ const manifest = parseManifest(resolved);
534
+ if (!manifest.version) {
535
+ throw new CliError('Missing "version" in SKILL.md frontmatter.', [
536
+ 'Add a version field: version: "1.0.0"'
537
+ ]);
538
+ }
539
+ if (!manifest.scope) {
540
+ throw new CliError('Missing "scope" in SKILL.md frontmatter.', [
541
+ "Add a scope field: scope: my-team"
542
+ ]);
543
+ }
544
+ spin.start("Packing skill...");
545
+ const archive = await pack(resolved);
546
+ spin.succeed(`Packed (${(archive.size / 1024).toFixed(1)}KB).`);
547
+ const client = new ApiClient();
548
+ spin.start("Checking registry...");
549
+ try {
550
+ await client.get(`/api/v1/skills/${manifest.scope}/${manifest.name}`);
551
+ spin.succeed("Skill found in registry.");
552
+ } catch {
553
+ spin.start(`Creating skill ${manifest.scope}/${manifest.name}...`);
554
+ await client.post("/api/v1/skills", {
555
+ body: {
556
+ scope: manifest.scope,
557
+ slug: manifest.name,
558
+ displayName: manifest.name,
559
+ description: manifest.description || "",
560
+ tags: manifest.tags || []
561
+ }
562
+ });
563
+ spin.succeed(`Created skill ${manifest.scope}/${manifest.name}.`);
564
+ }
565
+ spin.start("Preparing version...");
566
+ const fileTree = collectFileTree(resolved);
567
+ const prepared = await client.post(
568
+ `/api/v1/skills/${manifest.scope}/${manifest.name}/versions`,
569
+ {
570
+ body: {
571
+ version: manifest.version,
572
+ fileTree,
573
+ archiveSha256: archive.sha256,
574
+ archiveSize: archive.size,
575
+ entryPoint: "SKILL.md",
576
+ manifestJson: {
577
+ name: manifest.name,
578
+ description: manifest.description,
579
+ version: manifest.version,
580
+ scope: manifest.scope,
581
+ "allowed-tools": manifest["allowed-tools"],
582
+ "argument-hint": manifest["argument-hint"],
583
+ "disable-model-invocation": manifest["disable-model-invocation"],
584
+ "user-invocable": manifest["user-invocable"],
585
+ tags: manifest.tags
586
+ }
587
+ }
588
+ }
589
+ );
590
+ spin.succeed("Version prepared.");
591
+ spin.start("Uploading archive...");
592
+ const archiveData = readFileSync3(archive.path);
593
+ const uploadHeaders = {
594
+ "Content-Type": "application/gzip",
595
+ "Content-Length": String(archive.size)
596
+ };
597
+ let uploadResponse = await fetch(prepared.uploadUrl, {
598
+ method: "PUT",
599
+ headers: uploadHeaders,
600
+ body: archiveData,
601
+ redirect: "manual"
602
+ });
603
+ if (uploadResponse.status === 301 || uploadResponse.status === 302 || uploadResponse.status === 307 || uploadResponse.status === 308) {
604
+ let redirectUrl = uploadResponse.headers.get("location");
605
+ if (!redirectUrl) {
606
+ const body = await uploadResponse.text();
607
+ const endpointMatch = body.match(/<Endpoint>([^<]+)<\/Endpoint>/);
608
+ if (endpointMatch) {
609
+ const url = new URL(prepared.uploadUrl);
610
+ url.hostname = endpointMatch[1];
611
+ redirectUrl = url.toString();
612
+ }
613
+ }
614
+ if (!redirectUrl) {
615
+ spin.fail("Upload failed.");
616
+ throw new CliError("S3 returned a redirect but no usable endpoint.", [
617
+ "This may be a region mismatch. Contact support."
618
+ ]);
619
+ }
620
+ uploadResponse = await fetch(redirectUrl, {
621
+ method: "PUT",
622
+ headers: uploadHeaders,
623
+ body: archiveData
624
+ });
625
+ }
626
+ if (!uploadResponse.ok) {
627
+ spin.fail("Upload failed.");
628
+ throw new CliError(`Upload failed with status ${uploadResponse.status}.`, [
629
+ "Try again. If the problem persists, contact support."
630
+ ]);
631
+ }
632
+ spin.succeed("Archive uploaded.");
633
+ spin.start("Finalizing version...");
634
+ await client.post(
635
+ `/api/v1/skills/${manifest.scope}/${manifest.name}/versions/${manifest.version}/finalize`,
636
+ {
637
+ body: { status: "published" }
638
+ }
639
+ );
640
+ spin.succeed("Version finalized.");
641
+ return `${manifest.scope}/${manifest.name}@${manifest.version}`;
642
+ }
643
+ var pushCommand = new Command2("push").description("Publish a skill to the registry").argument("[dir]", "Skill directory", ".").option("--all", "Push all skills in .claude/skills/").action(async (dir, opts) => {
644
+ try {
645
+ if (!getAuthToken()) {
646
+ throw new CliError("Not logged in.", ["Run `csreg login` to authenticate."]);
647
+ }
648
+ if (opts.all) {
649
+ const skillsDir = findClaudeSkillsDir();
650
+ if (!skillsDir) {
651
+ throw new CliError("Cannot find .claude/skills/ directory.", [
652
+ "Run this from a project with a .claude/ directory."
653
+ ]);
654
+ }
655
+ const skillDirs = discoverSkillDirs(skillsDir);
656
+ if (skillDirs.length === 0) {
657
+ throw new CliError(`No skills found in ${skillsDir}/`, [
658
+ "Skills must be directories containing a SKILL.md file."
659
+ ]);
660
+ }
661
+ console.log(`Pushing ${skillDirs.length} skill(s) from ${skillsDir}/
662
+ `);
663
+ let published = 0;
664
+ let failed = 0;
665
+ for (const skillDir of skillDirs) {
666
+ const name = basename3(skillDir);
667
+ console.log(`
668
+ --- ${name} ---
669
+ `);
670
+ try {
671
+ const ref2 = await pushSingle(skillDir);
672
+ success(`Published ${ref2}`);
673
+ published++;
674
+ } catch (err) {
675
+ const msg = err instanceof Error ? err.message : String(err);
676
+ warn(`Failed to push ${name}: ${msg}`);
677
+ failed++;
678
+ }
679
+ }
680
+ console.log(`
681
+ ${"\u2500".repeat(40)}
682
+ `);
683
+ if (failed === 0) {
684
+ success(`All ${published} skill(s) published.`);
685
+ } else {
686
+ success(`Published ${published}/${published + failed} skill(s).`);
687
+ if (failed > 0) {
688
+ warn(`${failed} skill(s) failed. Check the errors above.`);
689
+ }
690
+ }
691
+ return;
692
+ }
693
+ const resolved = resolve3(dir);
694
+ if (!existsSync5(resolved)) {
695
+ throw new CliError(`Directory not found: ${resolved}`);
696
+ }
697
+ const ref = await pushSingle(resolved);
698
+ console.log("");
699
+ success(`Published ${ref}`);
700
+ } catch (err) {
701
+ handleError(err);
702
+ }
703
+ });
704
+
705
+ export {
706
+ setConfig,
707
+ getApiUrl,
708
+ getAuthToken,
709
+ CliError,
710
+ handleError,
711
+ ApiClient,
712
+ formatTable,
713
+ spinner,
714
+ success,
715
+ warn,
716
+ info,
717
+ parseManifest,
718
+ findClaudeSkillsDir,
719
+ runValidation,
720
+ validateCommand,
721
+ MAX_ARCHIVE_SIZE,
722
+ pack,
723
+ extract,
724
+ pushCommand
725
+ };