skillverse 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/dist/bin.js +2257 -0
  2. package/dist/bin.js.map +1 -0
  3. package/dist/index.js +1907 -0
  4. package/dist/index.js.map +1 -0
  5. package/package.json +52 -26
  6. package/prisma/dev.db +0 -0
  7. package/.prettierrc +0 -10
  8. package/README.md +0 -369
  9. package/client/README.md +0 -73
  10. package/client/eslint.config.js +0 -23
  11. package/client/index.html +0 -13
  12. package/client/package.json +0 -41
  13. package/client/postcss.config.js +0 -6
  14. package/client/src/App.css +0 -42
  15. package/client/src/App.tsx +0 -26
  16. package/client/src/assets/react.svg +0 -1
  17. package/client/src/components/AddSkillDialog.tsx +0 -249
  18. package/client/src/components/Layout.tsx +0 -134
  19. package/client/src/components/LinkWorkspaceDialog.tsx +0 -196
  20. package/client/src/components/LoadingSpinner.tsx +0 -57
  21. package/client/src/components/SkillCard.tsx +0 -269
  22. package/client/src/components/Toast.tsx +0 -44
  23. package/client/src/components/Tooltip.tsx +0 -132
  24. package/client/src/index.css +0 -168
  25. package/client/src/lib/api.ts +0 -196
  26. package/client/src/main.tsx +0 -10
  27. package/client/src/pages/Dashboard.tsx +0 -209
  28. package/client/src/pages/Marketplace.tsx +0 -282
  29. package/client/src/pages/Settings.tsx +0 -136
  30. package/client/src/pages/SkillLibrary.tsx +0 -163
  31. package/client/src/pages/Workspaces.tsx +0 -662
  32. package/client/src/stores/appStore.ts +0 -222
  33. package/client/tailwind.config.js +0 -82
  34. package/client/tsconfig.app.json +0 -28
  35. package/client/tsconfig.json +0 -7
  36. package/client/tsconfig.node.json +0 -26
  37. package/client/vite.config.ts +0 -26
  38. package/registry/.env.example +0 -5
  39. package/registry/Dockerfile +0 -42
  40. package/registry/docker-compose.yml +0 -33
  41. package/registry/package.json +0 -37
  42. package/registry/prisma/schema.prisma +0 -59
  43. package/registry/src/index.ts +0 -34
  44. package/registry/src/lib/db.ts +0 -3
  45. package/registry/src/middleware/errorHandler.ts +0 -35
  46. package/registry/src/routes/auth.ts +0 -152
  47. package/registry/src/routes/skills.ts +0 -295
  48. package/registry/tsconfig.json +0 -23
  49. package/server/.env.example +0 -11
  50. package/server/package.json +0 -60
  51. package/server/public/vite.svg +0 -1
  52. package/server/src/bin.ts +0 -428
  53. package/server/src/config.ts +0 -39
  54. package/server/src/index.ts +0 -112
  55. package/server/src/lib/db.ts +0 -14
  56. package/server/src/middleware/errorHandler.ts +0 -40
  57. package/server/src/middleware/logger.ts +0 -12
  58. package/server/src/routes/dashboard.ts +0 -102
  59. package/server/src/routes/marketplace.ts +0 -273
  60. package/server/src/routes/skills.ts +0 -294
  61. package/server/src/routes/workspaces.ts +0 -168
  62. package/server/src/services/bundleService.ts +0 -123
  63. package/server/src/services/skillService.ts +0 -722
  64. package/server/src/services/workspaceService.ts +0 -521
  65. package/server/src/verify-sync.ts +0 -91
  66. package/server/tsconfig.json +0 -19
  67. package/server/tsup.config.ts +0 -18
  68. package/shared/package.json +0 -21
  69. package/shared/pnpm-lock.yaml +0 -24
  70. package/shared/src/index.ts +0 -169
  71. package/shared/tsconfig.json +0 -10
  72. package/tsconfig.json +0 -25
  73. /package/{server/prisma → prisma}/schema.prisma +0 -0
  74. /package/{server/public → public}/assets/index-BsYtpZSa.css +0 -0
  75. /package/{server/public → public}/assets/index-Dfr_6UV8.js +0 -0
  76. /package/{server/public → public}/index.html +0 -0
  77. /package/{client/public → public}/vite.svg +0 -0
