@myrialabs/clopen 0.4.39 → 0.4.41

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 (173) hide show
  1. package/.env.example +1 -1
  2. package/backend/artifacts/detect.ts +15 -3
  3. package/backend/artifacts/generate.ts +2 -2
  4. package/backend/artifacts/index.ts +12 -4
  5. package/backend/artifacts/markers.ts +24 -1
  6. package/backend/artifacts/matrix.ts +47 -3
  7. package/backend/artifacts/sync.test.ts +3 -3
  8. package/backend/artifacts/sync.ts +8 -20
  9. package/backend/artifacts/types.ts +9 -3
  10. package/backend/auth/permissions.ts +29 -11
  11. package/backend/auth/session-cleanup.ts +10 -1
  12. package/backend/auth/tokens.ts +9 -1
  13. package/backend/chat/stream-manager.ts +42 -0
  14. package/backend/database/crypto/secret-columns.ts +5 -1
  15. package/backend/database/migrations/078_create_worktree_branch_tables.ts +158 -0
  16. package/backend/database/migrations/079_merge_commands_into_skills.ts +222 -0
  17. package/backend/database/migrations/080_create_file_shares.ts +111 -0
  18. package/backend/database/migrations/081_create_push_subscriptions.ts +32 -0
  19. package/backend/database/migrations/index.ts +28 -0
  20. package/backend/database/queries/file-share-queries.ts +163 -0
  21. package/backend/database/queries/index.ts +12 -4
  22. package/backend/database/queries/profile-queries.ts +5 -3
  23. package/backend/database/queries/push-subscription-queries.test.ts +90 -0
  24. package/backend/database/queries/push-subscription-queries.ts +99 -0
  25. package/backend/database/queries/skill-queries.ts +96 -18
  26. package/backend/database/queries/worktree-branch-queries.ts +331 -0
  27. package/backend/db-client/cloning.test.ts +161 -0
  28. package/backend/db-client/cloning.ts +672 -0
  29. package/backend/db-client/connection-url.test.ts +117 -0
  30. package/backend/db-client/connection-url.ts +126 -0
  31. package/backend/db-client/drivers/mongodb.ts +2 -14
  32. package/backend/db-client/drivers/mysql.ts +2 -8
  33. package/backend/db-client/drivers/postgres.ts +10 -13
  34. package/backend/db-client/drivers/redis.ts +2 -6
  35. package/backend/db-client/env/detect.ts +438 -0
  36. package/backend/db-client/env/diff.ts +94 -0
  37. package/backend/db-client/env/env.test.ts +574 -0
  38. package/backend/db-client/env/index.ts +15 -0
  39. package/backend/db-client/env/naming.ts +202 -0
  40. package/backend/db-client/env/service.ts +487 -0
  41. package/backend/db-client/integrations/index.ts +7 -0
  42. package/backend/db-client/integrations/links.ts +41 -10
  43. package/backend/db-client/providers/neon/adapter.ts +522 -0
  44. package/backend/db-client/providers/neon/api-types.ts +182 -0
  45. package/backend/db-client/providers/neon/client.ts +298 -0
  46. package/backend/db-client/providers/neon/endpoints.test.ts +201 -0
  47. package/backend/db-client/providers/neon/endpoints.ts +314 -0
  48. package/backend/db-client/providers/neon/list.test.ts +181 -0
  49. package/backend/db-client/providers/supabase/adapter.ts +25 -2
  50. package/backend/db-client/providers/types.ts +57 -0
  51. package/backend/engine/adapters/claude/stream.ts +2 -1
  52. package/backend/engine/adapters/cline/stream.ts +3 -3
  53. package/backend/engine/adapters/codex/stream.ts +3 -3
  54. package/backend/engine/adapters/copilot/stream.ts +3 -3
  55. package/backend/engine/adapters/cursor/stream.ts +25 -3
  56. package/backend/engine/adapters/opencode/stream.ts +4 -6
  57. package/backend/engine/adapters/pi/stream.ts +2 -2
  58. package/backend/engine/adapters/qwen/stream.ts +2 -2
  59. package/backend/engine/artifact-sync.ts +26 -20
  60. package/backend/engine/docs/artifacts.md +81 -22
  61. package/backend/engine/docs/quick-reference.md +2 -1
  62. package/backend/engine/resolve-model.test.ts +108 -0
  63. package/backend/engine/resolve-model.ts +53 -10
  64. package/backend/engine/structured-helpers.ts +22 -0
  65. package/backend/env-files/discovery.ts +48 -0
  66. package/backend/env-files/edit.ts +213 -0
  67. package/backend/env-files/env-files.test.ts +515 -0
  68. package/backend/env-files/git.ts +27 -0
  69. package/backend/env-files/index.ts +44 -0
  70. package/backend/env-files/keys.ts +69 -0
  71. package/backend/env-files/parse.ts +157 -0
  72. package/backend/env-files/write.ts +229 -0
  73. package/backend/files/file-shares.ts +369 -0
  74. package/backend/files/path-browsing.ts +27 -21
  75. package/backend/http/files-shared.test.ts +505 -0
  76. package/backend/http/files-shared.ts +351 -0
  77. package/backend/http/push.ts +150 -0
  78. package/backend/index.ts +8 -0
  79. package/backend/instructions/index.ts +1 -1
  80. package/backend/instructions/sync.ts +30 -6
  81. package/backend/integrations/health.ts +18 -4
  82. package/backend/integrations/projections/types.ts +9 -2
  83. package/backend/integrations/registry/index.ts +3 -0
  84. package/backend/integrations/registry/providers/context7.ts +1 -0
  85. package/backend/integrations/registry/providers/firecrawl.ts +1 -0
  86. package/backend/integrations/registry/providers/github.ts +1 -0
  87. package/backend/integrations/registry/providers/neon.ts +55 -0
  88. package/backend/integrations/registry/providers/supabase.ts +1 -0
  89. package/backend/integrations/registry/providers/vercel.ts +1 -0
  90. package/backend/integrations/registry/types.ts +2 -0
  91. package/backend/memory/compose.ts +2 -2
  92. package/backend/memory/consolidate.ts +2 -2
  93. package/backend/memory/extract/episodic.ts +2 -2
  94. package/backend/memory/judge.ts +2 -2
  95. package/backend/profiles/service.ts +7 -6
  96. package/backend/push/sender.ts +172 -0
  97. package/backend/push/tags.ts +25 -0
  98. package/backend/push/vapid-keys.ts +77 -0
  99. package/backend/push/webpush-crypto.test.ts +200 -0
  100. package/backend/push/webpush-crypto.ts +231 -0
  101. package/backend/skills/detect.ts +28 -0
  102. package/backend/skills/index.ts +22 -4
  103. package/backend/skills/invoke.test.ts +114 -0
  104. package/backend/skills/invoke.ts +222 -0
  105. package/backend/skills/service.ts +194 -44
  106. package/backend/skills/spec.ts +35 -0
  107. package/backend/skills/sync.ts +85 -55
  108. package/backend/subagents/detect.ts +2 -3
  109. package/backend/subagents/sync.ts +15 -8
  110. package/backend/work/pull-requests.ts +2 -2
  111. package/backend/work/start-work.ts +4 -0
  112. package/backend/worktrees/branching/engine.ts +557 -0
  113. package/backend/worktrees/branching/index.ts +56 -0
  114. package/backend/worktrees/branching/naming.test.ts +118 -0
  115. package/backend/worktrees/branching/naming.ts +97 -0
  116. package/backend/worktrees/branching/projector.test.ts +229 -0
  117. package/backend/worktrees/branching/projector.ts +139 -0
  118. package/backend/worktrees/branching/providers/neon.ts +220 -0
  119. package/backend/worktrees/branching/registry.ts +27 -0
  120. package/backend/worktrees/branching/service.ts +620 -0
  121. package/backend/worktrees/branching/suggest.test.ts +154 -0
  122. package/backend/worktrees/branching/suggest.ts +202 -0
  123. package/backend/worktrees/branching/types.ts +88 -0
  124. package/backend/worktrees/index.ts +7 -0
  125. package/backend/worktrees/service.ts +48 -1
  126. package/backend/ws/chat/stream.ts +100 -8
  127. package/backend/ws/db-client/env.ts +142 -0
  128. package/backend/ws/db-client/index.ts +2 -0
  129. package/backend/ws/files/index.ts +4 -0
  130. package/backend/ws/files/share.ts +95 -0
  131. package/backend/ws/git/branch-name.ts +2 -2
  132. package/backend/ws/git/commit-message.ts +2 -2
  133. package/backend/ws/index.ts +3 -4
  134. package/backend/ws/profiles/crud.ts +2 -3
  135. package/backend/ws/projects/index.ts +6 -1
  136. package/backend/ws/projects/info.ts +70 -6
  137. package/backend/ws/projects/overview.test.ts +108 -0
  138. package/backend/ws/projects/overview.ts +300 -0
  139. package/backend/ws/skills/catalog.ts +5 -1
  140. package/backend/ws/skills/crud.ts +128 -22
  141. package/backend/ws/skills/index.ts +4 -1
  142. package/backend/ws/system/device-info.ts +307 -76
  143. package/backend/ws/user/crud.ts +12 -3
  144. package/backend/ws/worktrees/branching.ts +212 -0
  145. package/backend/ws/worktrees/crud.ts +33 -7
  146. package/backend/ws/worktrees/index.ts +14 -0
  147. package/dist/assets/{index-C8Gi-b6U.js → index-CeNKKSDR.js} +1 -1
  148. package/dist/assets/{index-BrF6nqld.js → index-DW89566K.js} +1 -1
  149. package/dist/assets/main-Cy5DXWPT.js +1207 -0
  150. package/dist/assets/main-DJKj_4By.css +1 -0
  151. package/dist/index.html +7 -2
  152. package/dist/sw.js +112 -0
  153. package/package.json +1 -1
  154. package/shared/constants/engine-tools.ts +31 -6
  155. package/shared/constants/notification-messages.ts +142 -0
  156. package/shared/constants/tool-icons.ts +6 -2
  157. package/shared/types/db-client/env.ts +192 -0
  158. package/shared/types/db-client/index.ts +1 -0
  159. package/shared/types/db-client/integrations.ts +30 -0
  160. package/shared/types/integrations.ts +9 -0
  161. package/shared/types/unified/stream.ts +7 -0
  162. package/shared/types/worktree-branching.ts +315 -0
  163. package/shared/utils/logger.ts +1 -0
  164. package/backend/commands/detect.ts +0 -25
  165. package/backend/commands/index.ts +0 -9
  166. package/backend/commands/service.ts +0 -178
  167. package/backend/commands/store.ts +0 -45
  168. package/backend/commands/sync.ts +0 -94
  169. package/backend/database/queries/command-queries.ts +0 -82
  170. package/backend/ws/commands/crud.ts +0 -157
  171. package/backend/ws/commands/index.ts +0 -8
  172. package/dist/assets/main-Bd3gb79F.css +0 -1
  173. package/dist/assets/main-Bo1hD7mt.js +0 -1191
