@myrialabs/clopen 0.4.4 → 0.4.6

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 (53) hide show
  1. package/backend/auth/permissions.ts +15 -1
  2. package/backend/database/migrations/044_create_skills_table.ts +29 -0
  3. package/backend/database/migrations/index.ts +7 -0
  4. package/backend/database/queries/index.ts +3 -1
  5. package/backend/database/queries/skill-queries.ts +105 -0
  6. package/backend/engine/adapters/claude/stream.ts +5 -0
  7. package/backend/engine/adapters/codex/credential.ts +120 -13
  8. package/backend/engine/adapters/codex/stream.ts +34 -8
  9. package/backend/engine/adapters/copilot/stream.ts +4 -0
  10. package/backend/engine/adapters/opencode/stream.ts +4 -0
  11. package/backend/engine/adapters/qwen/stream.ts +3 -0
  12. package/backend/engine/docs/lessons-learned.md +54 -50
  13. package/backend/git/git-service.ts +40 -0
  14. package/backend/index.ts +10 -1
  15. package/backend/mcp/README.md +77 -24
  16. package/backend/mcp/external/config.ts +82 -101
  17. package/backend/mcp/external/parse.test.ts +190 -0
  18. package/backend/mcp/external/parse.ts +293 -0
  19. package/backend/mcp/external/proxy.ts +202 -0
  20. package/backend/mcp/index.ts +6 -3
  21. package/backend/mcp/internal/remote-server.ts +103 -55
  22. package/backend/skills/index.ts +21 -0
  23. package/backend/skills/marketplace.ts +172 -0
  24. package/backend/skills/service.ts +245 -0
  25. package/backend/skills/spec.ts +214 -0
  26. package/backend/skills/store.ts +99 -0
  27. package/backend/skills/sync.ts +187 -0
  28. package/backend/snapshot/gitignore.ts +230 -7
  29. package/backend/snapshot/helpers.ts +34 -10
  30. package/backend/ws/files/read.ts +10 -1
  31. package/backend/ws/git/branch-name.ts +20 -4
  32. package/backend/ws/git/branch.ts +66 -11
  33. package/backend/ws/git/commit-message.ts +18 -3
  34. package/backend/ws/git/commit.ts +50 -16
  35. package/backend/ws/git/conflict.ts +47 -5
  36. package/backend/ws/git/diff.ts +38 -4
  37. package/backend/ws/git/log.ts +22 -2
  38. package/backend/ws/git/remote.ts +82 -33
  39. package/backend/ws/git/staging.ts +39 -9
  40. package/backend/ws/git/status.ts +52 -0
  41. package/backend/ws/index.ts +5 -1
  42. package/backend/ws/mcp/crud.ts +30 -1
  43. package/backend/ws/skills/catalog.ts +79 -0
  44. package/backend/ws/skills/crud.ts +123 -0
  45. package/backend/ws/skills/index.ts +15 -0
  46. package/backend/ws/snapshot/timeline.ts +1 -1
  47. package/dist/assets/main-BkMrek4_.css +1 -0
  48. package/dist/assets/{main-AqTMkV9D.js → main-TYNK6Orl.js} +332 -295
  49. package/dist/index.html +2 -2
  50. package/package.json +1 -1
  51. package/shared/types/git.ts +20 -0
  52. package/shared/utils/logger.ts +1 -0
  53. package/dist/assets/main-DJf71Zum.css +0 -1
@@ -10,7 +10,8 @@
10
10
  * through the `/mcp` remote bridge (namespace `clopen-mcp`).
11
11
  * - EXTERNAL (`./external`) — servers the user installs from the official
12
12
  * MCP registry, stored in the `mcp_servers` table. Each occupies its own
13
- * `<slug>` namespace and is connected to directly by the engine.
13
+ * `<slug>` namespace and is proxied through the `/mcp/ext/<slug>` bridge
14
+ * (`./external/proxy.ts`) — the engine talks to Clopen, not the upstream.
14
15
  *
15
16
  * Adapters call `getEnabledMcpServers()` / `getXxxMcpConfig()` /
16
17
  * `resolveOpenCodeToolName()` here and receive the COMBINED view. The internal
@@ -57,8 +58,8 @@ export {
57
58
  // Internal server implementations + registries
58
59
  export * from './internal/servers';
59
60
 
60
- // Remote MCP HTTP bridge (serves internal tools to non-Claude engines)
61
- export { handleMcpRequest, closeMcpServer } from './internal/remote-server';
61
+ // Remote MCP HTTP bridge (serves internal tools + external proxies to non-Claude engines)
62
+ export { handleMcpRequest, handleExternalMcpRequest, closeMcpServer } from './internal/remote-server';
62
63
 
63
64
  // Project context service for MCP tool handlers
64
65
  export { projectContextService } from './internal/project-context';
@@ -87,6 +88,8 @@ export {
87
88
  loadOAuth
88
89
  } from './external/oauth';
89
90
  export type { CatalogServer, CatalogEnvVar, CatalogPage, ResolvedExternalServer } from './external/types';
91
+ export { parseMcpConfig } from './external/parse';
92
+ export type { ParsedMcpServer, ParsedField, ParseResult } from './external/parse';
90
93
 
91
94
  // ---------------------------------------------------------------------------
92
95
  // Merged config builders (internal `clopen-mcp` + external bare `<slug>`)
@@ -1,26 +1,42 @@
1
1
  /**
2
- * Remote MCP HTTP Server for Open Code
2
+ * Remote MCP HTTP bridge (Streamable HTTP transport, works natively with Bun).
3
3
  *
4
- * Serves custom MCP tools over HTTP (Streamable HTTP transport) so Open Code
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
- * Tool handlers execute directly in the main Clopen process — no subprocess,
8
- * no WebSocket bridge. This is architecturally identical to how Claude Code
9
- * uses in-process MCP servers via createSdkMcpServer().
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
- * Transport: WebStandardStreamableHTTPServerTransport (works natively with Bun)
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
- /** Active MCP servers keyed by MCP session ID */
46
- const servers = new Map<string, McpServer>();
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
- * Handle an incoming MCP HTTP request (GET/POST/DELETE).
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 → create new transport + server
108
- * - POST with session: route to existing transport
109
- * - GET with session: SSE stream for server notifications
110
- * - DELETE with session: close session
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
- export async function handleMcpRequest(request: Request): Promise<Response> {
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 new Response(JSON.stringify({
118
- jsonrpc: '2.0',
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
- const transport = transports.get(sessionId)!;
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
- const { allServers, enabledConfig } = await getServerDeps();
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
- debug.log('mcp', `🌐 Remote MCP session initialized: ${sid}`);
191
+ if (built.close) sessionCleanups.set(sid, built.close);
192
+ debug.log('mcp', `🌐 ${label} session initialized: ${sid}`);
152
193
  },
153
194
  onsessionclosed: (sid) => {
154
- transports.delete(sid);
155
- servers.delete(sid);
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
- // Create a fresh MCP server with all enabled tools (in-process handlers)
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 new Response(JSON.stringify({
183
- jsonrpc: '2.0',
184
- error: { code: -32000, message: 'Bad Request: No valid session ID provided' },
185
- id: null,
186
- }), {
187
- status: 400,
188
- headers: { 'Content-Type': 'application/json' },
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
- servers.clear();
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
+ }