package/dist/bin.js ADDED
@@ -0,0 +1,2257 @@
1
+ #!/usr/bin/env node
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __esm = (fn, res) => function __init() {
5
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
6
+ };
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+
12
+ // src/services/bundleService.ts
13
+ var bundleService_exports = {};
14
+ __export(bundleService_exports, {
15
+ bundleService: () => bundleService,
16
+ createBundle: () => createBundle,
17
+ deleteBundle: () => deleteBundle,
18
+ extractBundle: () => extractBundle,
19
+ getBundleSize: () => getBundleSize,
20
+ listBundles: () => listBundles
21
+ });
22
+ import { createWriteStream, existsSync as existsSync5, createReadStream } from "fs";
23
+ import { mkdir as mkdir4, rm as rm4, readdir, stat } from "fs/promises";
24
+ import { join as join5 } from "path";
25
+ import { pipeline } from "stream/promises";
26
+ import archiver from "archiver";
27
+ import { createGunzip } from "zlib";
28
+ import { extract } from "tar";
29
+ async function ensureBundlesDir() {
30
+ if (!existsSync5(BUNDLES_DIR)) {
31
+ await mkdir4(BUNDLES_DIR, { recursive: true });
32
+ }
33
+ }
34
+ async function createBundle(skillPath, skillName) {
35
+ await ensureBundlesDir();
36
+ const bundleName = `${skillName}-${Date.now()}.tar.gz`;
37
+ const bundlePath = join5(BUNDLES_DIR, bundleName);
38
+ return new Promise((resolve, reject) => {
39
+ const output = createWriteStream(bundlePath);
40
+ const archive = archiver("tar", {
41
+ gzip: true,
42
+ gzipOptions: { level: 9 }
43
+ });
44
+ output.on("close", () => {
45
+ console.log(`\u{1F4E6} Bundle created: ${bundlePath} (${archive.pointer()} bytes)`);
46
+ resolve(bundlePath);
47
+ });
48
+ archive.on("error", (err) => {
49
+ reject(err);
50
+ });
51
+ archive.pipe(output);
52
+ archive.directory(skillPath, false);
53
+ archive.finalize();
54
+ });
55
+ }
56
+ async function extractBundle(bundlePath, targetDir) {
57
+ if (!existsSync5(bundlePath)) {
58
+ throw new Error(`Bundle not found: ${bundlePath}`);
59
+ }
60
+ if (!existsSync5(targetDir)) {
61
+ await mkdir4(targetDir, { recursive: true });
62
+ }
63
+ await pipeline(
64
+ createReadStream(bundlePath),
65
+ createGunzip(),
66
+ extract({ cwd: targetDir })
67
+ );
68
+ console.log(`\u{1F4C2} Bundle extracted to: ${targetDir}`);
69
+ }
70
+ async function deleteBundle(bundlePath) {
71
+ if (existsSync5(bundlePath)) {
72
+ await rm4(bundlePath);
73
+ console.log(`\u{1F5D1}\uFE0F Bundle deleted: ${bundlePath}`);
74
+ }
75
+ }
76
+ async function getBundleSize(bundlePath) {
77
+ if (!existsSync5(bundlePath)) {
78
+ return 0;
79
+ }
80
+ const stats = await stat(bundlePath);
81
+ return stats.size;
82
+ }
83
+ async function listBundles() {
84
+ await ensureBundlesDir();
85
+ const files = await readdir(BUNDLES_DIR);
86
+ return files.filter((f) => f.endsWith(".tar.gz")).map((f) => join5(BUNDLES_DIR, f));
87
+ }
88
+ var BUNDLES_DIR, bundleService;
89
+ var init_bundleService = __esm({
90
+ "src/services/bundleService.ts"() {
91
+ "use strict";
92
+ BUNDLES_DIR = join5(
93
+ process.env.SKILLVERSE_HOME || join5(process.env.HOME || "", ".skillverse"),
94
+ "bundles"
95
+ );
96
+ bundleService = {
97
+ createBundle,
98
+ extractBundle,
99
+ deleteBundle,
100
+ getBundleSize,
101
+ listBundles,
102
+ BUNDLES_DIR
103
+ };
104
+ }
105
+ });
106
+
107
+ // src/index.ts
108
+ import express from "express";
109
+ import cors from "cors";
110
+ import dotenv2 from "dotenv";
111
+ import { fileURLToPath as fileURLToPath2 } from "url";
112
+ import { dirname as dirname2, join as join6 } from "path";
113
+ import { mkdir as mkdir5 } from "fs/promises";
114
+ import { existsSync as existsSync7 } from "fs";
115
+
116
+ // src/routes/skills.ts
117
+ import { Router } from "express";
118
+ import multer from "multer";
119
+ import { join as join4 } from "path";
120
+ import { existsSync as existsSync4 } from "fs";
121
+ import { mkdir as mkdir3, rm as rm3 } from "fs/promises";
122
+
123
+ // src/services/skillService.ts
124
+ import { join as join2, basename } from "path";
125
+ import { existsSync as existsSync2 } from "fs";
126
+ import { mkdir, rm, cp, readFile, unlink } from "fs/promises";
127
+ import matter from "gray-matter";
128
+ import simpleGit from "simple-git";
129
+ import AdmZip from "adm-zip";
130
+
131
+ // src/config.ts
132
+ import { join, dirname } from "path";
133
+ import { existsSync, mkdirSync } from "fs";
134
+ import { fileURLToPath } from "url";
135
+ import dotenv from "dotenv";
136
+ dotenv.config();
137
+ var __filename = fileURLToPath(import.meta.url);
138
+ var __dirname = dirname(__filename);
139
+ function setupEnvironment() {
140
+ const home = process.env.HOME || process.env.USERPROFILE || "";
141
+ const skillverseHome = process.env.SKILLVERSE_HOME || join(home, ".skillverse");
142
+ const dbUrl = process.env.DATABASE_URL;
143
+ if (!existsSync(skillverseHome)) {
144
+ try {
145
+ mkdirSync(skillverseHome, { recursive: true });
146
+ } catch (error) {
147
+ console.error("Failed to create .skillverse directory:", error);
148
+ }
149
+ }
150
+ if (!dbUrl) {
151
+ const dbPath = join(skillverseHome, "skillverse.db");
152
+ process.env.DATABASE_URL = `file:${dbPath}`;
153
+ }
154
+ return {
155
+ skillverseHome,
156
+ databaseUrl: process.env.DATABASE_URL
157
+ };
158
+ }
159
+ var config = setupEnvironment();
160
+
161
+ // src/lib/db.ts
162
+ import { PrismaClient } from "@prisma/client";
163
+ var globalForPrisma = globalThis;
164
+ var prisma = globalForPrisma.prisma ?? new PrismaClient({
165
+ log: process.env.NODE_ENV === "development" ? ["error", "warn"] : ["error"]
166
+ });
167
+ if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;
168
+
169
+ // ../shared/dist/index.js
170
+ var WORKSPACE_SKILLS_PATHS = {
171
+ vscode: {
172
+ project: ".github/skills",
173
+ global: "~/.copilot/skills"
174
+ },
175
+ cursor: {
176
+ project: ".cursor/skills",
177
+ global: "~/.cursor/skills"
178
+ },
179
+ "claude-desktop": {
180
+ project: ".claude/skills",
181
+ global: "~/.claude/skills"
182
+ },
183
+ codex: {
184
+ project: ".codex/skills",
185
+ global: "~/.codex/skills"
186
+ },
187
+ antigravity: {
188
+ project: ".agent/skills",
189
+ global: "~/.agent/skills"
190
+ },
191
+ custom: {
192
+ project: "skills",
193
+ global: ""
194
+ }
195
+ };
196
+ var ErrorCode = {
197
+ VALIDATION_ERROR: "VALIDATION_ERROR",
198
+ NOT_FOUND: "NOT_FOUND",
199
+ ALREADY_EXISTS: "ALREADY_EXISTS",
200
+ INTERNAL_ERROR: "INTERNAL_ERROR",
201
+ GIT_ERROR: "GIT_ERROR",
202
+ FILE_SYSTEM_ERROR: "FILE_SYSTEM_ERROR",
203
+ PERMISSION_ERROR: "PERMISSION_ERROR",
204
+ SYMLINK_ERROR: "SYMLINK_ERROR"
205
+ };
206
+
207
+ // src/middleware/errorHandler.ts
208
+ var AppError = class extends Error {
209
+ constructor(code, message, statusCode = 500, details) {
210
+ super(message);
211
+ this.code = code;
212
+ this.statusCode = statusCode;
213
+ this.details = details;
214
+ this.name = "AppError";
215
+ }
216
+ };
217
+ function errorHandler(err, req, res, next) {
218
+ console.error("Error:", err);
219
+ if (err instanceof AppError) {
220
+ return res.status(err.statusCode).json({
221
+ success: false,
222
+ error: err.message,
223
+ code: err.code,
224
+ details: err.details
225
+ });
226
+ }
227
+ return res.status(500).json({
228
+ success: false,
229
+ error: "Internal server error",
230
+ code: ErrorCode.INTERNAL_ERROR,
231
+ message: process.env.NODE_ENV === "development" ? err.message : void 0
232
+ });
233
+ }
234
+
235
+ // src/services/skillService.ts
236
+ var SKILLVERSE_HOME = process.env.SKILLVERSE_HOME || join2(process.env.HOME || "", ".skillverse");
237
+ var SKILLS_DIR = process.env.SKILLS_DIR || join2(SKILLVERSE_HOME, "skills");
238
+ var TEMP_DIR = process.env.TEMP_DIR || join2(SKILLVERSE_HOME, "temp");
239
+ function parseGitUrl(url) {
240
+ if (!url.includes("/tree/")) {
241
+ const urlParts = url.split("/");
242
+ const repoName = urlParts[urlParts.length - 1].replace(".git", "");
243
+ return { repoUrl: url, skillName: repoName };
244
+ }
245
+ const parts = url.split("/tree/");
246
+ const repoUrl = parts[0] + (parts[0].endsWith(".git") ? "" : ".git");
247
+ const pathParts = parts[1].split("/");
248
+ const branch = pathParts[0];
249
+ const subdir = pathParts.slice(1).join("/");
250
+ const skillName = pathParts[pathParts.length - 1];
251
+ return { repoUrl, subdir, skillName };
252
+ }
253
+ var SkillService = class {
254
+ async getAllSkills() {
255
+ const skills = await prisma.skill.findMany({
256
+ include: {
257
+ linkedWorkspaces: {
258
+ include: {
259
+ workspace: true
260
+ }
261
+ },
262
+ marketplaceEntry: true
263
+ },
264
+ orderBy: {
265
+ installDate: "desc"
266
+ }
267
+ });
268
+ return skills;
269
+ }
270
+ async getSkillById(id) {
271
+ const skill = await prisma.skill.findUnique({
272
+ where: { id },
273
+ include: {
274
+ linkedWorkspaces: {
275
+ include: {
276
+ workspace: true
277
+ }
278
+ },
279
+ marketplaceEntry: true
280
+ }
281
+ });
282
+ if (!skill) {
283
+ throw new AppError(ErrorCode.NOT_FOUND, "Skill not found", 404);
284
+ }
285
+ return skill;
286
+ }
287
+ async getSkillByName(name) {
288
+ const skill = await prisma.skill.findUnique({
289
+ where: { name },
290
+ include: {
291
+ linkedWorkspaces: {
292
+ include: {
293
+ workspace: true
294
+ }
295
+ },
296
+ marketplaceEntry: true
297
+ }
298
+ });
299
+ if (!skill) {
300
+ throw new AppError(ErrorCode.NOT_FOUND, `Skill "${name}" not found`, 404);
301
+ }
302
+ return skill;
303
+ }
304
+ async parseSkillMetadata(skillPath) {
305
+ try {
306
+ const skillMdPath = join2(skillPath, "SKILL.md");
307
+ let description = "";
308
+ let metadata = {};
309
+ if (existsSync2(skillMdPath)) {
310
+ const fileContent = await readFile(skillMdPath, "utf-8");
311
+ const parsed = matter(fileContent);
312
+ description = parsed.data.description || "";
313
+ metadata = parsed.data;
314
+ }
315
+ if (!description) {
316
+ const packageJsonPath = join2(skillPath, "package.json");
317
+ const skillJsonPath = join2(skillPath, "skill.json");
318
+ if (existsSync2(skillJsonPath)) {
319
+ const content = await readFile(skillJsonPath, "utf-8");
320
+ const json = JSON.parse(content);
321
+ description = json.description || "";
322
+ metadata = { ...metadata, ...json };
323
+ } else if (existsSync2(packageJsonPath)) {
324
+ const content = await readFile(packageJsonPath, "utf-8");
325
+ const pkg = JSON.parse(content);
326
+ description = pkg.description || "";
327
+ metadata = { ...metadata, name: pkg.name, version: pkg.version };
328
+ }
329
+ }
330
+ return { description, metadata };
331
+ } catch (error) {
332
+ console.warn("Failed to parse skill metadata:", error);
333
+ return { description: "", metadata: {} };
334
+ }
335
+ }
336
+ async createSkillFromGit(gitUrl, description) {
337
+ let tempPath = null;
338
+ try {
339
+ const { repoUrl, subdir, skillName } = parseGitUrl(gitUrl);
340
+ const existingSkill = await prisma.skill.findUnique({
341
+ where: { name: skillName }
342
+ });
343
+ if (existingSkill) {
344
+ throw new AppError(ErrorCode.ALREADY_EXISTS, `Skill "${skillName}" already exists`, 409);
345
+ }
346
+ const skillPath = join2(SKILLS_DIR, skillName);
347
+ if (existsSync2(skillPath)) {
348
+ throw new AppError(ErrorCode.ALREADY_EXISTS, `Skill directory "${skillName}" already exists`, 409);
349
+ }
350
+ let commitHash = "";
351
+ if (subdir) {
352
+ tempPath = join2(TEMP_DIR, `git-clone-${Date.now()}`);
353
+ await mkdir(tempPath, { recursive: true });
354
+ console.log(`Cloning ${repoUrl} to temp path for extraction...`);
355
+ const git = simpleGit();
356
+ await git.clone(repoUrl, tempPath);
357
+ try {
358
+ commitHash = await simpleGit(tempPath).revparse(["HEAD"]);
359
+ console.log(`Captured commit hash: ${commitHash}`);
360
+ } catch (e) {
361
+ console.warn("Failed to capture commit hash:", e);
362
+ }
363
+ const sourcePath = join2(tempPath, subdir);
364
+ if (!existsSync2(sourcePath)) {
365
+ throw new AppError(
366
+ ErrorCode.GIT_ERROR,
367
+ `Subdirectory "${subdir}" not found in repository`,
368
+ 400
369
+ );
370
+ }
371
+ const hasSkillMd = existsSync2(join2(sourcePath, "SKILL.md"));
372
+ const hasSkillJson = existsSync2(join2(sourcePath, "skill.json"));
373
+ const hasPackageJson = existsSync2(join2(sourcePath, "package.json"));
374
+ if (!hasSkillMd && !hasSkillJson && !hasPackageJson) {
375
+ throw new AppError(
376
+ ErrorCode.VALIDATION_ERROR,
377
+ `Invalid skill structure: "${subdir}" does not contain SKILL.md, skill.json, or package.json`,
378
+ 400
379
+ );
380
+ }
381
+ await mkdir(skillPath, { recursive: true });
382
+ await cp(sourcePath, skillPath, { recursive: true });
383
+ } else {
384
+ if (!existsSync2(skillPath)) {
385
+ await mkdir(skillPath, { recursive: true });
386
+ }
387
+ const git = simpleGit();
388
+ console.log(`Cloning ${gitUrl} to ${skillPath}...`);
389
+ await git.clone(gitUrl, skillPath);
390
+ try {
391
+ commitHash = await git.cwd(skillPath).revparse(["HEAD"]);
392
+ console.log(`Captured commit hash: ${commitHash}`);
393
+ } catch (e) {
394
+ console.warn("Failed to capture commit hash:", e);
395
+ }
396
+ }
397
+ const parsed = await this.parseSkillMetadata(skillPath);
398
+ const skill = await prisma.skill.create({
399
+ data: {
400
+ name: skillName,
401
+ source: "git",
402
+ sourceUrl: gitUrl,
403
+ repoUrl,
404
+ commitHash,
405
+ description: description || parsed.description || "",
406
+ storagePath: skillPath,
407
+ metadata: JSON.stringify(parsed.metadata)
408
+ }
409
+ });
410
+ return skill;
411
+ } catch (error) {
412
+ throw error;
413
+ } finally {
414
+ if (tempPath && existsSync2(tempPath)) {
415
+ await rm(tempPath, { recursive: true, force: true }).catch(console.error);
416
+ }
417
+ }
418
+ }
419
+ async createSkillFromDirectory(path, name, description) {
420
+ if (!existsSync2(path)) {
421
+ throw new AppError(ErrorCode.FILE_SYSTEM_ERROR, `Source path not found: ${path}`, 400);
422
+ }
423
+ const skillName = name || basename(path);
424
+ const skillPath = join2(SKILLS_DIR, skillName);
425
+ const existingSkill = await prisma.skill.findUnique({
426
+ where: { name: skillName }
427
+ });
428
+ if (existingSkill) {
429
+ throw new AppError(ErrorCode.ALREADY_EXISTS, `Skill "${skillName}" already exists`, 409);
430
+ }
431
+ if (existsSync2(skillPath)) {
432
+ throw new AppError(ErrorCode.ALREADY_EXISTS, `Skill directory "${skillName}" already exists`, 409);
433
+ }
434
+ try {
435
+ await mkdir(skillPath, { recursive: true });
436
+ await cp(path, skillPath, { recursive: true });
437
+ const parsed = await this.parseSkillMetadata(skillPath);
438
+ const skill = await prisma.skill.create({
439
+ data: {
440
+ name: skillName,
441
+ source: "local",
442
+ description: description || parsed.description || "",
443
+ storagePath: skillPath,
444
+ metadata: JSON.stringify(parsed.metadata)
445
+ }
446
+ });
447
+ return skill;
448
+ } catch (error) {
449
+ if (existsSync2(skillPath)) {
450
+ await rm(skillPath, { recursive: true, force: true }).catch(() => {
451
+ });
452
+ }
453
+ throw error;
454
+ }
455
+ }
456
+ /**
457
+ * Helper to handle cases where the archive contains a single top-level directory.
458
+ * Moves contents up one level if that's the case.
459
+ */
460
+ async stripTopLevelDirectory(targetPath) {
461
+ const { readdir: readdir2, rename, rmdir, stat: stat2 } = await import("fs/promises");
462
+ const items = await readdir2(targetPath);
463
+ const validItems = items.filter((i) => i !== ".DS_Store" && i !== "__MACOSX");
464
+ if (validItems.length === 1) {
465
+ const topLevelItem = validItems[0];
466
+ const topLevelPath = join2(targetPath, topLevelItem);
467
+ const stats = await stat2(topLevelPath);
468
+ if (stats.isDirectory()) {
469
+ console.log(`Striping top-level directory: ${topLevelItem}`);
470
+ const subItems = await readdir2(topLevelPath);
471
+ for (const item of subItems) {
472
+ await rename(join2(topLevelPath, item), join2(targetPath, item));
473
+ }
474
+ await rmdir(topLevelPath);
475
+ }
476
+ }
477
+ }
478
+ async createSkillFromLocal(name, zipPath, description) {
479
+ const skillPath = join2(SKILLS_DIR, name);
480
+ const existingSkill = await prisma.skill.findUnique({
481
+ where: { name }
482
+ });
483
+ if (existingSkill) {
484
+ throw new AppError(ErrorCode.ALREADY_EXISTS, `Skill "${name}" already exists`, 409);
485
+ }
486
+ if (existsSync2(skillPath)) {
487
+ throw new AppError(ErrorCode.ALREADY_EXISTS, `Skill directory "${name}" already exists`, 409);
488
+ }
489
+ const extractPath = join2(TEMP_DIR, `extract-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`);
490
+ await mkdir(extractPath, { recursive: true });
491
+ try {
492
+ const zip = new AdmZip(zipPath);
493
+ zip.extractAllTo(extractPath, true);
494
+ await this.stripTopLevelDirectory(extractPath);
495
+ const parsed = await this.parseSkillMetadata(extractPath);
496
+ if (existsSync2(skillPath)) {
497
+ throw new AppError(ErrorCode.ALREADY_EXISTS, `Skill directory "${name}" already exists`, 409);
498
+ }
499
+ await import("fs/promises").then((fs) => fs.rename(extractPath, skillPath));
500
+ const skill = await prisma.skill.create({
501
+ data: {
502
+ name,
503
+ source: "local",
504
+ description: description || parsed.description || "",
505
+ storagePath: skillPath,
506
+ metadata: JSON.stringify(parsed.metadata)
507
+ }
508
+ });
509
+ return skill;
510
+ } catch (error) {
511
+ if (existsSync2(skillPath)) {
512
+ await rm(skillPath, { recursive: true, force: true }).catch(() => {
513
+ });
514
+ }
515
+ if (existsSync2(extractPath)) {
516
+ await rm(extractPath, { recursive: true, force: true }).catch(() => {
517
+ });
518
+ }
519
+ throw error;
520
+ }
521
+ }
522
+ /**
523
+ * Create a skill from a tar.gz bundle (marketplace install)
524
+ * @param bundlePath - Path to the .tar.gz bundle
525
+ * @param originalName - Original skill name
526
+ * @param description - Optional skill description
527
+ */
528
+ async createSkillFromBundle(bundlePath, originalName, description) {
529
+ let name = originalName;
530
+ let counter = 1;
531
+ while (await prisma.skill.findUnique({ where: { name } })) {
532
+ name = `${originalName}-${counter}`;
533
+ counter++;
534
+ }
535
+ const skillPath = join2(SKILLS_DIR, name);
536
+ const extractPath = join2(TEMP_DIR, `extract-bundle-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`);
537
+ await mkdir(extractPath, { recursive: true });
538
+ try {
539
+ const { createReadStream: createReadStream2 } = await import("fs");
540
+ const { createGunzip: createGunzip2 } = await import("zlib");
541
+ const tar = await import("tar");
542
+ const { pipeline: pipeline2 } = await import("stream/promises");
543
+ await pipeline2(
544
+ createReadStream2(bundlePath),
545
+ createGunzip2(),
546
+ tar.extract({ cwd: extractPath })
547
+ );
548
+ await this.stripTopLevelDirectory(extractPath);
549
+ const parsed = await this.parseSkillMetadata(extractPath);
550
+ if (existsSync2(skillPath)) {
551
+ throw new AppError(ErrorCode.ALREADY_EXISTS, `Skill directory "${name}" already exists`, 409);
552
+ }
553
+ await import("fs/promises").then((fs) => fs.rename(extractPath, skillPath));
554
+ const skill = await prisma.skill.create({
555
+ data: {
556
+ name,
557
+ source: "local",
558
+ description: description || parsed.description || "",
559
+ storagePath: skillPath,
560
+ metadata: JSON.stringify(parsed.metadata)
561
+ }
562
+ });
563
+ console.log(`\u{1F4E6} Installed skill "${name}" from bundle`);
564
+ return skill;
565
+ } catch (error) {
566
+ if (existsSync2(skillPath)) {
567
+ await rm(skillPath, { recursive: true, force: true }).catch(() => {
568
+ });
569
+ }
570
+ if (existsSync2(extractPath)) {
571
+ await rm(extractPath, { recursive: true, force: true }).catch(() => {
572
+ });
573
+ }
574
+ throw error;
575
+ }
576
+ }
577
+ async updateSkill(id, data) {
578
+ const skill = await this.getSkillById(id);
579
+ const updatedSkill = await prisma.skill.update({
580
+ where: { id },
581
+ data: {
582
+ ...data.name && { name: data.name },
583
+ ...data.description !== void 0 && { description: data.description },
584
+ ...data.metadata && { metadata: JSON.stringify(data.metadata) }
585
+ }
586
+ });
587
+ return updatedSkill;
588
+ }
589
+ async deleteSkill(id, removeFiles = true) {
590
+ const skill = await this.getSkillById(id);
591
+ if (skill.linkedWorkspaces && skill.linkedWorkspaces.length > 0) {
592
+ for (const link of skill.linkedWorkspaces) {
593
+ try {
594
+ const workspacePath = link.workspace.path;
595
+ const symlinkPath = join2(workspacePath, skill.name);
596
+ if (existsSync2(symlinkPath)) {
597
+ const stats = await import("fs/promises").then((fs) => fs.lstat(symlinkPath));
598
+ if (stats.isSymbolicLink()) {
599
+ await unlink(symlinkPath);
600
+ console.log(`Removed symlink for ${skill.name} in workspace ${workspacePath}`);
601
+ }
602
+ }
603
+ } catch (error) {
604
+ console.warn(`Failed to remove symlink for ${skill.name} in workspace ${link.workspace.path}:`, error);
605
+ }
606
+ }
607
+ }
608
+ await prisma.skill.delete({
609
+ where: { id }
610
+ });
611
+ if (removeFiles && skill.storagePath) {
612
+ await rm(skill.storagePath, { recursive: true, force: true }).catch((err) => {
613
+ console.warn(`Failed to delete skill directory ${skill.storagePath}:`, err);
614
+ });
615
+ }
616
+ return { success: true, message: "Skill deleted successfully" };
617
+ }
618
+ // Check for updates
619
+ async checkForUpdate(id) {
620
+ const skill = await this.getSkillById(id);
621
+ if (skill.source !== "git" || !skill.repoUrl) {
622
+ return {
623
+ hasUpdate: false,
624
+ currentHash: skill.commitHash,
625
+ remoteHash: null,
626
+ message: "Not a git skill or missing repo URL"
627
+ };
628
+ }
629
+ const tempPath = join2(TEMP_DIR, `check-update-${Date.now()}`);
630
+ await mkdir(tempPath, { recursive: true });
631
+ try {
632
+ const git = simpleGit();
633
+ console.log(`Checking updates for ${skill.name} from ${skill.repoUrl}...`);
634
+ const remote = await git.listRemote([skill.repoUrl, "HEAD"]);
635
+ if (!remote) {
636
+ throw new Error("Failed to get remote HEAD");
637
+ }
638
+ const remoteHash = remote.split(" ")[0];
639
+ const hasUpdate = remoteHash !== skill.commitHash;
640
+ await prisma.skill.update({
641
+ where: { id },
642
+ data: {
643
+ lastUpdateCheck: /* @__PURE__ */ new Date(),
644
+ updateAvailable: hasUpdate
645
+ }
646
+ });
647
+ return {
648
+ hasUpdate,
649
+ currentHash: skill.commitHash,
650
+ remoteHash
651
+ };
652
+ } catch (error) {
653
+ console.error("Update check error:", error);
654
+ throw new AppError(ErrorCode.GIT_ERROR, `Failed to check for updates: ${error.message}`, 500);
655
+ } finally {
656
+ await rm(tempPath, { recursive: true, force: true }).catch(() => {
657
+ });
658
+ }
659
+ }
660
+ async checkUpdates(ids) {
661
+ const whereClause = {
662
+ source: "git",
663
+ repoUrl: { not: null }
664
+ };
665
+ if (ids && ids.length > 0) {
666
+ whereClause.id = { in: ids };
667
+ }
668
+ const skills = await prisma.skill.findMany({ where: whereClause });
669
+ const results = {};
670
+ console.log(`Checking updates for ${skills.length} skills...`);
671
+ await Promise.all(skills.map(async (skill) => {
672
+ try {
673
+ const result = await this.checkForUpdate(skill.id);
674
+ results[skill.id] = result;
675
+ } catch (e) {
676
+ results[skill.id] = { error: e.message };
677
+ }
678
+ }));
679
+ return results;
680
+ }
681
+ async refreshMetadata(id) {
682
+ const skill = await this.getSkillById(id);
683
+ const parsed = await this.parseSkillMetadata(skill.storagePath);
684
+ const updated = await prisma.skill.update({
685
+ where: { id },
686
+ data: {
687
+ description: parsed.description,
688
+ metadata: JSON.stringify(parsed.metadata)
689
+ }
690
+ });
691
+ return updated;
692
+ }
693
+ async upgradeSkill(id) {
694
+ const skill = await this.getSkillById(id);
695
+ if (skill.source !== "git" || !skill.sourceUrl) {
696
+ throw new AppError(ErrorCode.VALIDATION_ERROR, "Cannot upgrade non-git skill", 400);
697
+ }
698
+ let tempPath = null;
699
+ let tempSkillPath = null;
700
+ try {
701
+ const { repoUrl, subdir } = parseGitUrl(skill.sourceUrl);
702
+ tempPath = join2(TEMP_DIR, `upgrade-${Date.now()}`);
703
+ await mkdir(tempPath, { recursive: true });
704
+ const git = simpleGit();
705
+ console.log(`Cloning ${repoUrl} to temp for upgrade...`);
706
+ await git.clone(repoUrl, tempPath);
707
+ let commitHash = "";
708
+ try {
709
+ commitHash = await simpleGit(tempPath).revparse(["HEAD"]);
710
+ } catch (e) {
711
+ console.warn("Failed to capture commit hash during upgrade:", e);
712
+ }
713
+ let sourcePath = tempPath;
714
+ if (subdir) {
715
+ sourcePath = join2(tempPath, subdir);
716
+ if (!existsSync2(sourcePath)) {
717
+ throw new AppError(ErrorCode.GIT_ERROR, `Subdirectory "${subdir}" not found`, 400);
718
+ }
719
+ }
720
+ const hasSkillMd = existsSync2(join2(sourcePath, "SKILL.md"));
721
+ const hasSkillJson = existsSync2(join2(sourcePath, "skill.json"));
722
+ const hasPackageJson = existsSync2(join2(sourcePath, "package.json"));
723
+ if (!hasSkillMd && !hasSkillJson && !hasPackageJson) {
724
+ throw new AppError(ErrorCode.VALIDATION_ERROR, "Invalid skill structure in new version", 400);
725
+ }
726
+ const files = await import("fs/promises").then((fs) => fs.readdir(skill.storagePath));
727
+ for (const file of files) {
728
+ await rm(join2(skill.storagePath, file), { recursive: true, force: true });
729
+ }
730
+ await cp(sourcePath, skill.storagePath, { recursive: true });
731
+ const parsed = await this.parseSkillMetadata(skill.storagePath);
732
+ const updatedSkill = await prisma.skill.update({
733
+ where: { id },
734
+ data: {
735
+ commitHash,
736
+ updateAvailable: false,
737
+ lastUpdateCheck: /* @__PURE__ */ new Date(),
738
+ installDate: /* @__PURE__ */ new Date(),
739
+ // Considering upgrade as reinstall? Or user prefer generic updatedAt
740
+ // Keeping installDate as "last installed/upgraded"
741
+ description: parsed.description,
742
+ metadata: JSON.stringify(parsed.metadata)
743
+ }
744
+ });
745
+ return updatedSkill;
746
+ } catch (error) {
747
+ console.error("Upgrade error:", error);
748
+ throw new AppError(ErrorCode.GIT_ERROR, `Failed to upgrade skill: ${error.message}`, 500);
749
+ } finally {
750
+ if (tempPath) await rm(tempPath, { recursive: true, force: true }).catch(() => {
751
+ });
752
+ }
753
+ }
754
+ };
755
+ var skillService = new SkillService();
756
+
757
+ // src/services/workspaceService.ts
758
+ import { join as join3 } from "path";
759
+ import { homedir } from "os";
760
+ import { symlink, unlink as unlink2, rm as rm2, mkdir as mkdir2, appendFile, readFile as readFile2 } from "fs/promises";
761
+ import { existsSync as existsSync3, lstatSync } from "fs";
762
+ function computeSkillsPath(projectPath, type, scope) {
763
+ const pathConfig = WORKSPACE_SKILLS_PATHS[type];
764
+ if (scope === "global") {
765
+ return pathConfig.global.replace("~", homedir());
766
+ }
767
+ return join3(projectPath, pathConfig.project);
768
+ }
769
+ var WorkspaceService = class {
770
+ /**
771
+ * Helper to get expected skills path for a project
772
+ */
773
+ getSkillsPath(projectPath, type, scope) {
774
+ return computeSkillsPath(projectPath, type, scope);
775
+ }
776
+ /**
777
+ * Sync database links with filesystem state
778
+ * Removes links from DB if the symlink is missing from the workspace
779
+ */
780
+ async syncLinks(workspace) {
781
+ if (!workspace.linkedSkills || workspace.linkedSkills.length === 0) return;
782
+ for (const link of workspace.linkedSkills) {
783
+ if (!link.skill) continue;
784
+ const linkPath = join3(workspace.path, link.skill.name);
785
+ if (!existsSync3(linkPath)) {
786
+ console.log(`Link missing for skill "${link.skill.name}" in workspace "${workspace.name}". Removing from DB.`);
787
+ try {
788
+ await prisma.skillWorkspace.delete({
789
+ where: { id: link.id }
790
+ });
791
+ workspace.linkedSkills = workspace.linkedSkills.filter((l) => l.id !== link.id);
792
+ } catch (err) {
793
+ console.error(`Failed to sync link for ${link.skill.name}:`, err);
794
+ }
795
+ }
796
+ }
797
+ }
798
+ async findWorkspaceByPath(path) {
799
+ const workspace = await prisma.workspace.findUnique({
800
+ where: { path },
801
+ include: {
802
+ linkedSkills: {
803
+ include: {
804
+ skill: true
805
+ }
806
+ }
807
+ }
808
+ });
809
+ return workspace;
810
+ }
811
+ async getAllWorkspaces() {
812
+ const workspaces = await prisma.workspace.findMany({
813
+ include: {
814
+ linkedSkills: {
815
+ include: {
816
+ skill: true
817
+ }
818
+ }
819
+ },
820
+ orderBy: {
821
+ createdAt: "desc"
822
+ }
823
+ });
824
+ await Promise.all(workspaces.map((w) => this.syncLinks(w)));
825
+ return workspaces.map((workspace) => ({
826
+ ...workspace,
827
+ isPathValid: existsSync3(workspace.path)
828
+ }));
829
+ }
830
+ async getWorkspaceById(id) {
831
+ const workspace = await prisma.workspace.findUnique({
832
+ where: { id },
833
+ include: {
834
+ linkedSkills: {
835
+ include: {
836
+ skill: true
837
+ }
838
+ }
839
+ }
840
+ });
841
+ if (!workspace) {
842
+ throw new AppError(ErrorCode.NOT_FOUND, "Workspace not found", 404);
843
+ }
844
+ await this.syncLinks(workspace);
845
+ return {
846
+ ...workspace,
847
+ isPathValid: existsSync3(workspace.path)
848
+ };
849
+ }
850
+ async createWorkspace(name, projectPath, type, scope) {
851
+ const skillsPath = computeSkillsPath(projectPath, type, scope);
852
+ if (scope === "project" && projectPath && !existsSync3(projectPath)) {
853
+ throw new AppError(ErrorCode.FILE_SYSTEM_ERROR, `Project path does not exist: ${projectPath}`, 400);
854
+ }
855
+ if (!existsSync3(skillsPath)) {
856
+ try {
857
+ await mkdir2(skillsPath, { recursive: true });
858
+ } catch (err) {
859
+ throw new AppError(
860
+ ErrorCode.FILE_SYSTEM_ERROR,
861
+ `Failed to create skills directory: ${err.message}`,
862
+ 500
863
+ );
864
+ }
865
+ }
866
+ const existingWorkspace = await prisma.workspace.findUnique({
867
+ where: { path: skillsPath }
868
+ });
869
+ if (existingWorkspace) {
870
+ throw new AppError(ErrorCode.ALREADY_EXISTS, "Workspace already exists at this path", 409);
871
+ }
872
+ const workspace = await prisma.workspace.create({
873
+ data: {
874
+ name,
875
+ path: skillsPath,
876
+ type,
877
+ scope
878
+ }
879
+ });
880
+ if (scope === "project" && projectPath && existsSync3(projectPath)) {
881
+ try {
882
+ const gitignorePath = join3(projectPath, ".gitignore");
883
+ const relativeSkillsPath = WORKSPACE_SKILLS_PATHS[type].project;
884
+ let shouldAppend = false;
885
+ if (existsSync3(gitignorePath)) {
886
+ const content = await readFile2(gitignorePath, "utf-8");
887
+ if (!content.includes(relativeSkillsPath)) {
888
+ shouldAppend = true;
889
+ }
890
+ } else {
891
+ shouldAppend = true;
892
+ }
893
+ if (shouldAppend) {
894
+ const ignoreEntry = `
895
+
896
+ # SkillVerse
897
+ ${relativeSkillsPath}/
898
+ `;
899
+ await appendFile(gitignorePath, ignoreEntry);
900
+ console.log(`Added ${relativeSkillsPath}/ to .gitignore in ${projectPath}`);
901
+ }
902
+ } catch (err) {
903
+ console.warn("Failed to update .gitignore:", err);
904
+ }
905
+ }
906
+ return {
907
+ ...workspace,
908
+ isPathValid: true
909
+ };
910
+ }
911
+ async updateWorkspace(id, data) {
912
+ await this.getWorkspaceById(id);
913
+ const workspace = await prisma.workspace.update({
914
+ where: { id },
915
+ data
916
+ });
917
+ return {
918
+ ...workspace,
919
+ isPathValid: existsSync3(workspace.path)
920
+ };
921
+ }
922
+ async deleteWorkspace(id) {
923
+ const workspace = await this.getWorkspaceById(id);
924
+ const links = await prisma.skillWorkspace.findMany({
925
+ where: { workspaceId: id },
926
+ include: { skill: true }
927
+ });
928
+ for (const link of links) {
929
+ try {
930
+ const linkPath = join3(workspace.path, link.skill.name);
931
+ if (existsSync3(linkPath)) {
932
+ await rm2(linkPath, { recursive: true, force: true });
933
+ }
934
+ } catch (error) {
935
+ console.error(`Failed to remove symlink for ${link.skill.name}:`, error);
936
+ }
937
+ }
938
+ await prisma.workspace.delete({ where: { id } });
939
+ return { success: true, message: "Workspace deleted successfully" };
940
+ }
941
+ async linkSkillToWorkspace(skillId, workspaceId) {
942
+ const skill = await prisma.skill.findUnique({ where: { id: skillId } });
943
+ const workspace = await prisma.workspace.findUnique({ where: { id: workspaceId } });
944
+ if (!skill) {
945
+ throw new AppError(ErrorCode.NOT_FOUND, "Skill not found", 404);
946
+ }
947
+ if (!workspace) {
948
+ throw new AppError(ErrorCode.NOT_FOUND, "Workspace not found", 404);
949
+ }
950
+ if (!existsSync3(workspace.path)) {
951
+ throw new AppError(
952
+ ErrorCode.FILE_SYSTEM_ERROR,
953
+ `Workspace skills directory does not exist: ${workspace.path}. The folder may have been deleted. Please recreate it or remove this workspace.`,
954
+ 400
955
+ );
956
+ }
957
+ const existingLink = await prisma.skillWorkspace.findFirst({
958
+ where: {
959
+ skillId,
960
+ workspaceId
961
+ }
962
+ });
963
+ if (existingLink) {
964
+ throw new AppError(ErrorCode.ALREADY_EXISTS, "Skill is already linked to this workspace", 409);
965
+ }
966
+ const targetPath = join3(workspace.path, skill.name);
967
+ try {
968
+ if (existsSync3(targetPath)) {
969
+ const stats = lstatSync(targetPath);
970
+ if (stats.isSymbolicLink()) {
971
+ await unlink2(targetPath);
972
+ } else {
973
+ throw new AppError(
974
+ ErrorCode.FILE_SYSTEM_ERROR,
975
+ `A file or directory already exists at ${targetPath}`,
976
+ 409
977
+ );
978
+ }
979
+ }
980
+ await symlink(skill.storagePath, targetPath, "dir");
981
+ const link = await prisma.skillWorkspace.create({
982
+ data: {
983
+ skillId,
984
+ workspaceId
985
+ },
986
+ include: {
987
+ skill: true,
988
+ workspace: true
989
+ }
990
+ });
991
+ return link;
992
+ } catch (error) {
993
+ if (error instanceof AppError) throw error;
994
+ console.error("Symlink creation error:", error);
995
+ throw new AppError(
996
+ ErrorCode.SYMLINK_ERROR,
997
+ `Failed to create symlink: ${error.message}`,
998
+ 500,
999
+ error
1000
+ );
1001
+ }
1002
+ }
1003
+ async unlinkSkillFromWorkspace(skillId, workspaceId) {
1004
+ const link = await prisma.skillWorkspace.findFirst({
1005
+ where: {
1006
+ skillId,
1007
+ workspaceId
1008
+ },
1009
+ include: {
1010
+ skill: true,
1011
+ workspace: true
1012
+ }
1013
+ });
1014
+ if (!link) {
1015
+ throw new AppError(ErrorCode.NOT_FOUND, "Link not found", 404);
1016
+ }
1017
+ const linkPath = join3(link.workspace.path, link.skill.name);
1018
+ try {
1019
+ if (existsSync3(linkPath)) {
1020
+ await rm2(linkPath, { recursive: true, force: true });
1021
+ }
1022
+ await prisma.skillWorkspace.delete({
1023
+ where: { id: link.id }
1024
+ });
1025
+ return { success: true, message: "Skill unlinked successfully" };
1026
+ } catch (error) {
1027
+ console.error("Unlink error:", error);
1028
+ throw new AppError(
1029
+ ErrorCode.FILE_SYSTEM_ERROR,
1030
+ `Failed to unlink skill: ${error.message}`,
1031
+ 500,
1032
+ error
1033
+ );
1034
+ }
1035
+ }
1036
+ /**
1037
+ * Detect existing skills in a workspace skills directory
1038
+ * Returns list of skill names that could be migrated
1039
+ */
1040
+ async detectExistingSkills(skillsPath) {
1041
+ if (!existsSync3(skillsPath)) {
1042
+ return [];
1043
+ }
1044
+ const { readdir: readdir2, stat: stat2, readFile: readFile3 } = await import("fs/promises");
1045
+ const items = await readdir2(skillsPath);
1046
+ const existingSkills = [];
1047
+ for (const item of items) {
1048
+ if (item.startsWith(".")) continue;
1049
+ const itemPath = join3(skillsPath, item);
1050
+ try {
1051
+ const itemStat = await stat2(itemPath);
1052
+ const lstats = lstatSync(itemPath);
1053
+ if (lstats.isSymbolicLink()) continue;
1054
+ if (itemStat.isDirectory()) {
1055
+ const hasSkillMd = existsSync3(join3(itemPath, "SKILL.md"));
1056
+ const hasSkillJson = existsSync3(join3(itemPath, "skill.json"));
1057
+ const hasPackageJson = existsSync3(join3(itemPath, "package.json"));
1058
+ if (hasSkillMd || hasSkillJson || hasPackageJson) {
1059
+ existingSkills.push({
1060
+ name: item,
1061
+ hasSkillMd,
1062
+ path: itemPath
1063
+ });
1064
+ }
1065
+ }
1066
+ } catch (error) {
1067
+ console.warn(`Failed to check ${itemPath}:`, error);
1068
+ }
1069
+ }
1070
+ return existingSkills;
1071
+ }
1072
+ /**
1073
+ * Migrate existing skills from workspace to unified storage
1074
+ * 1. Move skills to ~/.skillverse/skills/
1075
+ * 2. Register in database
1076
+ * 3. Create symlinks back to workspace
1077
+ */
1078
+ async migrateExistingSkills(workspaceId, skillNames) {
1079
+ const workspace = await this.getWorkspaceById(workspaceId);
1080
+ const SKILLVERSE_HOME3 = process.env.SKILLVERSE_HOME || join3(homedir(), ".skillverse");
1081
+ const SKILLS_DIR2 = process.env.SKILLS_DIR || join3(SKILLVERSE_HOME3, "skills");
1082
+ if (!existsSync3(SKILLS_DIR2)) {
1083
+ await mkdir2(SKILLS_DIR2, { recursive: true });
1084
+ }
1085
+ const { rename, readFile: readFile3, cp: cp2 } = await import("fs/promises");
1086
+ const migrated = [];
1087
+ const errors = [];
1088
+ for (const skillName of skillNames) {
1089
+ const sourcePath = join3(workspace.path, skillName);
1090
+ const targetPath = join3(SKILLS_DIR2, skillName);
1091
+ try {
1092
+ if (!existsSync3(sourcePath)) {
1093
+ errors.push(`${skillName}: Source path not found`);
1094
+ continue;
1095
+ }
1096
+ const lstats = lstatSync(sourcePath);
1097
+ if (lstats.isSymbolicLink()) {
1098
+ errors.push(`${skillName}: Already a symlink, skipping`);
1099
+ continue;
1100
+ }
1101
+ if (existsSync3(targetPath)) {
1102
+ errors.push(`${skillName}: Already exists in unified storage`);
1103
+ continue;
1104
+ }
1105
+ const existingSkill = await prisma.skill.findUnique({
1106
+ where: { name: skillName }
1107
+ });
1108
+ if (existingSkill) {
1109
+ errors.push(`${skillName}: Already registered in database`);
1110
+ continue;
1111
+ }
1112
+ const skillMdPath = join3(sourcePath, "SKILL.md");
1113
+ let description = "";
1114
+ let metadata = {};
1115
+ if (existsSync3(skillMdPath)) {
1116
+ try {
1117
+ const matter2 = await import("gray-matter");
1118
+ const fileContent = await readFile3(skillMdPath, "utf-8");
1119
+ const parsed = matter2.default(fileContent);
1120
+ description = parsed.data.description || "";
1121
+ metadata = parsed.data;
1122
+ } catch (e) {
1123
+ console.warn(`Failed to parse SKILL.md for ${skillName}:`, e);
1124
+ }
1125
+ }
1126
+ await cp2(sourcePath, targetPath, { recursive: true });
1127
+ await rm2(sourcePath, { recursive: true, force: true });
1128
+ const skill = await prisma.skill.create({
1129
+ data: {
1130
+ name: skillName,
1131
+ source: "local",
1132
+ description,
1133
+ storagePath: targetPath,
1134
+ metadata: JSON.stringify(metadata)
1135
+ }
1136
+ });
1137
+ await symlink(targetPath, sourcePath, "dir");
1138
+ await prisma.skillWorkspace.create({
1139
+ data: {
1140
+ skillId: skill.id,
1141
+ workspaceId: workspace.id
1142
+ }
1143
+ });
1144
+ migrated.push(skillName);
1145
+ console.log(`\u2705 Migrated skill "${skillName}" to unified storage`);
1146
+ } catch (error) {
1147
+ console.error(`Failed to migrate ${skillName}:`, error);
1148
+ errors.push(`${skillName}: ${error.message}`);
1149
+ }
1150
+ }
1151
+ return {
1152
+ success: errors.length === 0,
1153
+ migrated,
1154
+ errors
1155
+ };
1156
+ }
1157
+ };
1158
+ var workspaceService = new WorkspaceService();
1159
+
1160
+ // src/routes/skills.ts
1161
+ var router = Router();
1162
+ var TEMP_DIR2 = process.env.TEMP_DIR || join4(process.env.HOME || "", ".skillverse", "temp");
1163
+ if (!existsSync4(TEMP_DIR2)) {
1164
+ mkdir3(TEMP_DIR2, { recursive: true });
1165
+ }
1166
+ var storage = multer.diskStorage({
1167
+ destination: (req, file, cb) => {
1168
+ cb(null, TEMP_DIR2);
1169
+ },
1170
+ filename: (req, file, cb) => {
1171
+ const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
1172
+ cb(null, uniqueSuffix + "-" + file.originalname);
1173
+ }
1174
+ });
1175
+ var upload = multer({
1176
+ storage,
1177
+ limits: {
1178
+ fileSize: 100 * 1024 * 1024
1179
+ // 100MB limit
1180
+ },
1181
+ fileFilter: (req, file, cb) => {
1182
+ if (file.mimetype === "application/zip" || file.originalname.endsWith(".zip")) {
1183
+ cb(null, true);
1184
+ } else {
1185
+ cb(new Error("Only ZIP files are allowed"));
1186
+ }
1187
+ }
1188
+ });
1189
+ router.get("/", async (req, res, next) => {
1190
+ try {
1191
+ const skills = await skillService.getAllSkills();
1192
+ res.json({
1193
+ success: true,
1194
+ data: skills
1195
+ });
1196
+ } catch (error) {
1197
+ next(error);
1198
+ }
1199
+ });
1200
+ router.get("/:id", async (req, res, next) => {
1201
+ try {
1202
+ const skill = await skillService.getSkillById(req.params.id);
1203
+ res.json({
1204
+ success: true,
1205
+ data: skill
1206
+ });
1207
+ } catch (error) {
1208
+ next(error);
1209
+ }
1210
+ });
1211
+ router.post("/from-git", async (req, res, next) => {
1212
+ try {
1213
+ const { gitUrl, description } = req.body;
1214
+ if (!gitUrl) {
1215
+ return res.status(400).json({
1216
+ success: false,
1217
+ error: "gitUrl is required"
1218
+ });
1219
+ }
1220
+ const skill = await skillService.createSkillFromGit(gitUrl, description);
1221
+ res.status(201).json({
1222
+ success: true,
1223
+ data: skill,
1224
+ message: "Skill created successfully from Git repository"
1225
+ });
1226
+ } catch (error) {
1227
+ next(error);
1228
+ }
1229
+ });
1230
+ router.post(
1231
+ "/from-local",
1232
+ upload.single("file"),
1233
+ async (req, res, next) => {
1234
+ try {
1235
+ const { name, description } = req.body;
1236
+ const file = req.file;
1237
+ if (!name) {
1238
+ if (file) {
1239
+ await rm3(file.path, { force: true });
1240
+ }
1241
+ return res.status(400).json({
1242
+ success: false,
1243
+ error: "name is required"
1244
+ });
1245
+ }
1246
+ if (!file) {
1247
+ return res.status(400).json({
1248
+ success: false,
1249
+ error: "ZIP file is required"
1250
+ });
1251
+ }
1252
+ const skill = await skillService.createSkillFromLocal(name, file.path, description);
1253
+ await rm3(file.path, { force: true });
1254
+ res.status(201).json({
1255
+ success: true,
1256
+ data: skill,
1257
+ message: "Skill created successfully from local file"
1258
+ });
1259
+ } catch (error) {
1260
+ if (req.file) {
1261
+ await rm3(req.file.path, { force: true }).catch(() => {
1262
+ });
1263
+ }
1264
+ next(error);
1265
+ }
1266
+ }
1267
+ );
1268
+ router.put("/:id", async (req, res, next) => {
1269
+ try {
1270
+ const { name, description, metadata } = req.body;
1271
+ const skill = await skillService.updateSkill(req.params.id, {
1272
+ name,
1273
+ description,
1274
+ metadata
1275
+ });
1276
+ res.json({
1277
+ success: true,
1278
+ data: skill,
1279
+ message: "Skill updated successfully"
1280
+ });
1281
+ } catch (error) {
1282
+ next(error);
1283
+ }
1284
+ });
1285
+ router.delete("/:id", async (req, res, next) => {
1286
+ try {
1287
+ const removeFiles = req.query.removeFiles !== "false";
1288
+ const result = await skillService.deleteSkill(req.params.id, removeFiles);
1289
+ res.json(result);
1290
+ } catch (error) {
1291
+ next(error);
1292
+ }
1293
+ });
1294
+ router.post("/:id/link", async (req, res, next) => {
1295
+ try {
1296
+ const { workspaceId } = req.body;
1297
+ if (!workspaceId) {
1298
+ return res.status(400).json({
1299
+ success: false,
1300
+ error: "workspaceId is required"
1301
+ });
1302
+ }
1303
+ const link = await workspaceService.linkSkillToWorkspace(req.params.id, workspaceId);
1304
+ res.status(201).json({
1305
+ success: true,
1306
+ data: link,
1307
+ message: "Skill linked to workspace successfully"
1308
+ });
1309
+ } catch (error) {
1310
+ next(error);
1311
+ }
1312
+ });
1313
+ router.delete(
1314
+ "/:id/unlink/:workspaceId",
1315
+ async (req, res, next) => {
1316
+ try {
1317
+ const result = await workspaceService.unlinkSkillFromWorkspace(
1318
+ req.params.id,
1319
+ req.params.workspaceId
1320
+ );
1321
+ res.json(result);
1322
+ } catch (error) {
1323
+ next(error);
1324
+ }
1325
+ }
1326
+ );
1327
+ router.get("/:id/check-update", async (req, res, next) => {
1328
+ try {
1329
+ const result = await skillService.checkForUpdate(req.params.id);
1330
+ res.json({
1331
+ success: true,
1332
+ data: result
1333
+ });
1334
+ } catch (error) {
1335
+ next(error);
1336
+ }
1337
+ });
1338
+ router.post("/:id/upgrade", async (req, res, next) => {
1339
+ try {
1340
+ const skill = await skillService.upgradeSkill(req.params.id);
1341
+ res.json({
1342
+ success: true,
1343
+ data: skill,
1344
+ message: "Skill upgraded successfully"
1345
+ });
1346
+ } catch (error) {
1347
+ next(error);
1348
+ }
1349
+ });
1350
+ router.post("/check-updates", async (req, res, next) => {
1351
+ try {
1352
+ const { ids } = req.body;
1353
+ const results = await skillService.checkUpdates(ids);
1354
+ res.json({
1355
+ success: true,
1356
+ data: results
1357
+ });
1358
+ } catch (error) {
1359
+ next(error);
1360
+ }
1361
+ });
1362
+ router.post("/:id/refresh-metadata", async (req, res, next) => {
1363
+ try {
1364
+ const skill = await skillService.refreshMetadata(req.params.id);
1365
+ res.json({
1366
+ success: true,
1367
+ data: skill,
1368
+ message: "Metadata refreshed successfully"
1369
+ });
1370
+ } catch (error) {
1371
+ next(error);
1372
+ }
1373
+ });
1374
+ router.get("/:id/skill-md", async (req, res, next) => {
1375
+ try {
1376
+ const { readFile: readFile3 } = await import("fs/promises");
1377
+ const skill = await skillService.getSkillById(req.params.id);
1378
+ const skillMdPath = join4(skill.storagePath, "SKILL.md");
1379
+ if (!existsSync4(skillMdPath)) {
1380
+ return res.json({
1381
+ success: true,
1382
+ data: {
1383
+ exists: false,
1384
+ content: null
1385
+ }
1386
+ });
1387
+ }
1388
+ const content = await readFile3(skillMdPath, "utf-8");
1389
+ res.json({
1390
+ success: true,
1391
+ data: {
1392
+ exists: true,
1393
+ content
1394
+ }
1395
+ });
1396
+ } catch (error) {
1397
+ next(error);
1398
+ }
1399
+ });
1400
+ var skills_default = router;
1401
+
1402
+ // src/routes/workspaces.ts
1403
+ import { Router as Router2 } from "express";
1404
+ var router2 = Router2();
1405
+ router2.get("/", async (req, res, next) => {
1406
+ try {
1407
+ const workspaces = await workspaceService.getAllWorkspaces();
1408
+ res.json({
1409
+ success: true,
1410
+ data: workspaces
1411
+ });
1412
+ } catch (error) {
1413
+ next(error);
1414
+ }
1415
+ });
1416
+ router2.get("/:id", async (req, res, next) => {
1417
+ try {
1418
+ const workspace = await workspaceService.getWorkspaceById(req.params.id);
1419
+ res.json({
1420
+ success: true,
1421
+ data: workspace
1422
+ });
1423
+ } catch (error) {
1424
+ next(error);
1425
+ }
1426
+ });
1427
+ router2.post("/", async (req, res, next) => {
1428
+ try {
1429
+ const { name, projectPath, type, scope } = req.body;
1430
+ if (!name || !type || !scope) {
1431
+ return res.status(400).json({
1432
+ success: false,
1433
+ error: "name, type, and scope are required"
1434
+ });
1435
+ }
1436
+ if (scope === "project" && !projectPath) {
1437
+ return res.status(400).json({
1438
+ success: false,
1439
+ error: "projectPath is required for project scope"
1440
+ });
1441
+ }
1442
+ const validTypes = ["vscode", "cursor", "claude-desktop", "codex", "antigravity", "custom"];
1443
+ if (!validTypes.includes(type)) {
1444
+ return res.status(400).json({
1445
+ success: false,
1446
+ error: `type must be one of: ${validTypes.join(", ")}`
1447
+ });
1448
+ }
1449
+ const validScopes = ["project", "global"];
1450
+ if (!validScopes.includes(scope)) {
1451
+ return res.status(400).json({
1452
+ success: false,
1453
+ error: `scope must be one of: ${validScopes.join(", ")}`
1454
+ });
1455
+ }
1456
+ const workspace = await workspaceService.createWorkspace(name, projectPath || "", type, scope);
1457
+ res.status(201).json({
1458
+ success: true,
1459
+ data: workspace,
1460
+ message: "Workspace created successfully"
1461
+ });
1462
+ } catch (error) {
1463
+ next(error);
1464
+ }
1465
+ });
1466
+ router2.put("/:id", async (req, res, next) => {
1467
+ try {
1468
+ const { name, path, type, scope } = req.body;
1469
+ if (type) {
1470
+ const validTypes = ["vscode", "cursor", "claude-desktop", "codex", "antigravity", "custom"];
1471
+ if (!validTypes.includes(type)) {
1472
+ return res.status(400).json({
1473
+ success: false,
1474
+ error: `type must be one of: ${validTypes.join(", ")}`
1475
+ });
1476
+ }
1477
+ }
1478
+ if (scope) {
1479
+ const validScopes = ["project", "global"];
1480
+ if (!validScopes.includes(scope)) {
1481
+ return res.status(400).json({
1482
+ success: false,
1483
+ error: `scope must be one of: ${validScopes.join(", ")}`
1484
+ });
1485
+ }
1486
+ }
1487
+ const workspace = await workspaceService.updateWorkspace(req.params.id, {
1488
+ name,
1489
+ path,
1490
+ type,
1491
+ scope
1492
+ });
1493
+ res.json({
1494
+ success: true,
1495
+ data: workspace,
1496
+ message: "Workspace updated successfully"
1497
+ });
1498
+ } catch (error) {
1499
+ next(error);
1500
+ }
1501
+ });
1502
+ router2.delete("/:id", async (req, res, next) => {
1503
+ try {
1504
+ const result = await workspaceService.deleteWorkspace(req.params.id);
1505
+ res.json(result);
1506
+ } catch (error) {
1507
+ next(error);
1508
+ }
1509
+ });
1510
+ router2.post("/:id/detect-skills", async (req, res, next) => {
1511
+ try {
1512
+ const workspace = await workspaceService.getWorkspaceById(req.params.id);
1513
+ const existingSkills = await workspaceService.detectExistingSkills(workspace.path);
1514
+ res.json({
1515
+ success: true,
1516
+ data: existingSkills
1517
+ });
1518
+ } catch (error) {
1519
+ next(error);
1520
+ }
1521
+ });
1522
+ router2.post("/:id/migrate-skills", async (req, res, next) => {
1523
+ try {
1524
+ const { skillNames } = req.body;
1525
+ if (!skillNames || !Array.isArray(skillNames) || skillNames.length === 0) {
1526
+ return res.status(400).json({
1527
+ success: false,
1528
+ error: "skillNames array is required"
1529
+ });
1530
+ }
1531
+ const result = await workspaceService.migrateExistingSkills(req.params.id, skillNames);
1532
+ res.json({
1533
+ success: true,
1534
+ data: result
1535
+ });
1536
+ } catch (error) {
1537
+ next(error);
1538
+ }
1539
+ });
1540
+ var workspaces_default = router2;
1541
+
1542
+ // src/routes/marketplace.ts
1543
+ import { Router as Router3 } from "express";
1544
+ init_bundleService();
1545
+ import { existsSync as existsSync6 } from "fs";
1546
+ var router3 = Router3();
1547
+ router3.get("/skills", async (req, res, next) => {
1548
+ try {
1549
+ const { search, page = "1", pageSize = "20" } = req.query;
1550
+ const where = {};
1551
+ if (search) {
1552
+ where.skill = {
1553
+ OR: [
1554
+ { name: { contains: search } },
1555
+ { description: { contains: search } }
1556
+ ]
1557
+ };
1558
+ }
1559
+ const [items, total] = await Promise.all([
1560
+ prisma.marketplaceSkill.findMany({
1561
+ where,
1562
+ include: {
1563
+ skill: true
1564
+ },
1565
+ orderBy: {
1566
+ downloads: "desc"
1567
+ },
1568
+ skip: (parseInt(page) - 1) * parseInt(pageSize),
1569
+ take: parseInt(pageSize)
1570
+ }),
1571
+ prisma.marketplaceSkill.count({ where })
1572
+ ]);
1573
+ res.json({
1574
+ success: true,
1575
+ data: {
1576
+ items,
1577
+ total,
1578
+ page: parseInt(page),
1579
+ pageSize: parseInt(pageSize)
1580
+ }
1581
+ });
1582
+ } catch (error) {
1583
+ next(error);
1584
+ }
1585
+ });
1586
+ router3.get("/skills/:id", async (req, res, next) => {
1587
+ try {
1588
+ const marketplaceSkill = await prisma.marketplaceSkill.findUnique({
1589
+ where: { id: req.params.id },
1590
+ include: {
1591
+ skill: true
1592
+ }
1593
+ });
1594
+ if (!marketplaceSkill) {
1595
+ throw new AppError(ErrorCode.NOT_FOUND, "Marketplace skill not found", 404);
1596
+ }
1597
+ res.json({
1598
+ success: true,
1599
+ data: marketplaceSkill
1600
+ });
1601
+ } catch (error) {
1602
+ next(error);
1603
+ }
1604
+ });
1605
+ router3.get("/download/:id", async (req, res, next) => {
1606
+ try {
1607
+ const marketplaceSkill = await prisma.marketplaceSkill.findUnique({
1608
+ where: { id: req.params.id },
1609
+ include: {
1610
+ skill: true
1611
+ }
1612
+ });
1613
+ if (!marketplaceSkill) {
1614
+ throw new AppError(ErrorCode.NOT_FOUND, "Marketplace skill not found", 404);
1615
+ }
1616
+ if (marketplaceSkill.skill.source === "git" && marketplaceSkill.skill.sourceUrl) {
1617
+ return res.json({
1618
+ success: true,
1619
+ data: {
1620
+ type: "git",
1621
+ sourceUrl: marketplaceSkill.skill.sourceUrl
1622
+ }
1623
+ });
1624
+ }
1625
+ if (marketplaceSkill.bundlePath && existsSync6(marketplaceSkill.bundlePath)) {
1626
+ res.setHeader("Content-Type", "application/gzip");
1627
+ res.setHeader(
1628
+ "Content-Disposition",
1629
+ `attachment; filename="${marketplaceSkill.skill.name}.tar.gz"`
1630
+ );
1631
+ return res.sendFile(marketplaceSkill.bundlePath);
1632
+ }
1633
+ throw new AppError(ErrorCode.NOT_FOUND, "Bundle not available for this skill", 404);
1634
+ } catch (error) {
1635
+ next(error);
1636
+ }
1637
+ });
1638
+ router3.post("/publish", async (req, res, next) => {
1639
+ try {
1640
+ const { skillId, publisherName } = req.body;
1641
+ if (!skillId) {
1642
+ return res.status(400).json({
1643
+ success: false,
1644
+ error: "skillId is required"
1645
+ });
1646
+ }
1647
+ const skill = await prisma.skill.findUnique({
1648
+ where: { id: skillId }
1649
+ });
1650
+ if (!skill) {
1651
+ throw new AppError(ErrorCode.NOT_FOUND, "Skill not found", 404);
1652
+ }
1653
+ const existingEntry = await prisma.marketplaceSkill.findUnique({
1654
+ where: { skillId }
1655
+ });
1656
+ if (existingEntry) {
1657
+ throw new AppError(ErrorCode.ALREADY_EXISTS, "Skill is already published to marketplace", 409);
1658
+ }
1659
+ let bundlePath = null;
1660
+ let bundleSize = null;
1661
+ if (skill.source === "local" && existsSync6(skill.storagePath)) {
1662
+ bundlePath = await bundleService.createBundle(skill.storagePath, skill.name);
1663
+ bundleSize = await bundleService.getBundleSize(bundlePath);
1664
+ }
1665
+ const marketplaceSkill = await prisma.marketplaceSkill.create({
1666
+ data: {
1667
+ skillId,
1668
+ publisherName: publisherName || "Anonymous",
1669
+ bundlePath,
1670
+ bundleSize
1671
+ },
1672
+ include: {
1673
+ skill: true
1674
+ }
1675
+ });
1676
+ res.status(201).json({
1677
+ success: true,
1678
+ data: marketplaceSkill,
1679
+ message: "Skill published to marketplace successfully"
1680
+ });
1681
+ } catch (error) {
1682
+ next(error);
1683
+ }
1684
+ });
1685
+ router3.post("/install/:id", async (req, res, next) => {
1686
+ try {
1687
+ const marketplaceSkill = await prisma.marketplaceSkill.findUnique({
1688
+ where: { id: req.params.id },
1689
+ include: {
1690
+ skill: true
1691
+ }
1692
+ });
1693
+ if (!marketplaceSkill) {
1694
+ throw new AppError(ErrorCode.NOT_FOUND, "Marketplace skill not found", 404);
1695
+ }
1696
+ const sourceSkill = marketplaceSkill.skill;
1697
+ if (sourceSkill.source === "git" && sourceSkill.sourceUrl) {
1698
+ const newSkill = await skillService.createSkillFromGit(
1699
+ sourceSkill.sourceUrl,
1700
+ sourceSkill.description || void 0
1701
+ );
1702
+ await prisma.marketplaceSkill.update({
1703
+ where: { id: req.params.id },
1704
+ data: { downloads: { increment: 1 } }
1705
+ });
1706
+ return res.status(201).json({
1707
+ success: true,
1708
+ data: newSkill,
1709
+ message: "Skill installed from marketplace successfully"
1710
+ });
1711
+ }
1712
+ if (sourceSkill.source === "local" && marketplaceSkill.bundlePath && existsSync6(marketplaceSkill.bundlePath)) {
1713
+ const newSkill = await skillService.createSkillFromBundle(
1714
+ marketplaceSkill.bundlePath,
1715
+ sourceSkill.name,
1716
+ sourceSkill.description || void 0
1717
+ );
1718
+ await prisma.marketplaceSkill.update({
1719
+ where: { id: req.params.id },
1720
+ data: { downloads: { increment: 1 } }
1721
+ });
1722
+ return res.status(201).json({
1723
+ success: true,
1724
+ data: newSkill,
1725
+ message: "Skill installed from marketplace successfully"
1726
+ });
1727
+ }
1728
+ return res.status(400).json({
1729
+ success: false,
1730
+ error: "Cannot install this skill. Bundle not available."
1731
+ });
1732
+ } catch (error) {
1733
+ next(error);
1734
+ }
1735
+ });
1736
+ router3.delete("/unpublish/:skillId", async (req, res, next) => {
1737
+ try {
1738
+ const marketplaceSkill = await prisma.marketplaceSkill.findUnique({
1739
+ where: { skillId: req.params.skillId }
1740
+ });
1741
+ if (!marketplaceSkill) {
1742
+ throw new AppError(ErrorCode.NOT_FOUND, "Skill is not published to marketplace", 404);
1743
+ }
1744
+ await prisma.marketplaceSkill.delete({
1745
+ where: { id: marketplaceSkill.id }
1746
+ });
1747
+ res.json({
1748
+ success: true,
1749
+ message: "Skill unpublished from marketplace successfully"
1750
+ });
1751
+ } catch (error) {
1752
+ next(error);
1753
+ }
1754
+ });
1755
+ var marketplace_default = router3;
1756
+
1757
+ // src/routes/dashboard.ts
1758
+ import { Router as Router4 } from "express";
1759
+ var router4 = Router4();
1760
+ router4.get("/stats", async (req, res, next) => {
1761
+ try {
1762
+ const [totalSkills, totalWorkspaces, totalLinks, marketplaceSkills, recentSkills] = await Promise.all([
1763
+ prisma.skill.count(),
1764
+ prisma.workspace.count(),
1765
+ prisma.skillWorkspace.count(),
1766
+ prisma.marketplaceSkill.count(),
1767
+ prisma.skill.findMany({
1768
+ orderBy: { installDate: "desc" },
1769
+ take: 5,
1770
+ include: {
1771
+ linkedWorkspaces: {
1772
+ include: {
1773
+ workspace: true
1774
+ }
1775
+ }
1776
+ }
1777
+ })
1778
+ ]);
1779
+ res.json({
1780
+ success: true,
1781
+ data: {
1782
+ totalSkills,
1783
+ totalWorkspaces,
1784
+ totalLinks,
1785
+ marketplaceSkills,
1786
+ recentSkills
1787
+ }
1788
+ });
1789
+ } catch (error) {
1790
+ next(error);
1791
+ }
1792
+ });
1793
+ router4.get("/activity", async (req, res, next) => {
1794
+ try {
1795
+ const [recentSkills, recentLinks, recentPublished] = await Promise.all([
1796
+ prisma.skill.findMany({
1797
+ orderBy: { createdAt: "desc" },
1798
+ take: 10,
1799
+ select: {
1800
+ id: true,
1801
+ name: true,
1802
+ source: true,
1803
+ createdAt: true
1804
+ }
1805
+ }),
1806
+ prisma.skillWorkspace.findMany({
1807
+ orderBy: { linkedAt: "desc" },
1808
+ take: 10,
1809
+ include: {
1810
+ skill: { select: { name: true } },
1811
+ workspace: { select: { name: true } }
1812
+ }
1813
+ }),
1814
+ prisma.marketplaceSkill.findMany({
1815
+ orderBy: { publishDate: "desc" },
1816
+ take: 10,
1817
+ include: {
1818
+ skill: { select: { name: true } }
1819
+ }
1820
+ })
1821
+ ]);
1822
+ const activities = [
1823
+ ...recentSkills.map((s) => ({
1824
+ type: "skill_added",
1825
+ date: s.createdAt,
1826
+ data: { skillName: s.name, source: s.source }
1827
+ })),
1828
+ ...recentLinks.map((l) => ({
1829
+ type: "skill_linked",
1830
+ date: l.linkedAt,
1831
+ data: { skillName: l.skill.name, workspaceName: l.workspace.name }
1832
+ })),
1833
+ ...recentPublished.map((p) => ({
1834
+ type: "skill_published",
1835
+ date: p.publishDate,
1836
+ data: { skillName: p.skill.name }
1837
+ }))
1838
+ ].sort((a, b) => b.date.getTime() - a.date.getTime());
1839
+ res.json({
1840
+ success: true,
1841
+ data: activities.slice(0, 20)
1842
+ });
1843
+ } catch (error) {
1844
+ next(error);
1845
+ }
1846
+ });
1847
+ var dashboard_default = router4;
1848
+
1849
+ // src/middleware/logger.ts
1850
+ function requestLogger(req, res, next) {
1851
+ const start = Date.now();
1852
+ res.on("finish", () => {
1853
+ const duration = Date.now() - start;
1854
+ console.log(`${req.method} ${req.path} - ${res.statusCode} - ${duration}ms`);
1855
+ });
1856
+ next();
1857
+ }
1858
+
1859
+ // src/index.ts
1860
+ dotenv2.config();
1861
+ var __filename2 = fileURLToPath2(import.meta.url);
1862
+ var __dirname2 = dirname2(__filename2);
1863
+ var app = express();
1864
+ var PORT = process.env.PORT || 3001;
1865
+ app.use(cors());
1866
+ app.use(express.json());
1867
+ app.use(express.urlencoded({ extended: true }));
1868
+ app.use(requestLogger);
1869
+ var possiblePublicDirs = [
1870
+ join6(__dirname2, "../public"),
1871
+ // Production: dist/index.js -> public
1872
+ join6(__dirname2, "../../public"),
1873
+ // Dev tsx might resolve here
1874
+ join6(process.cwd(), "public"),
1875
+ // Fallback: relative to cwd
1876
+ join6(process.cwd(), "server/public")
1877
+ // Fallback: from root
1878
+ ];
1879
+ var publicDir = possiblePublicDirs.find((dir) => existsSync7(dir));
1880
+ if (publicDir) {
1881
+ app.use(express.static(publicDir));
1882
+ console.log(`\u{1F4C2} Serving static files from: ${publicDir}`);
1883
+ } else {
1884
+ console.warn('\u26A0\uFE0F No public directory found. Run "npm run build" in client first.');
1885
+ }
1886
+ app.use("/api/skills", skills_default);
1887
+ app.use("/api/workspaces", workspaces_default);
1888
+ app.use("/api/marketplace", marketplace_default);
1889
+ app.use("/api/dashboard", dashboard_default);
1890
+ app.get("/health", (req, res) => {
1891
+ res.json({ status: "ok", timestamp: (/* @__PURE__ */ new Date()).toISOString() });
1892
+ });
1893
+ if (publicDir && existsSync7(publicDir)) {
1894
+ app.get("*", (req, res) => {
1895
+ res.sendFile(join6(publicDir, "index.html"));
1896
+ });
1897
+ }
1898
+ app.use(errorHandler);
1899
+ async function initializeStorage() {
1900
+ const skillverseHome = process.env.SKILLVERSE_HOME || join6(process.env.HOME || "", ".skillverse");
1901
+ const skillsDir = process.env.SKILLS_DIR || join6(skillverseHome, "skills");
1902
+ const marketplaceDir = process.env.MARKETPLACE_DIR || join6(skillverseHome, "marketplace");
1903
+ const dirs = [skillverseHome, skillsDir, marketplaceDir];
1904
+ for (const dir of dirs) {
1905
+ if (!existsSync7(dir)) {
1906
+ await mkdir5(dir, { recursive: true });
1907
+ console.log(`Created directory: ${dir}`);
1908
+ }
1909
+ }
1910
+ }
1911
+ async function startServer(port = parseInt(process.env.PORT || "3001")) {
1912
+ try {
1913
+ await initializeStorage();
1914
+ return new Promise((resolve) => {
1915
+ app.listen(port, () => {
1916
+ console.log(`\u{1F680} SkillVerse server running on http://localhost:${port}`);
1917
+ console.log(`\u{1F4C1} Storage: ${process.env.SKILLVERSE_HOME || join6(process.env.HOME || "", ".skillverse")}`);
1918
+ resolve();
1919
+ });
1920
+ });
1921
+ } catch (error) {
1922
+ console.error("Failed to start server:", error);
1923
+ process.exit(1);
1924
+ }
1925
+ }
1926
+ if (process.argv[1] === fileURLToPath2(import.meta.url)) {
1927
+ startServer();
1928
+ }
1929
+
1930
+ // src/bin.ts
1931
+ import { program } from "commander";
1932
+ import open from "open";
1933
+ import { existsSync as existsSync8, readFileSync, writeFileSync } from "fs";
1934
+ import { join as join7 } from "path";
1935
+ import readline from "readline";
1936
+ var { skillverseHome: SKILLVERSE_HOME2 } = config;
1937
+ var AUTH_FILE = join7(SKILLVERSE_HOME2, "auth.json");
1938
+ var CONFIG_FILE = join7(SKILLVERSE_HOME2, "config.json");
1939
+ function getRegistryUrl() {
1940
+ if (existsSync8(CONFIG_FILE)) {
1941
+ const config2 = JSON.parse(readFileSync(CONFIG_FILE, "utf-8"));
1942
+ return config2.registryUrl || "http://localhost:4000";
1943
+ }
1944
+ return process.env.SKILLVERSE_REGISTRY || "http://localhost:4000";
1945
+ }
1946
+ function getAuthToken() {
1947
+ if (existsSync8(AUTH_FILE)) {
1948
+ const auth = JSON.parse(readFileSync(AUTH_FILE, "utf-8"));
1949
+ return auth.token || null;
1950
+ }
1951
+ return null;
1952
+ }
1953
+ function saveAuth(token, user) {
1954
+ writeFileSync(AUTH_FILE, JSON.stringify({ token, user }, null, 2));
1955
+ }
1956
+ async function prompt(question, hidden = false) {
1957
+ const rl = readline.createInterface({
1958
+ input: process.stdin,
1959
+ output: process.stdout
1960
+ });
1961
+ return new Promise((resolve) => {
1962
+ if (hidden) {
1963
+ process.stdout.write(question);
1964
+ let input = "";
1965
+ process.stdin.setRawMode(true);
1966
+ process.stdin.resume();
1967
+ process.stdin.on("data", (char) => {
1968
+ const c = char.toString();
1969
+ if (c === "\n" || c === "\r") {
1970
+ process.stdin.setRawMode(false);
1971
+ process.stdin.pause();
1972
+ console.log();
1973
+ rl.close();
1974
+ resolve(input);
1975
+ } else if (c === "") {
1976
+ process.exit();
1977
+ } else if (c === "\x7F") {
1978
+ input = input.slice(0, -1);
1979
+ } else {
1980
+ input += c;
1981
+ }
1982
+ });
1983
+ } else {
1984
+ rl.question(question, (answer) => {
1985
+ rl.close();
1986
+ resolve(answer);
1987
+ });
1988
+ }
1989
+ });
1990
+ }
1991
+ program.name("skillverse").description("SkillVerse - Local-first skill management platform for AI coding assistants").version("0.1.0");
1992
+ program.command("start").description("Start the SkillVerse local server").option("-p, --port <number>", "Port to run server on", "3001").option("--no-open", "Do not open browser on start").action(async (options) => {
1993
+ const port = parseInt(options.port, 10);
1994
+ console.log("");
1995
+ console.log(" \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557");
1996
+ console.log(" \u2551 \u{1F680} SkillVerse CLI \u2551");
1997
+ console.log(" \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D");
1998
+ console.log("");
1999
+ await startServer(port);
2000
+ if (options.open) {
2001
+ const url = `http://localhost:${port}`;
2002
+ console.log(`
2003
+ \u{1F310} Opening ${url} in your browser...`);
2004
+ open(url).catch((err) => console.error("Failed to open browser:", err));
2005
+ }
2006
+ console.log("\n\u{1F4A1} Press Ctrl+C to stop the server\n");
2007
+ });
2008
+ program.command("login").description("Login to SkillVerse Registry").option("-r, --registry <url>", "Registry URL").action(async (options) => {
2009
+ const registryUrl = options.registry || getRegistryUrl();
2010
+ console.log(`
2011
+ \u{1F510} Logging in to ${registryUrl}...
2012
+ `);
2013
+ const username = await prompt("Username: ");
2014
+ const password = await prompt("Password: ", true);
2015
+ try {
2016
+ const response = await fetch(`${registryUrl}/api/auth/login`, {
2017
+ method: "POST",
2018
+ headers: { "Content-Type": "application/json" },
2019
+ body: JSON.stringify({ username, password })
2020
+ });
2021
+ const data = await response.json();
2022
+ if (!response.ok) {
2023
+ console.error(`
2024
+ \u274C Login failed: ${data.error || "Unknown error"}`);
2025
+ process.exit(1);
2026
+ }
2027
+ saveAuth(data.data.token, data.data.user);
2028
+ console.log(`
2029
+ \u2705 Logged in as ${data.data.user.username}`);
2030
+ } catch (error) {
2031
+ console.error(`
2032
+ \u274C Failed to connect to registry: ${error.message}`);
2033
+ process.exit(1);
2034
+ }
2035
+ });
2036
+ program.command("publish [path]").description("Publish a skill to the Registry").option("-n, --name <name>", "Skill name (defaults to directory name)").option("-d, --description <desc>", "Skill description").option("-r, --registry <url>", "Registry URL").action(async (skillPath, options) => {
2037
+ const token = getAuthToken();
2038
+ if (!token) {
2039
+ console.error("\n\u274C Not logged in. Run `skillverse login` first.");
2040
+ process.exit(1);
2041
+ }
2042
+ const targetPath = skillPath || process.cwd();
2043
+ const registryUrl = options.registry || getRegistryUrl();
2044
+ if (!existsSync8(targetPath)) {
2045
+ console.error(`
2046
+ \u274C Path not found: ${targetPath}`);
2047
+ process.exit(1);
2048
+ }
2049
+ const skillName = options.name || targetPath.split("/").pop();
2050
+ console.log(`
2051
+ \u{1F4E6} Publishing skill "${skillName}" to ${registryUrl}...`);
2052
+ try {
2053
+ const { bundleService: bundleService2 } = await Promise.resolve().then(() => (init_bundleService(), bundleService_exports));
2054
+ const bundlePath = await bundleService2.createBundle(targetPath, skillName);
2055
+ const FormData = (await import("form-data")).default;
2056
+ const form = new FormData();
2057
+ form.append("name", skillName);
2058
+ if (options.description) form.append("description", options.description);
2059
+ form.append("bundle", readFileSync(bundlePath), {
2060
+ filename: `${skillName}.tar.gz`,
2061
+ contentType: "application/gzip"
2062
+ });
2063
+ const response = await fetch(`${registryUrl}/api/skills/publish`, {
2064
+ method: "POST",
2065
+ headers: {
2066
+ "Authorization": `Bearer ${token}`,
2067
+ ...form.getHeaders()
2068
+ },
2069
+ body: form
2070
+ });
2071
+ const data = await response.json();
2072
+ if (!response.ok) {
2073
+ console.error(`
2074
+ \u274C Publish failed: ${data.error || "Unknown error"}`);
2075
+ process.exit(1);
2076
+ }
2077
+ console.log(`
2078
+ \u2705 Published ${skillName}@${data.data.version}`);
2079
+ console.log(` \u{1F4E5} Install: skillverse install ${skillName}`);
2080
+ } catch (error) {
2081
+ console.error(`
2082
+ \u274C Publish failed: ${error.message}`);
2083
+ process.exit(1);
2084
+ }
2085
+ });
2086
+ program.command("search <query>").description("Search for skills in the Registry").option("-r, --registry <url>", "Registry URL").action(async (query, options) => {
2087
+ const registryUrl = options.registry || getRegistryUrl();
2088
+ console.log(`
2089
+ \u{1F50D} Searching for "${query}"...
2090
+ `);
2091
+ try {
2092
+ const response = await fetch(`${registryUrl}/api/skills?search=${encodeURIComponent(query)}`);
2093
+ const data = await response.json();
2094
+ if (!response.ok) {
2095
+ console.error(`\u274C Search failed: ${data.error || "Unknown error"}`);
2096
+ process.exit(1);
2097
+ }
2098
+ if (data.data.items.length === 0) {
2099
+ console.log("No skills found.");
2100
+ return;
2101
+ }
2102
+ console.log(`Found ${data.data.total} skill(s):
2103
+ `);
2104
+ for (const skill of data.data.items) {
2105
+ console.log(` \u{1F4E6} ${skill.name}@${skill.version}`);
2106
+ console.log(` ${skill.description || "No description"}`);
2107
+ console.log(` by ${skill.publisher?.displayName || skill.publisher?.username}`);
2108
+ console.log(` \u{1F4E5} ${skill.downloads} downloads
2109
+ `);
2110
+ }
2111
+ } catch (error) {
2112
+ console.error(`
2113
+ \u274C Failed to search: ${error.message}`);
2114
+ process.exit(1);
2115
+ }
2116
+ });
2117
+ program.command("config").description("Configure SkillVerse settings").option("-r, --registry <url>", "Set default registry URL").action((options) => {
2118
+ const config2 = existsSync8(CONFIG_FILE) ? JSON.parse(readFileSync(CONFIG_FILE, "utf-8")) : {};
2119
+ if (options.registry) {
2120
+ config2.registryUrl = options.registry;
2121
+ writeFileSync(CONFIG_FILE, JSON.stringify(config2, null, 2));
2122
+ console.log(`\u2705 Registry URL set to: ${options.registry}`);
2123
+ } else {
2124
+ console.log("\nCurrent Configuration:");
2125
+ console.log(` Registry: ${config2.registryUrl || getRegistryUrl()}`);
2126
+ }
2127
+ });
2128
+ program.command("install [gitUrl]").description("Install a skill from Git URL").option("-a, --agent <agent>", "Link to agent workspace (vscode, cursor, etc.)").action(async (gitUrl, options) => {
2129
+ if (!gitUrl) {
2130
+ console.error("\u274C Git URL is required (Registry install not yet supported via CLI)");
2131
+ process.exit(1);
2132
+ }
2133
+ try {
2134
+ console.log(`
2135
+ \u2B07\uFE0F Installing skill from ${gitUrl}...`);
2136
+ const skill = await skillService.createSkillFromGit(gitUrl);
2137
+ console.log(`\u2705 Installed skill "${skill.name}"`);
2138
+ if (options.agent) {
2139
+ const projectPath = process.cwd();
2140
+ const type = options.agent;
2141
+ const validAgents = ["vscode", "cursor", "claude-desktop", "codex", "antigravity", "custom"];
2142
+ if (!validAgents.includes(type)) {
2143
+ console.error(`\u274C Invalid agent type. Valid types: ${validAgents.join(", ")}`);
2144
+ process.exit(1);
2145
+ }
2146
+ console.log(`
2147
+ \u{1F517} Linking to ${type} workspace...`);
2148
+ const skillsPath = workspaceService.getSkillsPath(projectPath, type, "project");
2149
+ const existingWorkspace = await workspaceService.findWorkspaceByPath(skillsPath);
2150
+ let workspaceId = existingWorkspace?.id;
2151
+ if (!workspaceId) {
2152
+ console.log(` Creating new workspace for ${type}...`);
2153
+ const newWorkspace = await workspaceService.createWorkspace(
2154
+ `${type}-workspace`,
2155
+ projectPath,
2156
+ type,
2157
+ "project"
2158
+ );
2159
+ workspaceId = newWorkspace.id;
2160
+ }
2161
+ await workspaceService.linkSkillToWorkspace(skill.id, workspaceId);
2162
+ console.log(`\u2705 Linked "${skill.name}" to ${type} workspace at ${skillsPath}`);
2163
+ }
2164
+ } catch (error) {
2165
+ console.error(`
2166
+ \u274C Install failed: ${error.message}`);
2167
+ process.exit(1);
2168
+ }
2169
+ });
2170
+ program.command("add").description("Add a local skill").requiredOption("-p, --path <path>", "Path to skill directory").option("-a, --agent <agent>", "Link to agent workspace").action(async (options) => {
2171
+ const sourcePath = options.path.startsWith("/") ? options.path : join7(process.cwd(), options.path);
2172
+ if (!existsSync8(sourcePath)) {
2173
+ console.error(`\u274C Source path not found: ${sourcePath}`);
2174
+ process.exit(1);
2175
+ }
2176
+ try {
2177
+ console.log(`
2178
+ \u{1F4E6} Adding skill from ${sourcePath}...`);
2179
+ const skill = await skillService.createSkillFromDirectory(sourcePath);
2180
+ console.log(`\u2705 Added skill "${skill.name}"`);
2181
+ if (options.agent) {
2182
+ const projectPath = process.cwd();
2183
+ const type = options.agent;
2184
+ const validAgents = ["vscode", "cursor", "claude-desktop", "codex", "antigravity", "custom"];
2185
+ if (!validAgents.includes(type)) {
2186
+ console.error(`\u274C Invalid agent type. Valid types: ${validAgents.join(", ")}`);
2187
+ process.exit(1);
2188
+ }
2189
+ console.log(`
2190
+ \u{1F517} Linking to ${type} workspace...`);
2191
+ const skillsPath = workspaceService.getSkillsPath(projectPath, type, "project");
2192
+ const existingWorkspace = await workspaceService.findWorkspaceByPath(skillsPath);
2193
+ let workspaceId = existingWorkspace?.id;
2194
+ if (!workspaceId) {
2195
+ console.log(` Creating new workspace for ${type}...`);
2196
+ const newWorkspace = await workspaceService.createWorkspace(
2197
+ `${type}-workspace`,
2198
+ projectPath,
2199
+ type,
2200
+ "project"
2201
+ );
2202
+ workspaceId = newWorkspace.id;
2203
+ }
2204
+ await workspaceService.linkSkillToWorkspace(skill.id, workspaceId);
2205
+ console.log(`\u2705 Linked "${skill.name}" to ${type} workspace at ${skillsPath}`);
2206
+ }
2207
+ } catch (error) {
2208
+ console.error(`
2209
+ \u274C Add failed: ${error.message}`);
2210
+ process.exit(1);
2211
+ }
2212
+ });
2213
+ program.command("list").description("List installed skills").action(async () => {
2214
+ try {
2215
+ const skills = await skillService.getAllSkills();
2216
+ if (skills.length === 0) {
2217
+ console.log("\nNo skills installed.");
2218
+ return;
2219
+ }
2220
+ console.log(`
2221
+ \u{1F4E6} Installed Skills (${skills.length}):
2222
+ `);
2223
+ console.log("Name".padEnd(50) + "Source".padEnd(10) + "Linked");
2224
+ console.log("-".repeat(80));
2225
+ for (const skill of skills) {
2226
+ const source = skill.source;
2227
+ const linkedCount = skill.linkedWorkspaces?.length || 0;
2228
+ const updateStatus = skill.updateAvailable ? "*" : "";
2229
+ console.log(
2230
+ `${skill.name}${updateStatus}`.padEnd(50) + source.padEnd(10) + `${linkedCount} workspace(s)`
2231
+ );
2232
+ }
2233
+ console.log("\n(* indicates update available)");
2234
+ } catch (error) {
2235
+ console.error(`
2236
+ \u274C List failed: ${error.message}`);
2237
+ process.exit(1);
2238
+ }
2239
+ });
2240
+ program.command("remove <name>").description("Remove a skill").action(async (name) => {
2241
+ try {
2242
+ const skill = await skillService.getSkillByName(name);
2243
+ console.log(`
2244
+ \u{1F5D1}\uFE0F Removing skill "${name}"...`);
2245
+ await skillService.deleteSkill(skill.id);
2246
+ console.log(`\u2705 Skill "${name}" removed successfully`);
2247
+ } catch (error) {
2248
+ console.error(`
2249
+ \u274C Remove failed: ${error.message}`);
2250
+ process.exit(1);
2251
+ }
2252
+ });
2253
+ program.parse();
2254
+ if (!process.argv.slice(2).length) {
2255
+ program.parse(["node", "skillverse", "start"]);
2256
+ }
2257
+ //# sourceMappingURL=bin.js.map