@@ -0,0 +1,222 @@
1
+ /**
2
+ * Slash invocation — Clopen expands `/<slug>` itself, before the prompt reaches
3
+ * any engine.
4
+ *
5
+ * This is the whole reason Commands merged into Skills. The old design
6
+ * materialized a command file into each engine's native command directory and
7
+ * relied on the engine to expand it. Only four of the eight engines have such a
8
+ * directory (Claude, Codex, OpenCode, Pi); on the other four the model was handed
9
+ * a list of command NAMES with no bodies and no `$ARGUMENTS` substitution, so
10
+ * `/review-pr 123` produced an invented procedure instead of the user's.
11
+ *
12
+ * Expanding here makes a slash skill behave identically on every engine, and
13
+ * makes `uses:` possible: the composed prompt can deterministically pull in
14
+ * several other skills in one invocation, instead of hoping the model notices
15
+ * they are relevant.
16
+ *
17
+ * Argument substitution follows the convention users already know from Claude's
18
+ * custom commands:
19
+ * - `$ARGUMENTS` — everything typed after the slug;
20
+ * - `$1` … `$9` — individual whitespace-separated arguments;
21
+ * and when a body references neither, the arguments are appended under a short
22
+ * heading so they are never silently dropped.
23
+ */
24
+
25
+ import { skillQueries, parseTriggers, parseUses } from '$backend/database/queries';
26
+ import { artifactFilter } from '$backend/profiles';
27
+ import { debug } from '$shared/utils/logger';
28
+ import { parseSkillMd } from './spec';
29
+ import { getSkillMdPath, getSkillDir, readSkillMd } from './store';
30
+
31
+ /** A `/slug args…` message, split into its parts. */
32
+ export interface SlashInvocation {
33
+ slug: string;
34
+ args: string;
35
+ }
36
+
37
+ /** The result of expanding a slash invocation. */
38
+ export interface ExpandedInvocation {
39
+ slug: string;
40
+ name: string;
41
+ /** The prompt text to send to the engine in place of the user's `/slug` line. */
42
+ text: string;
43
+ /** Slugs force-loaded through `uses:` (transitively resolved, in load order). */
44
+ used: string[];
45
+ }
46
+
47
+ /** What the caller knows about the stream the invocation belongs to. */
48
+ export interface InvocationContext {
49
+ profileId?: number | null;
50
+ }
51
+
52
+ /**
53
+ * Anything that is not a lone `/word …` line is a normal message. The slug
54
+ * pattern deliberately matches the skill slug grammar, so a path like `/usr/bin`
55
+ * or a lone `/` never looks like an invocation.
56
+ */
57
+ const SLASH_RE = /^[ \t]*\/([a-z0-9]+(?:-[a-z0-9]+)*)(?:[ \t]+([\s\S]*))?$/;
58
+
59
+ /** Parse a raw message into a slash invocation, or null when it isn't one. */
60
+ export function parseSlashInvocation(text: string): SlashInvocation | null {
61
+ const match = SLASH_RE.exec(text.replace(/\s+$/, ''));
62
+ if (!match) return null;
63
+ return { slug: match[1], args: (match[2] ?? '').trim() };
64
+ }
65
+
66
+ /** Split an argument string the way a shell-ish `$1 $2` substitution expects. */
67
+ function splitArgs(args: string): string[] {
68
+ return args.length ? args.split(/\s+/) : [];
69
+ }
70
+
71
+ /**
72
+ * Substitute `$ARGUMENTS` / `$1`…`$9` into a body. Returns the substituted text
73
+ * plus whether any placeholder was actually present, so the caller can decide to
74
+ * append unconsumed arguments rather than drop them.
75
+ *
76
+ * Exported for direct testing: this is the contract users rely on when porting a
77
+ * `.claude/commands/*.md`, and it is the one part of expansion that has to be
78
+ * right without a database or an engine in the loop.
79
+ */
80
+ export function substituteArgs(body: string, args: string): { text: string; consumed: boolean } {
81
+ const positional = splitArgs(args);
82
+ let consumed = false;
83
+ const text = body
84
+ .replace(/\$ARGUMENTS\b/g, () => {
85
+ consumed = true;
86
+ return args;
87
+ })
88
+ .replace(/\$([1-9])\b/g, (_match, index: string) => {
89
+ consumed = true;
90
+ return positional[Number(index) - 1] ?? '';
91
+ });
92
+ return { text, consumed };
93
+ }
94
+
95
+ /**
96
+ * The skills that may be invoked by slug for this stream: the enabled set, or
97
+ * exactly the active Profile's set when it references any skill (same
98
+ * presence-per-type rule the sync path uses — a profile-referenced skill counts
99
+ * even if globally disabled).
100
+ */
101
+ function invocableSlugs(profileId?: number | null): Set<string> {
102
+ const filter = artifactFilter(profileId ?? undefined, 'skill');
103
+ const rows = filter ? skillQueries.getAll().filter(r => filter.has(r.slug)) : skillQueries.getEnabled();
104
+ return new Set(rows.map(r => r.slug));
105
+ }
106
+
107
+ /**
108
+ * Resolve `uses:` transitively, breadth-first, skipping anything not currently
109
+ * invocable. A skill that lists itself (directly or through a cycle) is visited
110
+ * once — a cycle must not hang or duplicate the load list.
111
+ */
112
+ function resolveUses(rootSlug: string, allowed: Set<string>): string[] {
113
+ const seen = new Set<string>([rootSlug]);
114
+ const ordered: string[] = [];
115
+ const queue = [...parseUses(skillQueries.getBySlug(rootSlug)?.uses)];
116
+ while (queue.length > 0) {
117
+ const slug = queue.shift()!;
118
+ if (seen.has(slug)) continue;
119
+ seen.add(slug);
120
+ const row = skillQueries.getBySlug(slug);
121
+ if (!row) {
122
+ debug.warn('skills', `⚠️ Skill "${rootSlug}" uses "${slug}", which does not exist — skipping`);
123
+ continue;
124
+ }
125
+ if (!allowed.has(slug)) {
126
+ debug.warn('skills', `⚠️ Skill "${rootSlug}" uses "${slug}", which is disabled or out of profile — skipping`);
127
+ continue;
128
+ }
129
+ ordered.push(slug);
130
+ queue.push(...parseUses(row.uses));
131
+ }
132
+ return ordered;
133
+ }
134
+
135
+ /**
136
+ * Build the block that force-loads the `uses:` skills. Paths, not inlined
137
+ * bodies: every engine has a file-reading tool, the bundled `scripts/` and
138
+ * `references/` beside each SKILL.md stay reachable, and a chain of skills
139
+ * doesn't blow up the prompt.
140
+ */
141
+ function buildUsesBlock(used: { slug: string; name: string; description: string }[]): string {
142
+ if (used.length === 0) return '';
143
+ const lines = [
144
+ '# Required skills',
145
+ '',
146
+ 'Before doing anything else, read each of these SKILL.md files with your',
147
+ 'file-reading tool and follow them for this task. They are required, not',
148
+ 'suggestions — do not skip one because the task looks simple.',
149
+ ''
150
+ ];
151
+ for (const skill of used) {
152
+ lines.push(`- **${skill.name}** — ${skill.description}`);
153
+ lines.push(` Instructions: ${getSkillMdPath(skill.slug)}`);
154
+ }
155
+ return lines.join('\n');
156
+ }
157
+
158
+ /**
159
+ * Expand a `/slug args…` message into the prompt the engine should actually
160
+ * receive. Returns null when the text is not a slash invocation, or names a slug
161
+ * that isn't an invocable slash skill for this stream — in both cases the
162
+ * message must be sent through untouched (the user may simply have typed a line
163
+ * starting with a slash).
164
+ *
165
+ * Never throws: a skill whose SKILL.md has gone missing on disk falls back to
166
+ * "not an invocation" rather than breaking the turn.
167
+ */
168
+ export async function expandSlashInvocation(
169
+ text: string,
170
+ context: InvocationContext
171
+ ): Promise<ExpandedInvocation | null> {
172
+ const invocation = parseSlashInvocation(text);
173
+ if (!invocation) return null;
174
+
175
+ const row = skillQueries.getBySlug(invocation.slug);
176
+ if (!row || !parseTriggers(row.triggers).includes('slash')) return null;
177
+
178
+ const allowed = invocableSlugs(context.profileId);
179
+ if (!allowed.has(row.slug)) return null;
180
+
181
+ let body: string;
182
+ try {
183
+ const raw = await readSkillMd(row.slug);
184
+ if (raw == null) {
185
+ debug.warn('skills', `⚠️ /${row.slug} invoked but SKILL.md is missing on disk — sending the message as typed`);
186
+ return null;
187
+ }
188
+ body = parseSkillMd(raw).body;
189
+ } catch (error) {
190
+ debug.warn('skills', `⚠️ Could not read SKILL.md for /${row.slug} — sending the message as typed:`, error);
191
+ return null;
192
+ }
193
+
194
+ const { text: substituted, consumed } = substituteArgs(body, invocation.args);
195
+ const usedSlugs = resolveUses(row.slug, allowed);
196
+ const used = usedSlugs
197
+ .map(slug => skillQueries.getBySlug(slug))
198
+ .filter((r): r is NonNullable<typeof r> => r !== null)
199
+ .map(r => ({ slug: r.slug, name: r.name, description: r.description }));
200
+
201
+ const sections = [buildUsesBlock(used), substituted.trim()];
202
+ // Arguments the body never referenced would otherwise vanish — the user typed
203
+ // them for a reason, so hand them to the model explicitly.
204
+ if (invocation.args && !consumed) {
205
+ sections.push(`# Arguments\n\n${invocation.args}`);
206
+ }
207
+ // The skill's own folder is where its bundled resources live; say so once so
208
+ // `scripts/`-style references in the body resolve without guessing.
209
+ sections.push(`(Invoked as /${row.slug}. Skill files: ${getSkillDir(row.slug)})`);
210
+
211
+ debug.log(
212
+ 'skills',
213
+ `⌨️ Expanded /${row.slug}${invocation.args ? ' with arguments' : ''}${used.length ? `, requiring ${used.length} skill(s)` : ''}`
214
+ );
215
+
216
+ return {
217
+ slug: row.slug,
218
+ name: row.name,
219
+ text: sections.filter(Boolean).join('\n\n'),
220
+ used: usedSlugs
221
+ };
222
+ }
@@ -2,9 +2,25 @@
2
2
  * Skill service — orchestrates the DB metadata table and the on-disk canonical
