@myrialabs/clopen 0.4.5 → 0.4.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.
- package/backend/auth/permissions.ts +14 -1
- package/backend/auth/session-invalidation.test.ts +17 -21
- package/backend/auth/session-invalidation.ts +10 -11
- package/backend/database/migrations/044_create_skills_table.ts +29 -0
- package/backend/database/migrations/index.ts +7 -0
- package/backend/database/queries/index.ts +3 -1
- package/backend/database/queries/skill-queries.ts +105 -0
- package/backend/engine/adapters/claude/models.ts +46 -3
- package/backend/engine/adapters/claude/stream.ts +5 -0
- package/backend/engine/adapters/codex/credential.ts +114 -13
- package/backend/engine/adapters/codex/stream.ts +34 -8
- package/backend/engine/adapters/copilot/stream.ts +4 -0
- package/backend/engine/adapters/opencode/stream.ts +4 -0
- package/backend/engine/adapters/qwen/stream.ts +3 -0
- package/backend/engine/docs/lessons-learned.md +54 -50
- package/backend/files/file-archive.test.ts +86 -26
- package/backend/files/file-archive.ts +214 -134
- package/backend/index.ts +10 -1
- package/backend/mcp/README.md +77 -24
- package/backend/mcp/external/config.ts +82 -101
- package/backend/mcp/external/proxy.ts +202 -0
- package/backend/mcp/index.ts +4 -3
- package/backend/mcp/internal/remote-server.ts +103 -55
- package/backend/skills/index.ts +21 -0
- package/backend/skills/marketplace.ts +172 -0
- package/backend/skills/service.ts +245 -0
- package/backend/skills/spec.ts +214 -0
- package/backend/skills/store.ts +99 -0
- package/backend/skills/sync.ts +187 -0
- package/backend/terminal/index.ts +2 -5
- package/backend/terminal/ptykit.ts +64 -0
- package/backend/tunnel/tunnel-config.ts +1 -1
- package/backend/utils/ws.ts +14 -0
- package/backend/ws/files/write.ts +23 -7
- package/backend/ws/index.ts +5 -1
- package/backend/ws/projects/crud.ts +4 -4
- package/backend/ws/skills/catalog.ts +79 -0
- package/backend/ws/skills/crud.ts +123 -0
- package/backend/ws/skills/index.ts +15 -0
- package/backend/ws/system/operations.ts +23 -0
- package/backend/ws/terminal/index.ts +6 -33
- package/backend/ws/terminal/tunnel.ts +76 -0
- package/dist/assets/index-xrB3zcfA.js +1 -0
- package/dist/assets/main-BXS8bjJ6.css +1 -0
- package/dist/assets/{main-zXKH_C5O.js → main-LBI3a0n5.js} +304 -261
- package/dist/index.html +2 -2
- package/package.json +7 -11
- package/shared/constants/engines.ts +4 -4
- package/shared/utils/logger.ts +1 -0
- package/backend/terminal/helpers.ts +0 -14
- package/backend/terminal/pty-manager.ts +0 -4
- package/backend/terminal/pty-session-manager.ts +0 -349
- package/backend/terminal/stream-manager.ts +0 -300
- package/backend/ws/terminal/access.ts +0 -56
- package/backend/ws/terminal/persistence.ts +0 -145
- package/backend/ws/terminal/session.ts +0 -470
- package/backend/ws/terminal/stream.ts +0 -82
- package/dist/assets/main-gNUEJAC5.css +0 -1
|
@@ -1,26 +1,42 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Remote MCP HTTP
|
|
2
|
+
* Remote MCP HTTP bridge (Streamable HTTP transport, works natively with Bun).
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
* can connect via `type: 'remote'` config instead of spawning a stdio subprocess.
|
|
4
|
+
* Mounts TWO kinds of endpoint for every non-Claude engine:
|
|
6
5
|
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
6
|
+
* - `/mcp` — the INTERNAL `clopen-mcp` bridge. Serves the custom tools
|
|
7
|
+
* defined via `defineServer()`; handlers execute in-process in the main
|
|
8
|
+
* Clopen process (no subprocess, no WebSocket bridge), architecturally
|
|
9
|
+
* identical to how Claude Code uses `createSdkMcpServer()`.
|
|
10
10
|
*
|
|
11
|
-
*
|
|
11
|
+
* - `/mcp/ext/<slug>` — an EXTERNAL proxy. Clopen connects to a user-installed
|
|
12
|
+
* third-party server (`backend/mcp/external/proxy.ts`) and re-exposes its
|
|
13
|
+
* sanitized tools here, so engines never connect to it directly.
|
|
14
|
+
*
|
|
15
|
+
* Both share the session/transport plumbing below; they differ only in the
|
|
16
|
+
* server `handleStreamable` builds per session.
|
|
12
17
|
*/
|
|
13
18
|
|
|
14
19
|
import { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js';
|
|
15
20
|
import { isInitializeRequest } from '@modelcontextprotocol/sdk/types.js';
|
|
16
|
-
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
17
21
|
import { createRemoteMcpServer } from './servers/helper';
|
|
22
|
+
import { createExternalProxyServer } from '../external/proxy';
|
|
18
23
|
import { debug } from '$shared/utils/logger';
|
|
19
24
|
import { authQueries } from '$backend/database/queries';
|
|
20
25
|
import { hashToken } from '$backend/auth/tokens';
|
|
21
26
|
import { getAuthMode } from '$backend/auth/auth-service';
|
|
22
27
|
import { isMcpServiceToken } from './service-token';
|
|
23
28
|
|
|
29
|
+
/** Anything we can `.connect(transport)` — both `McpServer` and low-level `Server`. */
|
|
30
|
+
interface ConnectableServer {
|
|
31
|
+
connect(transport: WebStandardStreamableHTTPServerTransport): Promise<void>;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** A built server plus optional teardown (external proxies close their upstream client). */
|
|
35
|
+
interface BuiltServer {
|
|
36
|
+
server: ConnectableServer;
|
|
37
|
+
close?: () => Promise<void>;
|
|
38
|
+
}
|
|
39
|
+
|
|
24
40
|
// Lazy imports to avoid circular dependencies at module load time
|
|
25
41
|
let _allServers: Parameters<typeof createRemoteMcpServer>[0] | null = null;
|
|
26
42
|
let _enabledConfig: Parameters<typeof createRemoteMcpServer>[1] | null = null;
|
|
@@ -42,8 +58,20 @@ async function getServerDeps() {
|
|
|
42
58
|
/** Active transports keyed by MCP session ID */
|
|
43
59
|
const transports = new Map<string, WebStandardStreamableHTTPServerTransport>();
|
|
44
60
|
|
|
45
|
-
/**
|
|
46
|
-
|
|
61
|
+
/**
|
|
62
|
+
* Per-session teardown for the MCP server bound to it. Internal sessions have
|
|
63
|
+
* no upstream to release (`() => {}`); external-proxy sessions close their
|
|
64
|
+
* upstream client (and any stdio subprocess) here.
|
|
65
|
+
*/
|
|
66
|
+
const sessionCleanups = new Map<string, () => Promise<void>>();
|
|
67
|
+
|
|
68
|
+
/** Forget a session and run its teardown. Idempotent. */
|
|
69
|
+
function disposeSession(sessionId: string): void {
|
|
70
|
+
transports.delete(sessionId);
|
|
71
|
+
const cleanup = sessionCleanups.get(sessionId);
|
|
72
|
+
sessionCleanups.delete(sessionId);
|
|
73
|
+
cleanup?.().catch(error => debug.warn('mcp', `Error tearing down MCP session ${sessionId}:`, error));
|
|
74
|
+
}
|
|
47
75
|
|
|
48
76
|
/**
|
|
49
77
|
* Validate authentication token from request headers.
|
|
@@ -99,31 +127,38 @@ function isAuthRequired(): boolean {
|
|
|
99
127
|
return getAuthMode() !== 'none';
|
|
100
128
|
}
|
|
101
129
|
|
|
130
|
+
/** JSON-RPC error helper for the bridge endpoints. */
|
|
131
|
+
function jsonRpcError(status: number, code: number, message: string, extraHeaders?: Record<string, string>): Response {
|
|
132
|
+
return new Response(JSON.stringify({ jsonrpc: '2.0', error: { code, message }, id: null }), {
|
|
133
|
+
status,
|
|
134
|
+
headers: { 'Content-Type': 'application/json', ...extraHeaders },
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
|
|
102
138
|
/**
|
|
103
|
-
*
|
|
139
|
+
* Shared Streamable-HTTP request core for every bridge endpoint.
|
|
104
140
|
*
|
|
105
|
-
* Mounted at /mcp on the main Elysia server.
|
|
106
141
|
* Follows the Streamable HTTP transport protocol:
|
|
107
|
-
* - POST without session: initialization →
|
|
108
|
-
* - POST with session: route to existing transport
|
|
109
|
-
*
|
|
110
|
-
*
|
|
142
|
+
* - POST without session: initialization → build a fresh server via `makeServer`
|
|
143
|
+
* - POST/GET/DELETE with session: route to the existing transport
|
|
144
|
+
*
|
|
145
|
+
* `makeServer` is the only thing that differs between endpoints: the internal
|
|
146
|
+
* `/mcp` builds the in-process `clopen-mcp` tool server; `/mcp/ext/<slug>`
|
|
147
|
+
* builds an external proxy. A `makeServer` rejection (e.g. an upstream that
|
|
148
|
+
* won't connect) is returned as a JSON-RPC error for THAT endpoint only — it
|
|
149
|
+
* never affects other servers or sessions.
|
|
111
150
|
*/
|
|
112
|
-
|
|
151
|
+
async function handleStreamable(
|
|
152
|
+
request: Request,
|
|
153
|
+
label: string,
|
|
154
|
+
makeServer: () => Promise<BuiltServer>
|
|
155
|
+
): Promise<Response> {
|
|
113
156
|
// Authentication check (skip if authMode is 'none')
|
|
114
157
|
if (isAuthRequired()) {
|
|
115
158
|
const auth = validateAuthToken(request);
|
|
116
159
|
if (!auth) {
|
|
117
|
-
return
|
|
118
|
-
|
|
119
|
-
error: { code: -32001, message: 'Unauthorized: Valid Bearer token required' },
|
|
120
|
-
id: null,
|
|
121
|
-
}), {
|
|
122
|
-
status: 401,
|
|
123
|
-
headers: {
|
|
124
|
-
'Content-Type': 'application/json',
|
|
125
|
-
'WWW-Authenticate': 'Bearer realm="MCP Server"'
|
|
126
|
-
},
|
|
160
|
+
return jsonRpcError(401, -32001, 'Unauthorized: Valid Bearer token required', {
|
|
161
|
+
'WWW-Authenticate': 'Bearer realm="MCP Server"',
|
|
127
162
|
});
|
|
128
163
|
}
|
|
129
164
|
}
|
|
@@ -132,46 +167,41 @@ export async function handleMcpRequest(request: Request): Promise<Response> {
|
|
|
132
167
|
|
|
133
168
|
// Existing session — route to its transport
|
|
134
169
|
if (sessionId && transports.has(sessionId)) {
|
|
135
|
-
|
|
136
|
-
return transport.handleRequest(request);
|
|
170
|
+
return transports.get(sessionId)!.handleRequest(request);
|
|
137
171
|
}
|
|
138
172
|
|
|
139
173
|
// New initialization request — create transport + MCP server
|
|
140
174
|
if (request.method === 'POST') {
|
|
141
|
-
// Parse body to check if it's an init request
|
|
142
175
|
const body = await request.json();
|
|
143
176
|
|
|
144
177
|
if (isInitializeRequest(body)) {
|
|
145
|
-
|
|
178
|
+
let built: BuiltServer;
|
|
179
|
+
try {
|
|
180
|
+
built = await makeServer();
|
|
181
|
+
} catch (error) {
|
|
182
|
+
const message = error instanceof Error ? error.message : 'Failed to start MCP server';
|
|
183
|
+
debug.warn('mcp', `🌐 ${label}: server init failed — ${message}`);
|
|
184
|
+
return jsonRpcError(502, -32000, `MCP server unavailable: ${message}`);
|
|
185
|
+
}
|
|
146
186
|
|
|
147
187
|
const transport = new WebStandardStreamableHTTPServerTransport({
|
|
148
188
|
sessionIdGenerator: () => crypto.randomUUID(),
|
|
149
189
|
onsessioninitialized: (sid) => {
|
|
150
190
|
transports.set(sid, transport);
|
|
151
|
-
|
|
191
|
+
if (built.close) sessionCleanups.set(sid, built.close);
|
|
192
|
+
debug.log('mcp', `🌐 ${label} session initialized: ${sid}`);
|
|
152
193
|
},
|
|
153
194
|
onsessionclosed: (sid) => {
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
debug.log('mcp', `🌐 Remote MCP session closed: ${sid}`);
|
|
195
|
+
disposeSession(sid);
|
|
196
|
+
debug.log('mcp', `🌐 ${label} session closed: ${sid}`);
|
|
157
197
|
},
|
|
158
198
|
});
|
|
159
199
|
|
|
160
200
|
transport.onclose = () => {
|
|
161
|
-
if (transport.sessionId)
|
|
162
|
-
transports.delete(transport.sessionId);
|
|
163
|
-
servers.delete(transport.sessionId);
|
|
164
|
-
}
|
|
201
|
+
if (transport.sessionId) disposeSession(transport.sessionId);
|
|
165
202
|
};
|
|
166
203
|
|
|
167
|
-
|
|
168
|
-
const mcpServer = createRemoteMcpServer(allServers, enabledConfig);
|
|
169
|
-
await mcpServer.connect(transport);
|
|
170
|
-
|
|
171
|
-
// Store server reference for cleanup
|
|
172
|
-
if (transport.sessionId) {
|
|
173
|
-
servers.set(transport.sessionId, mcpServer);
|
|
174
|
-
}
|
|
204
|
+
await built.server.connect(transport);
|
|
175
205
|
|
|
176
206
|
// Handle the initialization request with pre-parsed body
|
|
177
207
|
return transport.handleRequest(request, { parsedBody: body });
|
|
@@ -179,16 +209,29 @@ export async function handleMcpRequest(request: Request): Promise<Response> {
|
|
|
179
209
|
}
|
|
180
210
|
|
|
181
211
|
// Invalid request
|
|
182
|
-
return
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
212
|
+
return jsonRpcError(400, -32000, 'Bad Request: No valid session ID provided');
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* Handle an incoming request to the INTERNAL `clopen-mcp` bridge (`/mcp`).
|
|
217
|
+
* Serves the in-process custom tools defined via `defineServer()`.
|
|
218
|
+
*/
|
|
219
|
+
export async function handleMcpRequest(request: Request): Promise<Response> {
|
|
220
|
+
return handleStreamable(request, 'Remote MCP', async () => {
|
|
221
|
+
const { allServers, enabledConfig } = await getServerDeps();
|
|
222
|
+
return { server: createRemoteMcpServer(allServers, enabledConfig) };
|
|
189
223
|
});
|
|
190
224
|
}
|
|
191
225
|
|
|
226
|
+
/**
|
|
227
|
+
* Handle an incoming request to an EXTERNAL proxy bridge
|
|
228
|
+
* (`/mcp/ext/<slug>`). Clopen connects to the upstream third-party server and
|
|
229
|
+
* re-exposes its (sanitized) tools, so engines never connect to it directly.
|
|
230
|
+
*/
|
|
231
|
+
export async function handleExternalMcpRequest(request: Request, slug: string): Promise<Response> {
|
|
232
|
+
return handleStreamable(request, `External MCP (${slug})`, () => createExternalProxyServer(slug));
|
|
233
|
+
}
|
|
234
|
+
|
|
192
235
|
/**
|
|
193
236
|
* Close all active MCP sessions and transports.
|
|
194
237
|
* Called during graceful server shutdown.
|
|
@@ -202,7 +245,12 @@ export async function closeMcpServer(): Promise<void> {
|
|
|
202
245
|
debug.error('mcp', `Error closing MCP transport ${sessionId}:`, error);
|
|
203
246
|
}
|
|
204
247
|
}
|
|
248
|
+
// Release any upstream proxy clients (and their stdio subprocesses).
|
|
249
|
+
for (const [sessionId, cleanup] of sessionCleanups) {
|
|
250
|
+
try { await cleanup(); }
|
|
251
|
+
catch (error) { debug.error('mcp', `Error closing upstream for MCP session ${sessionId}:`, error); }
|
|
252
|
+
}
|
|
205
253
|
transports.clear();
|
|
206
|
-
|
|
254
|
+
sessionCleanups.clear();
|
|
207
255
|
debug.log('mcp', '🌐 All remote MCP sessions closed');
|
|
208
256
|
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Agent Skills — public facade.
|
|
3
|
+
*
|
|
4
|
+
* The single entry point the rest of the backend imports from. Hides the split
|
|
5
|
+
* between the DB metadata table, the on-disk canonical store, the marketplace
|
|
6
|
+
* providers, and the per-engine sync layer.
|
|
7
|
+
*
|
|
8
|
+
* - SERVICE (`./service`) — CRUD used by the WS layer (Settings → Skills).
|
|
9
|
+
* - MARKETPLACE (`./marketplace`) — browse + install from external providers.
|
|
10
|
+
* - SYNC (`./sync`) — materialize enabled skills for each engine,
|
|
11
|
+
* called at stream start by the adapters.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
export { skillService } from './service';
|
|
15
|
+
export type { SkillDTO, ParsedSkillPreview } from './service';
|
|
16
|
+
|
|
17
|
+
export { listMarketplaceSkills, fetchMarketplaceSkill } from './marketplace';
|
|
18
|
+
export type { MarketplaceSkill, MarketplacePage } from './marketplace';
|
|
19
|
+
|
|
20
|
+
export { syncSkills, syncSkillsAllEngines } from './sync';
|
|
21
|
+
export type { SkillEngine } from './sync';
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Skill marketplace — browse and install skills from the community registry.
|
|
3
|
+
*
|
|
4
|
+
* Source: the `claude-skill-registry` lite index — a single daily-updated JSON
|
|
5
|
+
* catalog hosted as a static file on GitHub Pages. It crawls public GitHub repos
|
|
6
|
+
* for SKILL.md files under `.claude/skills`, scores them, and ships the top
|
|
7
|
+
* ~5000. Being a static file (not the GitHub API) it has no rate limit.
|
|
8
|
+
*
|
|
9
|
+
* The catalog is filtered, deduped, and ordered (verified first, then by stars);
|
|
10
|
+
* `verified` reflects the index's security/install signals. Every install
|
|
11
|
+
* resolves to raw SKILL.md text that the skill service validates against the
|
|
12
|
+
* open spec before writing — no registry output is trusted blindly.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { debug } from '$shared/utils/logger';
|
|
16
|
+
|
|
17
|
+
/** A skill as listed in the marketplace browse view. */
|
|
18
|
+
export interface MarketplaceSkill {
|
|
19
|
+
/** Install-scoped id stored as `marketplace_ref`, e.g. `community:owner/repo/path`. */
|
|
20
|
+
ref: string;
|
|
21
|
+
name: string;
|
|
22
|
+
slug: string;
|
|
23
|
+
description: string;
|
|
24
|
+
stars?: number;
|
|
25
|
+
/** Passed the registry's automated security/install review. */
|
|
26
|
+
verified?: boolean;
|
|
27
|
+
homepage?: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface MarketplacePage {
|
|
31
|
+
skills: MarketplaceSkill[];
|
|
32
|
+
nextCursor: string | null;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** SKILL.md text plus any bundled resource files, ready for the service to write. */
|
|
36
|
+
export interface FetchedSkill {
|
|
37
|
+
skillMd: string;
|
|
38
|
+
resources: { path: string; content: string }[];
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const PAGE_SIZE = 30;
|
|
42
|
+
const COMMUNITY_INDEX_URL = 'https://majiayu000.github.io/claude-skill-registry-core/search-index-lite.json';
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* A lite-index entry. The index uses full keys (`name`/`description`/`install`/
|
|
46
|
+
* `stars`/…); `verified` is derived from its security/install signals.
|
|
47
|
+
*/
|
|
48
|
+
interface CommunityEntry {
|
|
49
|
+
name?: string;
|
|
50
|
+
description?: string;
|
|
51
|
+
install?: string;
|
|
52
|
+
branch?: string;
|
|
53
|
+
stars?: number;
|
|
54
|
+
security_status?: string;
|
|
55
|
+
install_status?: string;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
let communityCache: { entries: CommunityEntry[]; at: number } | null = null;
|
|
59
|
+
|
|
60
|
+
async function getCommunityIndex(): Promise<CommunityEntry[]> {
|
|
61
|
+
if (communityCache && Date.now() - communityCache.at < 10 * 60_000) return communityCache.entries;
|
|
62
|
+
const res = await fetch(COMMUNITY_INDEX_URL, { headers: { 'User-Agent': 'Clopen-Skills' } });
|
|
63
|
+
if (!res.ok) throw new Error(`Failed to load the skills registry (HTTP ${res.status}).`);
|
|
64
|
+
const json = await res.json() as { skills?: CommunityEntry[] } | CommunityEntry[];
|
|
65
|
+
const entries = Array.isArray(json) ? json : (json.skills ?? []);
|
|
66
|
+
communityCache = { entries, at: Date.now() };
|
|
67
|
+
return entries;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Split an install path into `[owner, repo, ...folder]`, dropping a trailing
|
|
72
|
+
* `SKILL.md` — index entries are inconsistent: some point at the folder, some
|
|
73
|
+
* at the file itself.
|
|
74
|
+
*/
|
|
75
|
+
function installParts(installPath: string): string[] {
|
|
76
|
+
const parts = installPath.replace(/^https?:\/\/github\.com\//, '').split('/').filter(Boolean);
|
|
77
|
+
if (parts[parts.length - 1] === 'SKILL.md') parts.pop();
|
|
78
|
+
return parts;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** A usable skill name — some entries are labelled `unknown`; fall back to the folder. */
|
|
82
|
+
function skillName(e: CommunityEntry): string {
|
|
83
|
+
if (e.name && e.name !== 'unknown') return e.name;
|
|
84
|
+
const parts = installParts(e.install ?? '');
|
|
85
|
+
return parts[parts.length - 1] || 'unknown';
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Build a browseable GitHub URL for a community install path (`owner/repo/path`). */
|
|
89
|
+
function homepageUrl(installPath: string, branch?: string): string {
|
|
90
|
+
const [owner, repo, ...rest] = installParts(installPath);
|
|
91
|
+
const base = `https://github.com/${owner}/${repo}`;
|
|
92
|
+
return rest.length > 0 ? `${base}/tree/${branch || 'HEAD'}/${rest.join('/')}` : base;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function mapSkill(e: CommunityEntry): MarketplaceSkill {
|
|
96
|
+
const name = skillName(e);
|
|
97
|
+
return {
|
|
98
|
+
ref: `community:${e.install}`,
|
|
99
|
+
name,
|
|
100
|
+
slug: name,
|
|
101
|
+
description: e.description ?? '',
|
|
102
|
+
stars: e.stars,
|
|
103
|
+
verified: e.security_status === 'passed' && e.install_status === 'known_good',
|
|
104
|
+
homepage: homepageUrl(e.install!, e.branch)
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Resolve a community install path (`owner/repo/path/to/skill`) to a raw SKILL.md URL. */
|
|
109
|
+
function rawSkillUrl(installPath: string): string | null {
|
|
110
|
+
const [owner, repo, ...rest] = installParts(installPath);
|
|
111
|
+
if (!owner || !repo) return null;
|
|
112
|
+
const path = rest.length > 0 ? `${rest.join('/')}/SKILL.md` : 'SKILL.md';
|
|
113
|
+
return `https://raw.githubusercontent.com/${owner}/${repo}/HEAD/${path}`;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Collapse entries that are the same skill in the same repo but copied into
|
|
118
|
+
* several folders (e.g. `development/`, `.claude/skills/`, `data/`). Same name
|
|
119
|
+
* across *different* repos is kept — those are distinct implementations.
|
|
120
|
+
*/
|
|
121
|
+
function dedupe(entries: CommunityEntry[]): CommunityEntry[] {
|
|
122
|
+
const isCanonical = (install?: string) => (install?.includes('/.claude/skills/') ? 0 : 1);
|
|
123
|
+
const best = new Map<string, CommunityEntry>();
|
|
124
|
+
for (const e of entries) {
|
|
125
|
+
if (!e.install) continue;
|
|
126
|
+
const parts = installParts(e.install);
|
|
127
|
+
if (parts.length < 2) continue;
|
|
128
|
+
const key = `${parts[0]}/${parts[1]}::${skillName(e).toLowerCase()}`;
|
|
129
|
+
const current = best.get(key);
|
|
130
|
+
if (!current || isCanonical(e.install) < isCanonical(current.install)) best.set(key, e);
|
|
131
|
+
}
|
|
132
|
+
return [...best.values()];
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// ---------------------------------------------------------------------------
|
|
136
|
+
// Public facade
|
|
137
|
+
// ---------------------------------------------------------------------------
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Browse the catalog (paginated, name/description filtered). Verified skills
|
|
141
|
+
* sort first, then by stars.
|
|
142
|
+
*/
|
|
143
|
+
export async function listMarketplaceSkills(
|
|
144
|
+
query: string,
|
|
145
|
+
cursor: string | null
|
|
146
|
+
): Promise<MarketplacePage> {
|
|
147
|
+
debug.log('skills', `🛒 marketplace list q="${query}" cursor=${cursor ?? '-'}`);
|
|
148
|
+
let skills = dedupe(await getCommunityIndex()).map(mapSkill);
|
|
149
|
+
|
|
150
|
+
const q = query.trim().toLowerCase();
|
|
151
|
+
if (q) skills = skills.filter(s => `${s.name} ${s.description}`.toLowerCase().includes(q));
|
|
152
|
+
skills.sort((a, b) =>
|
|
153
|
+
(a.verified ? 0 : 1) - (b.verified ? 0 : 1) ||
|
|
154
|
+
(b.stars ?? 0) - (a.stars ?? 0) ||
|
|
155
|
+
a.name.localeCompare(b.name)
|
|
156
|
+
);
|
|
157
|
+
|
|
158
|
+
const offset = cursor ? Number(cursor) || 0 : 0;
|
|
159
|
+
const page = skills.slice(offset, offset + PAGE_SIZE);
|
|
160
|
+
const next = offset + PAGE_SIZE < skills.length ? String(offset + PAGE_SIZE) : null;
|
|
161
|
+
return { skills: page, nextCursor: next };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** Download a skill's SKILL.md from the registry for installation. */
|
|
165
|
+
export async function fetchMarketplaceSkill(ref: string): Promise<FetchedSkill> {
|
|
166
|
+
if (!ref.startsWith('community:')) throw new Error(`Unknown marketplace reference: ${ref}`);
|
|
167
|
+
const url = rawSkillUrl(ref.slice('community:'.length));
|
|
168
|
+
if (!url) throw new Error('This skill has no resolvable SKILL.md location.');
|
|
169
|
+
const res = await fetch(url);
|
|
170
|
+
if (!res.ok) throw new Error(`Could not download SKILL.md (HTTP ${res.status}).`);
|
|
171
|
+
return { skillMd: await res.text(), resources: [] };
|
|
172
|
+
}
|
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Skill service — orchestrates the DB metadata table and the on-disk canonical
|
|
3
|
+
* store for the Settings → Skills CRUD surface. The WS layer calls these; they
|
|
4
|
+
* keep the `skills` table and `{clopenDir}/skills/<slug>/` in lockstep.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { skillQueries, type SkillRow, type SkillSource } from '$backend/database/queries';
|
|
8
|
+
import { debug } from '$shared/utils/logger';
|
|
9
|
+
import {
|
|
10
|
+
parseSkillMd,
|
|
11
|
+
serializeSkillMd,
|
|
12
|
+
validateFrontmatter,
|
|
13
|
+
slugifySkillName,
|
|
14
|
+
type ParsedSkill
|
|
15
|
+
} from './spec';
|
|
16
|
+
import {
|
|
17
|
+
writeSkillMd,
|
|
18
|
+
writeSkillResource,
|
|
19
|
+
readSkillMd,
|
|
20
|
+
deleteSkillDir,
|
|
21
|
+
skillDirExists
|
|
22
|
+
} from './store';
|
|
23
|
+
import { fetchMarketplaceSkill } from './marketplace';
|
|
24
|
+
|
|
25
|
+
/** A skill as surfaced to the Settings UI (DB metadata + on-disk presence). */
|
|
26
|
+
export interface SkillDTO {
|
|
27
|
+
id: number;
|
|
28
|
+
slug: string;
|
|
29
|
+
name: string;
|
|
30
|
+
description: string;
|
|
31
|
+
source: SkillSource;
|
|
32
|
+
marketplaceRef: string | null;
|
|
33
|
+
version: string | null;
|
|
34
|
+
license: string | null;
|
|
35
|
+
enabled: boolean;
|
|
36
|
+
/** False when the DB row exists but its SKILL.md is missing on disk. */
|
|
37
|
+
present: boolean;
|
|
38
|
+
createdAt: string;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** A previewed skill parsed from pasted/imported SKILL.md text. */
|
|
42
|
+
export interface ParsedSkillPreview {
|
|
43
|
+
name: string;
|
|
44
|
+
description: string;
|
|
45
|
+
license: string | null;
|
|
46
|
+
body: string;
|
|
47
|
+
warnings: string[];
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function toDTO(row: SkillRow, present: boolean): SkillDTO {
|
|
51
|
+
return {
|
|
52
|
+
id: row.id,
|
|
53
|
+
slug: row.slug,
|
|
54
|
+
name: row.name,
|
|
55
|
+
description: row.description,
|
|
56
|
+
source: row.source,
|
|
57
|
+
marketplaceRef: row.marketplace_ref,
|
|
58
|
+
version: row.version,
|
|
59
|
+
license: row.license,
|
|
60
|
+
enabled: row.is_enabled === 1,
|
|
61
|
+
present,
|
|
62
|
+
createdAt: row.created_at
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Derive a slug that doesn't collide with an existing skill. */
|
|
67
|
+
function uniqueSlug(base: string): string {
|
|
68
|
+
const root = slugifySkillName(base);
|
|
69
|
+
if (!skillQueries.getBySlug(root)) return root;
|
|
70
|
+
for (let i = 2; i < 1000; i++) {
|
|
71
|
+
const candidate = `${root}-${i}`.slice(0, 64).replace(/-+$/g, '');
|
|
72
|
+
if (!skillQueries.getBySlug(candidate)) return candidate;
|
|
73
|
+
}
|
|
74
|
+
return slugifySkillName(`${root}-${Date.now()}`);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Throw a single combined error if frontmatter validation fails. */
|
|
78
|
+
function assertValid(skill: ParsedSkill, expectedName: string): void {
|
|
79
|
+
const result = validateFrontmatter(skill.frontmatter, expectedName);
|
|
80
|
+
if (!result.valid) throw new Error(result.errors.join(' '));
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export const skillService = {
|
|
84
|
+
async list(): Promise<SkillDTO[]> {
|
|
85
|
+
const rows = skillQueries.getAll();
|
|
86
|
+
const presence = await Promise.all(rows.map(r => skillDirExists(r.slug)));
|
|
87
|
+
return rows.map((row, i) => toDTO(row, presence[i]));
|
|
88
|
+
},
|
|
89
|
+
|
|
90
|
+
async get(id: number): Promise<{ skill: SkillDTO; body: string } | null> {
|
|
91
|
+
const row = skillQueries.getById(id);
|
|
92
|
+
if (!row) return null;
|
|
93
|
+
const raw = await readSkillMd(row.slug);
|
|
94
|
+
const body = raw ? parseSkillMd(raw).body : '';
|
|
95
|
+
return { skill: toDTO(row, raw !== null), body };
|
|
96
|
+
},
|
|
97
|
+
|
|
98
|
+
/** Create a skill from in-app editor fields (name + description + markdown body). */
|
|
99
|
+
async create(input: { name: string; description: string; body: string; license?: string | null }): Promise<SkillDTO> {
|
|
100
|
+
const slug = uniqueSlug(input.name);
|
|
101
|
+
const skill: ParsedSkill = {
|
|
102
|
+
frontmatter: {
|
|
103
|
+
name: slug,
|
|
104
|
+
description: input.description.trim(),
|
|
105
|
+
license: input.license?.trim() || undefined,
|
|
106
|
+
extra: {}
|
|
107
|
+
},
|
|
108
|
+
body: input.body
|
|
109
|
+
};
|
|
110
|
+
assertValid(skill, slug);
|
|
111
|
+
await writeSkillMd(slug, serializeSkillMd(skill));
|
|
112
|
+
const row = skillQueries.insert({
|
|
113
|
+
slug,
|
|
114
|
+
name: input.name.trim(),
|
|
115
|
+
description: input.description.trim(),
|
|
116
|
+
source: 'custom',
|
|
117
|
+
license: input.license?.trim() || null
|
|
118
|
+
});
|
|
119
|
+
debug.log('skills', `📦 Created skill: ${slug}`);
|
|
120
|
+
return toDTO(row, true);
|
|
121
|
+
},
|
|
122
|
+
|
|
123
|
+
/** Update an existing skill's editable fields and rewrite its SKILL.md. */
|
|
124
|
+
async update(id: number, input: { name: string; description: string; body: string; license?: string | null }): Promise<SkillDTO> {
|
|
125
|
+
const row = skillQueries.getById(id);
|
|
126
|
+
if (!row) throw new Error('Skill not found');
|
|
127
|
+
// `name` (frontmatter) must keep matching the folder slug — only the
|
|
128
|
+
// display name, description, license and body are editable here.
|
|
129
|
+
const skill: ParsedSkill = {
|
|
130
|
+
frontmatter: {
|
|
131
|
+
name: row.slug,
|
|
132
|
+
description: input.description.trim(),
|
|
133
|
+
license: input.license?.trim() || undefined,
|
|
134
|
+
extra: {}
|
|
135
|
+
},
|
|
136
|
+
body: input.body
|
|
137
|
+
};
|
|
138
|
+
assertValid(skill, row.slug);
|
|
139
|
+
await writeSkillMd(row.slug, serializeSkillMd(skill));
|
|
140
|
+
skillQueries.updateMeta(id, input.name.trim(), input.description.trim(), input.license?.trim() || null);
|
|
141
|
+
debug.log('skills', `🔧 Updated skill: ${row.slug}`);
|
|
142
|
+
return toDTO(skillQueries.getById(id)!, true);
|
|
143
|
+
},
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Parse pasted/uploaded SKILL.md text into a reviewable preview. Nothing is
|
|
147
|
+
* persisted — the UI shows the result, then calls `import` to commit it.
|
|
148
|
+
*/
|
|
149
|
+
parsePreview(raw: string): ParsedSkillPreview {
|
|
150
|
+
const parsed = parseSkillMd(raw);
|
|
151
|
+
const warnings: string[] = [];
|
|
152
|
+
const result = validateFrontmatter(parsed.frontmatter, undefined);
|
|
153
|
+
if (!result.valid) warnings.push(...result.errors);
|
|
154
|
+
return {
|
|
155
|
+
name: parsed.frontmatter.name,
|
|
156
|
+
description: parsed.frontmatter.description,
|
|
157
|
+
license: parsed.frontmatter.license ?? null,
|
|
158
|
+
body: parsed.body,
|
|
159
|
+
warnings
|
|
160
|
+
};
|
|
161
|
+
},
|
|
162
|
+
|
|
163
|
+
/** Persist a skill from pasted/uploaded SKILL.md text. */
|
|
164
|
+
async import(raw: string): Promise<SkillDTO> {
|
|
165
|
+
const parsed = parseSkillMd(raw);
|
|
166
|
+
const displayName = parsed.frontmatter.name || 'Imported skill';
|
|
167
|
+
const slug = uniqueSlug(parsed.frontmatter.name || displayName);
|
|
168
|
+
// Re-key the frontmatter `name` to the de-duped slug so it matches the folder.
|
|
169
|
+
parsed.frontmatter.name = slug;
|
|
170
|
+
assertValid(parsed, slug);
|
|
171
|
+
await writeSkillMd(slug, serializeSkillMd(parsed));
|
|
172
|
+
const row = skillQueries.insert({
|
|
173
|
+
slug,
|
|
174
|
+
name: displayName,
|
|
175
|
+
description: parsed.frontmatter.description,
|
|
176
|
+
source: 'imported',
|
|
177
|
+
license: parsed.frontmatter.license ?? null
|
|
178
|
+
});
|
|
179
|
+
debug.log('skills', `📥 Imported skill: ${slug}`);
|
|
180
|
+
return toDTO(row, true);
|
|
181
|
+
},
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Fetch and parse a marketplace skill for review before install — nothing is
|
|
185
|
+
* persisted. Powers the install modal's prefilled detail form.
|
|
186
|
+
*/
|
|
187
|
+
async previewInstall(ref: string): Promise<{ name: string; description: string; license: string | null; body: string }> {
|
|
188
|
+
const fetched = await fetchMarketplaceSkill(ref);
|
|
189
|
+
const parsed = parseSkillMd(fetched.skillMd);
|
|
190
|
+
return {
|
|
191
|
+
name: parsed.frontmatter.name || ref.split(/[:/]/).pop() || 'Skill',
|
|
192
|
+
description: parsed.frontmatter.description,
|
|
193
|
+
license: parsed.frontmatter.license ?? null,
|
|
194
|
+
body: parsed.body
|
|
195
|
+
};
|
|
196
|
+
},
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Install a skill from a marketplace provider: download its SKILL.md (+ any
|
|
200
|
+
* bundled resources), validate against the spec, and persist it under a
|
|
201
|
+
* de-duped slug with `source: 'marketplace'`. Optional `override` fields (from
|
|
202
|
+
* the install modal) replace the fetched name/description/license/body.
|
|
203
|
+
*/
|
|
204
|
+
async install(ref: string, override?: { name?: string; description?: string; license?: string | null; body?: string }): Promise<SkillDTO> {
|
|
205
|
+
const fetched = await fetchMarketplaceSkill(ref);
|
|
206
|
+
const parsed = parseSkillMd(fetched.skillMd);
|
|
207
|
+
if (override?.description !== undefined) parsed.frontmatter.description = override.description.trim();
|
|
208
|
+
if (override?.license !== undefined) parsed.frontmatter.license = override.license?.trim() || undefined;
|
|
209
|
+
if (override?.body !== undefined) parsed.body = override.body;
|
|
210
|
+
const displayName = override?.name?.trim() || parsed.frontmatter.name || ref.split(/[:/]/).pop() || 'Skill';
|
|
211
|
+
const slug = uniqueSlug(parsed.frontmatter.name || displayName);
|
|
212
|
+
parsed.frontmatter.name = slug;
|
|
213
|
+
assertValid(parsed, slug);
|
|
214
|
+
await writeSkillMd(slug, serializeSkillMd(parsed));
|
|
215
|
+
for (const resource of fetched.resources) {
|
|
216
|
+
await writeSkillResource(slug, resource.path, resource.content);
|
|
217
|
+
}
|
|
218
|
+
const row = skillQueries.insert({
|
|
219
|
+
slug,
|
|
220
|
+
name: displayName,
|
|
221
|
+
description: parsed.frontmatter.description,
|
|
222
|
+
source: 'marketplace',
|
|
223
|
+
marketplaceRef: ref,
|
|
224
|
+
version: parsed.frontmatter.metadata?.version ?? null,
|
|
225
|
+
license: parsed.frontmatter.license ?? null
|
|
226
|
+
});
|
|
227
|
+
debug.log('skills', `📥 Installed marketplace skill: ${slug} (${ref})`);
|
|
228
|
+
return toDTO(row, true);
|
|
229
|
+
},
|
|
230
|
+
|
|
231
|
+
toggle(id: number, enabled: boolean): SkillDTO {
|
|
232
|
+
const row = skillQueries.getById(id);
|
|
233
|
+
if (!row) throw new Error('Skill not found');
|
|
234
|
+
skillQueries.setEnabled(id, enabled);
|
|
235
|
+
return toDTO(skillQueries.getById(id)!, true);
|
|
236
|
+
},
|
|
237
|
+
|
|
238
|
+
async remove(id: number): Promise<void> {
|
|
239
|
+
const row = skillQueries.getById(id);
|
|
240
|
+
if (!row) throw new Error('Skill not found');
|
|
241
|
+
await deleteSkillDir(row.slug);
|
|
242
|
+
skillQueries.remove(id);
|
|
243
|
+
debug.log('skills', `🗑️ Deleted skill: ${row.slug}`);
|
|
244
|
+
}
|
|
245
|
+
};
|