3
3
  * store for the Settings → Skills CRUD surface. The WS layer calls these; they
4
4
  * keep the `skills` table and `{clopenDir}/skills/<slug>/` in lockstep.
5
+ *
6
+ * Since migration 079 a skill covers BOTH ways of invoking a reusable prompt:
7
+ * - `auto` — the model reads the description and loads the skill when it fits;
8
+ * - `slash` — the user types `/<slug>` and Clopen expands the body into the
9
+ * prompt (see `./invoke.ts`). This is what the old Commands feature was.
10
+ * The two are independent switches, so one skill can be both.
5
11
  */
6
12
 
7
- import { skillQueries, type SkillRow, type SkillSource } from '$backend/database/queries';
13
+ import {
14
+ skillQueries,
15
+ parseTriggers,
16
+ stringifyTriggers,
17
+ parseUses,
18
+ stringifyUses,
19
+ type SkillRow,
20
+ type SkillSource,
21
+ type SkillTrigger
22
+ } from '$backend/database/queries';
23
+ import { uniqueSlug } from '$backend/artifacts';
8
24
  import { debug } from '$shared/utils/logger';
9
25
  import {
10
26
  parseSkillMd,
@@ -32,21 +48,58 @@ export interface SkillDTO {
32
48
  marketplaceRef: string | null;
33
49
  version: string | null;
34
50
  license: string | null;
51
+ /** How the skill can be invoked — `auto` and/or `slash`. Never empty. */
52
+ triggers: SkillTrigger[];
53
+ /** Argument hint shown beside `/slug` in the chat picker. */
54
+ argumentHint: string | null;
55
+ /** Sibling slugs force-loaded whenever this skill runs. */
56
+ uses: string[];
35
57
  enabled: boolean;
36
58
  /** False when the DB row exists but its SKILL.md is missing on disk. */
37
59
  present: boolean;
38
60
  createdAt: string;
39
61
  }
40
62
 
63
+ /** Editable fields shared by create / update. */
64
+ export interface SkillInputFields {
65
+ /**
66
+ * Machine id, settable only at creation.
67
+ *
68
+ * It is the folder name on disk, the `/<slug>` a user types in chat, and what
69
+ * `uses:` lists and Profile bundles reference — so renaming it after the fact
70
+ * would break every one of those silently. Blank means "derive it from the
71
+ * name". {@link skillService.update} ignores this field entirely.
72
+ */
73
+ slug?: string;
74
+ name: string;
75
+ description: string;
76
+ body: string;
77
+ license?: string | null;
78
+ triggers?: SkillTrigger[];
79
+ argumentHint?: string | null;
80
+ uses?: string[];
81
+ }
82
+
41
83
  /** A previewed skill parsed from pasted/imported SKILL.md text. */
42
84
  export interface ParsedSkillPreview {
43
85
  name: string;
44
86
  description: string;
45
87
  license: string | null;
88
+ triggers: SkillTrigger[];
89
+ argumentHint: string | null;
90
+ uses: string[];
46
91
  body: string;
47
92
  warnings: string[];
48
93
  }
49
94
 
95
+ /** One slash-invocable skill as offered to the chat "/" picker. */
96
+ export interface AvailableSkill {
97
+ slug: string;
98
+ name: string;
99
+ description: string;
100
+ argumentHint: string | null;
101
+ }
102
+
50
103
  function toDTO(row: SkillRow, present: boolean): SkillDTO {
51
104
  return {
52
105
  id: row.id,
@@ -57,21 +110,41 @@ function toDTO(row: SkillRow, present: boolean): SkillDTO {
57
110
  marketplaceRef: row.marketplace_ref,
58
111
  version: row.version,
59
112
  license: row.license,
113
+ triggers: parseTriggers(row.triggers),
114
+ argumentHint: row.argument_hint,
115
+ uses: parseUses(row.uses),
60
116
  enabled: row.is_enabled === 1,
61
117
  present,
62
118
  createdAt: row.created_at
63
119
  };
64
120
  }
65
121
 
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()}`);
122
+ /** Normalise a comma list of trigger names into the validated set. */
123
+ function triggersFromFrontmatter(raw: string | undefined): SkillTrigger[] {
124
+ return parseTriggers(raw);
125
+ }
126
+
127
+ /** `uses` round-trips through frontmatter as a comma list, and through the DB as JSON. */
128
+ function usesFromFrontmatter(raw: string | undefined): string[] {
129
+ return (raw ?? '').split(',').map(u => u.trim()).filter(Boolean);
130
+ }
131
+
132
+ /** Build the canonical SKILL.md frontmatter for a set of editor fields. */
133
+ function frontmatterFor(slug: string, input: SkillInputFields): ParsedSkill['frontmatter'] {
134
+ const triggers = input.triggers?.length ? input.triggers : (['auto'] as SkillTrigger[]);
135
+ const uses = (input.uses ?? []).map(u => u.trim()).filter(Boolean);
136
+ return {
137
+ name: slug,
138
+ description: input.description.trim(),
139
+ license: input.license?.trim() || undefined,
140
+ // `triggers` is always written, even when it is the default: an explicit
141
+ // value is what makes an exported SKILL.md round-trip into another Clopen
142
+ // with the same behaviour instead of silently reverting to `auto`.
143
+ triggers: stringifyTriggers(triggers),
144
+ argumentHint: input.argumentHint?.trim() || undefined,
145
+ uses: uses.length ? uses.join(', ') : undefined,
146
+ extra: {}
147
+ };
75
148
  }
76
149
 
77
150
  /** Throw a single combined error if frontmatter validation fails. */
@@ -80,6 +153,29 @@ function assertValid(skill: ParsedSkill, expectedName: string): void {
80
153
  if (!result.valid) throw new Error(result.errors.join(' '));
81
154
  }
82
155
 
156
+ /** Derive a slug that doesn't collide with an existing skill. */
157
+ function nextSlug(base: string): string {
158
+ return uniqueSlug(slugifySkillName(base), s => !!skillQueries.getBySlug(s));
159
+ }
160
+
161
+ /**
162
+ * Resolve the slug for a new skill.
163
+ *
164
+ * A slug the user typed is normalised but never silently de-duplicated: they
165
+ * asked for that exact id, so a clash is reported instead of quietly becoming
166
+ * `<slug>-2`. A derived slug keeps the old auto-suffix behaviour, because there
167
+ * the user expressed no preference.
168
+ */
169
+ function resolveNewSlug(input: SkillInputFields): string {
170
+ const requested = input.slug?.trim();
171
+ if (!requested) return nextSlug(input.name);
172
+ const slug = slugifySkillName(requested);
173
+ if (skillQueries.getBySlug(slug)) {
174
+ throw new Error(`The id "${slug}" is already used by another skill. Pick a different one.`);
175
+ }
176
+ return slug;
177
+ }
178
+
83
179
  export const skillService = {
84
180
  async list(): Promise<SkillDTO[]> {
85
181
  const rows = skillQueries.getAll();
@@ -87,6 +183,29 @@ export const skillService = {
87
183
  return rows.map((row, i) => toDTO(row, presence[i]));
88
184
  },
89
185
 
186
+ /**
187
+ * Minimal list of slash-invocable skills for the chat "/" picker. Non-admin
188
+ * surface (any user can invoke one), so it exposes only display fields — no
189
+ * bodies, no source/disk metadata.
190
+ *
191
+ * `profileFilter` mirrors the stream-time semantics: when an active profile
192
+ * references ≥1 skill, the picker shows exactly that set (even if a referenced
193
+ * skill is globally disabled) instead of the enabled set.
194
+ */
195
+ available(profileFilter?: Set<string> | null): AvailableSkill[] {
196
+ const rows = profileFilter
197
+ ? skillQueries.getAll().filter(r => profileFilter.has(r.slug))
198
+ : skillQueries.getEnabled();
199
+ return rows
200
+ .filter(r => parseTriggers(r.triggers).includes('slash'))
201
+ .map(r => ({
202
+ slug: r.slug,
203
+ name: r.name,
204
+ description: r.description,
205
+ argumentHint: r.argument_hint
206
+ }));
207
+ },
208
+
90
209
  async get(id: number): Promise<{ skill: SkillDTO; body: string } | null> {
91
210
  const row = skillQueries.getById(id);
92
211
  if (!row) return null;
@@ -95,18 +214,13 @@ export const skillService = {
95
214
  return { skill: toDTO(row, raw !== null), body };
96
215
  },
97
216
 
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
- };
217
+ /** Create a skill from in-app editor fields. */
218
+ async create(input: SkillInputFields): Promise<SkillDTO> {
219
+ if (!input.name.trim()) throw new Error('A skill name is required');
220
+ // The body IS the skill — an empty one loads nothing and runs nothing.
221
+ if (!input.body.trim()) throw new Error('Instructions are required');
222
+ const slug = resolveNewSlug(input);
223
+ const skill: ParsedSkill = { frontmatter: frontmatterFor(slug, input), body: input.body };
110
224
  assertValid(skill, slug);
111
225
  await writeSkillMd(slug, serializeSkillMd(skill));
112
226
  const row = skillQueries.insert({
@@ -114,30 +228,35 @@ export const skillService = {
114
228
  name: input.name.trim(),
115
229
  description: input.description.trim(),
116
230
  source: 'custom',
117
- license: input.license?.trim() || null
231
+ license: input.license?.trim() || null,
232
+ triggers: stringifyTriggers(input.triggers),
233
+ argumentHint: input.argumentHint?.trim() || null,
234
+ uses: stringifyUses(input.uses)
118
235
  });
119
- debug.log('skills', `📦 Created skill: ${slug}`);
236
+ debug.log('skills', `📦 Created skill: ${slug} (${stringifyTriggers(input.triggers)})`);
120
237
  return toDTO(row, true);
121
238
  },
122
239
 
123
240
  /** 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> {
241
+ async update(id: number, input: SkillInputFields): Promise<SkillDTO> {
125
242
  const row = skillQueries.getById(id);
126
243
  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
- };
244
+ if (!input.body.trim()) throw new Error('Instructions are required');
245
+ // The slug is frozen after creation: it is the folder on disk, the `/<slug>`
246
+ // typed in chat, and what `uses:` lists and Profiles reference. Only the
247
+ // display name, description, license, triggers, hint, `uses` and body are
248
+ // editable here — `input.slug` is deliberately ignored.
249
+ const skill: ParsedSkill = { frontmatter: frontmatterFor(row.slug, input), body: input.body };
138
250
  assertValid(skill, row.slug);
139
251
  await writeSkillMd(row.slug, serializeSkillMd(skill));
140
- skillQueries.updateMeta(id, input.name.trim(), input.description.trim(), input.license?.trim() || null);
252
+ skillQueries.updateMeta(id, {
253
+ name: input.name.trim(),
254
+ description: input.description.trim(),
255
+ license: input.license?.trim() || null,
256
+ triggers: stringifyTriggers(input.triggers),
257
+ argumentHint: input.argumentHint?.trim() || null,
258
+ uses: stringifyUses(input.uses)
259
+ });
141
260
  debug.log('skills', `🔧 Updated skill: ${row.slug}`);
142
261
  return toDTO(skillQueries.getById(id)!, true);
143
262
  },
@@ -145,28 +264,51 @@ export const skillService = {
145
264
  /**
146
265
  * Parse pasted/uploaded SKILL.md text into a reviewable preview. Nothing is
147
266
  * persisted — the UI shows the result, then calls `import` to commit it.
267
+ *
268
+ * A pasted document with no `name` but an `argument-hint` is almost certainly
269
+ * a pre-merge Clopen/Claude command file, so it previews as a slash skill.
148
270
  */
149
271
  parsePreview(raw: string): ParsedSkillPreview {
150
272
  const parsed = parseSkillMd(raw);
151
273
  const warnings: string[] = [];
274
+ const triggers = parsed.frontmatter.triggers
275
+ ? triggersFromFrontmatter(parsed.frontmatter.triggers)
276
+ : parsed.frontmatter.argumentHint
277
+ ? (['slash'] as SkillTrigger[])
278
+ : (['auto'] as SkillTrigger[]);
152
279
  const result = validateFrontmatter(parsed.frontmatter, undefined);
153
280
  if (!result.valid) warnings.push(...result.errors);
154
281
  return {
155
282
  name: parsed.frontmatter.name,
156
283
  description: parsed.frontmatter.description,
157
284
  license: parsed.frontmatter.license ?? null,
285
+ triggers,
286
+ argumentHint: parsed.frontmatter.argumentHint ?? null,
287
+ uses: usesFromFrontmatter(parsed.frontmatter.uses),
158
288
  body: parsed.body,
159
289
  warnings
160
290
  };
161
291
  },
162
292
 
163
- /** Persist a skill from pasted/uploaded SKILL.md text. */
164
- async import(raw: string): Promise<SkillDTO> {
293
+ /**
294
+ * Persist a skill from pasted/uploaded SKILL.md text. Accepts both a real
295
+ * SKILL.md and a bare command document (frontmatter with only
296
+ * `description`/`argument-hint`, no `name`) — the latter is what users paste
297
+ * from a `.claude/commands/*.md`.
298
+ */
299
+ async import(raw: string, nameHint?: string): Promise<SkillDTO> {
300
+ const preview = this.parsePreview(raw);
165
301
  const parsed = parseSkillMd(raw);
166
- const displayName = parsed.frontmatter.name || 'Imported skill';
167
- const slug = uniqueSlug(parsed.frontmatter.name || displayName);
302
+ const displayName = (nameHint?.trim() || preview.name || preview.description || 'Imported skill').trim();
303
+ const slug = nextSlug(preview.name || displayName);
168
304
  // Re-key the frontmatter `name` to the de-duped slug so it matches the folder.
169
305
  parsed.frontmatter.name = slug;
306
+ parsed.frontmatter.triggers = stringifyTriggers(preview.triggers);
307
+ if (!parsed.frontmatter.description.trim()) {
308
+ // The spec requires a description and the "/" picker shows it; fall back
309
+ // to the display name rather than rejecting a valid command paste.
310
+ parsed.frontmatter.description = displayName;
311
+ }
170
312
  assertValid(parsed, slug);
171
313
  await writeSkillMd(slug, serializeSkillMd(parsed));
172
314
  const row = skillQueries.insert({
@@ -174,7 +316,10 @@ export const skillService = {
174
316
  name: displayName,
175
317
  description: parsed.frontmatter.description,
176
318
  source: 'imported',
177
- license: parsed.frontmatter.license ?? null
319
+ license: parsed.frontmatter.license ?? null,
320
+ triggers: stringifyTriggers(preview.triggers),
321
+ argumentHint: preview.argumentHint,
322
+ uses: stringifyUses(preview.uses)
178
323
  });
179
324
  debug.log('skills', `📥 Imported skill: ${slug}`);
180
325
  return toDTO(row, true);
@@ -208,8 +353,10 @@ export const skillService = {
208
353
  if (override?.license !== undefined) parsed.frontmatter.license = override.license?.trim() || undefined;
209
354
  if (override?.body !== undefined) parsed.body = override.body;
210
355
  const displayName = override?.name?.trim() || parsed.frontmatter.name || ref.split(/[:/]/).pop() || 'Skill';
211
- const slug = uniqueSlug(parsed.frontmatter.name || displayName);
356
+ const slug = nextSlug(parsed.frontmatter.name || displayName);
212
357
  parsed.frontmatter.name = slug;
358
+ const triggers = triggersFromFrontmatter(parsed.frontmatter.triggers);
359
+ parsed.frontmatter.triggers = stringifyTriggers(triggers);
213
360
  assertValid(parsed, slug);
214
361
  await writeSkillMd(slug, serializeSkillMd(parsed));
215
362
  for (const resource of fetched.resources) {
@@ -222,7 +369,10 @@ export const skillService = {
222
369
  source: 'marketplace',
223
370
  marketplaceRef: ref,
224
371
  version: parsed.frontmatter.metadata?.version ?? null,
225
- license: parsed.frontmatter.license ?? null
372
+ license: parsed.frontmatter.license ?? null,
373
+ triggers: stringifyTriggers(triggers),
374
+ argumentHint: parsed.frontmatter.argumentHint ?? null,
375
+ uses: stringifyUses(usesFromFrontmatter(parsed.frontmatter.uses))
226
376
  });
227
377
  debug.log('skills', `📥 Installed marketplace skill: ${slug} (${ref})`);
228
378
  return toDTO(row, true);
@@ -6,6 +6,10 @@
6
6
  * `description`, optional `license`/`compatibility`/`metadata`/`allowed-tools`)
7
7
  * followed by a Markdown instruction body.
8
8
  *
9
+ * Clopen adds three keys of its own — `triggers`, `argument-hint` and `uses`
10
+ * (see {@link SkillFrontmatter}). The spec tells runtimes to ignore frontmatter
11
+ * keys they don't model, so a Clopen skill stays a valid, portable SKILL.md.
12
+ *
9
13
  * We deliberately hand-roll a tiny frontmatter parser rather than pull in a YAML
10
14
  * dependency: the spec's frontmatter surface is small and flat (one nested
11
15
  * `metadata` map), and skills we author in-app are written back in this exact
@@ -20,6 +24,20 @@ export interface SkillFrontmatter {
20
24
  compatibility?: string;
21
25
  allowedTools?: string;
22
26
  metadata?: Record<string, string>;
27
+ /**
28
+ * Clopen extension — how the skill is invoked, as a comma list of `auto`
29
+ * (the model decides from `description`) and/or `slash` (the user types
30
+ * `/<name>`). Absent means `auto`, which is what every pre-merge skill was.
31
+ */
32
+ triggers?: string;
33
+ /** Clopen extension — argument hint shown beside `/<name>` in the chat picker. */
34
+ argumentHint?: string;
35
+ /**
36
+ * Clopen extension — comma list of sibling skill slugs force-loaded whenever
37
+ * this skill runs. This is what lets one `/slash` skill pull in several
38
+ * skills deterministically instead of hoping the model picks them up.
39
+ */
40
+ uses?: string;
23
41
  /** Frontmatter keys we don't model, kept verbatim for lossless round-trips. */
24
42
  extra: Record<string, string>;
25
43
  }
@@ -123,6 +141,9 @@ export function parseSkillMd(raw: string): ParsedSkill {
123
141
  case 'license': fm.license = value; break;
124
142
  case 'compatibility': fm.compatibility = value; break;
125
143
  case 'allowed-tools': fm.allowedTools = value; break;
144
+ case 'triggers': fm.triggers = value; break;
145
+ case 'argument-hint': fm.argumentHint = value; break;
146
+ case 'uses': fm.uses = value; break;
126
147
  default: fm.extra[key] = value;
127
148
  }
128
149
  }
@@ -140,6 +161,9 @@ export function serializeSkillMd(skill: ParsedSkill): string {
140
161
  if (fm.license) lines.push(`license: ${quoteIfNeeded(fm.license)}`);
141
162
  if (fm.compatibility) lines.push(`compatibility: ${quoteIfNeeded(fm.compatibility)}`);
142
163
  if (fm.allowedTools) lines.push(`allowed-tools: ${quoteIfNeeded(fm.allowedTools)}`);
164
+ if (fm.triggers) lines.push(`triggers: ${quoteIfNeeded(fm.triggers)}`);
165
+ if (fm.argumentHint) lines.push(`argument-hint: ${quoteIfNeeded(fm.argumentHint)}`);
166
+ if (fm.uses) lines.push(`uses: ${quoteIfNeeded(fm.uses)}`);
143
167
  for (const [k, v] of Object.entries(fm.extra)) lines.push(`${k}: ${quoteIfNeeded(v)}`);
144
168
  if (fm.metadata && Object.keys(fm.metadata).length > 0) {
145
169
  lines.push('metadata:');
@@ -184,6 +208,17 @@ export function validateFrontmatter(fm: SkillFrontmatter, expectedName?: string)
184
208
  errors.push('`compatibility` must be at most 500 characters.');
185
209
  }
186
210
 
211
+ if (fm.triggers) {
212
+ const parsed = fm.triggers.split(',').map(t => t.trim().toLowerCase()).filter(Boolean);
213
+ const unknown = parsed.filter(t => t !== 'auto' && t !== 'slash');
214
+ if (unknown.length > 0) {
215
+ errors.push(`\`triggers\` may only contain "auto" and "slash" (got: ${unknown.join(', ')}).`);
216
+ }
217
+ if (parsed.length === 0) {
218
+ errors.push('`triggers` must name at least one of "auto" or "slash".');
219
+ }
220
+ }
221
+
187
222
  // Angle brackets in frontmatter can inject unintended system-prompt content.
188
223
  for (const [label, value] of [
189
224
  ['name', fm.name],