@myrialabs/clopen 0.4.40 → 0.4.42

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 (141) 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 +6 -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 +50 -0
  14. package/backend/database/crypto/secret-columns.ts +5 -1
  15. package/backend/database/index.ts +18 -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/082_create_git_identities.test.ts +186 -0
  20. package/backend/database/migrations/082_create_git_identities.ts +122 -0
  21. package/backend/database/migrations/index.ts +28 -0
  22. package/backend/database/queries/file-share-queries.ts +163 -0
  23. package/backend/database/queries/git-identity-queries.ts +290 -0
  24. package/backend/database/queries/index.ts +8 -4
  25. package/backend/database/queries/profile-queries.ts +5 -3
  26. package/backend/database/queries/push-subscription-queries.test.ts +90 -0
  27. package/backend/database/queries/push-subscription-queries.ts +99 -0
  28. package/backend/database/queries/skill-queries.ts +96 -18
  29. package/backend/engine/adapters/claude/environment.ts +11 -1
  30. package/backend/engine/adapters/claude/stream.ts +3 -2
  31. package/backend/engine/adapters/cline/stream.ts +3 -3
  32. package/backend/engine/adapters/codex/stream.ts +38 -6
  33. package/backend/engine/adapters/copilot/stream.ts +3 -3
  34. package/backend/engine/adapters/cursor/stream.ts +25 -3
  35. package/backend/engine/adapters/opencode/server.ts +26 -2
  36. package/backend/engine/adapters/opencode/stream.ts +8 -7
  37. package/backend/engine/adapters/pi/stream.ts +2 -2
  38. package/backend/engine/adapters/qwen/stream.ts +5 -3
  39. package/backend/engine/artifact-sync.ts +26 -20
  40. package/backend/engine/docs/artifacts.md +81 -22
  41. package/backend/engine/docs/quick-reference.md +2 -1
  42. package/backend/engine/resolve-model.test.ts +108 -0
  43. package/backend/engine/resolve-model.ts +53 -10
  44. package/backend/engine/structured-helpers.ts +22 -0
  45. package/backend/engine/types.ts +10 -0
  46. package/backend/files/file-shares.ts +369 -0
  47. package/backend/files/path-browsing.ts +27 -21
  48. package/backend/git/git-executor.ts +28 -2
  49. package/backend/git/git-service.ts +59 -40
  50. package/backend/git/identity/cli.test.ts +58 -0
  51. package/backend/git/identity/cli.ts +201 -0
  52. package/backend/git/identity/credential-helper.test.ts +242 -0
  53. package/backend/git/identity/env.test.ts +214 -0
  54. package/backend/git/identity/env.ts +193 -0
  55. package/backend/git/identity/import-local.test.ts +199 -0
  56. package/backend/git/identity/import-local.ts +141 -0
  57. package/backend/git/identity/index.ts +78 -0
  58. package/backend/git/identity/keys.ts +183 -0
  59. package/backend/git/identity/resolve.ts +140 -0
  60. package/backend/git/identity/scope-config.test.ts +145 -0
  61. package/backend/git/identity/scope-config.ts +175 -0
  62. package/backend/git/identity/service.ts +297 -0
  63. package/backend/http/files-shared.test.ts +505 -0
  64. package/backend/http/files-shared.ts +351 -0
  65. package/backend/http/push.ts +150 -0
  66. package/backend/index.ts +24 -0
  67. package/backend/instructions/index.ts +1 -1
  68. package/backend/instructions/sync.ts +30 -6
  69. package/backend/memory/compose.ts +2 -2
  70. package/backend/memory/consolidate.ts +2 -2
  71. package/backend/memory/extract/episodic.ts +2 -2
  72. package/backend/memory/judge.ts +2 -2
  73. package/backend/preview/browser/browser-console-manager.ts +214 -34
  74. package/backend/preview/browser/browser-pool.ts +526 -123
  75. package/backend/preview/browser/browser-preview-service.ts +192 -8
  76. package/backend/preview/browser/browser-tab-lifecycle.test.ts +240 -0
  77. package/backend/preview/browser/browser-tab-lifecycle.ts +495 -0
  78. package/backend/preview/browser/browser-tab-manager.ts +291 -65
  79. package/backend/preview/browser/capture-profile.ts +15 -1
  80. package/backend/preview/browser/types.ts +26 -1
  81. package/backend/profiles/service.ts +7 -6
  82. package/backend/push/sender.ts +172 -0
  83. package/backend/push/tags.ts +25 -0
  84. package/backend/push/vapid-keys.ts +77 -0
  85. package/backend/push/webpush-crypto.test.ts +200 -0
  86. package/backend/push/webpush-crypto.ts +231 -0
  87. package/backend/skills/detect.ts +28 -0
  88. package/backend/skills/index.ts +22 -4
  89. package/backend/skills/invoke.test.ts +114 -0
  90. package/backend/skills/invoke.ts +222 -0
  91. package/backend/skills/service.ts +194 -44
  92. package/backend/skills/spec.ts +35 -0
  93. package/backend/skills/sync.ts +85 -55
  94. package/backend/subagents/detect.ts +2 -3
  95. package/backend/subagents/sync.ts +15 -8
  96. package/backend/terminal/ptykit.ts +24 -0
  97. package/backend/work/pull-requests.ts +2 -2
  98. package/backend/ws/chat/stream.ts +100 -8
  99. package/backend/ws/files/index.ts +4 -0
  100. package/backend/ws/files/share.ts +95 -0
  101. package/backend/ws/git/branch-name.ts +2 -2
  102. package/backend/ws/git/branch.ts +17 -6
  103. package/backend/ws/git/commit-message.ts +2 -2
  104. package/backend/ws/git/commit.ts +6 -5
  105. package/backend/ws/git/conflict.ts +3 -2
  106. package/backend/ws/git/identity-context.ts +91 -0
  107. package/backend/ws/git/identity.ts +200 -0
  108. package/backend/ws/git/index.ts +3 -1
  109. package/backend/ws/git/remote.ts +57 -11
  110. package/backend/ws/index.ts +3 -4
  111. package/backend/ws/preview/browser/data.ts +60 -0
  112. package/backend/ws/preview/browser/interact.ts +6 -0
  113. package/backend/ws/preview/browser/tab-info.ts +9 -1
  114. package/backend/ws/preview/browser/tab.ts +64 -8
  115. package/backend/ws/preview/index.ts +21 -0
  116. package/backend/ws/profiles/crud.ts +2 -3
  117. package/backend/ws/skills/catalog.ts +5 -1
  118. package/backend/ws/skills/crud.ts +128 -22
  119. package/backend/ws/skills/index.ts +4 -1
  120. package/backend/ws/user/crud.ts +12 -3
  121. package/bin/clopen.ts +9 -0
  122. package/dist/assets/{index-D4igjF6e.js → index-BynqyvF4.js} +1 -1
  123. package/dist/assets/{index-DONNwiXm.js → index-DLoJsmNQ.js} +1 -1
  124. package/dist/assets/{main-BrfXH1bL.js → main-CUyZAmqt.js} +601 -592
  125. package/dist/assets/main-DVCW3cfr.css +1 -0
  126. package/dist/index.html +7 -2
  127. package/dist/sw.js +112 -0
  128. package/package.json +2 -2
  129. package/shared/constants/engine-tools.ts +31 -6
  130. package/shared/constants/notification-messages.ts +142 -0
  131. package/shared/types/git-identity.ts +112 -0
  132. package/shared/types/unified/stream.ts +7 -0
  133. package/backend/commands/detect.ts +0 -25
  134. package/backend/commands/index.ts +0 -9
  135. package/backend/commands/service.ts +0 -178
  136. package/backend/commands/store.ts +0 -45
  137. package/backend/commands/sync.ts +0 -94
  138. package/backend/database/queries/command-queries.ts +0 -82
  139. package/backend/ws/commands/crud.ts +0 -157
  140. package/backend/ws/commands/index.ts +0 -8
  141. package/dist/assets/main-CT1PygsW.css +0 -1
@@ -0,0 +1,231 @@
1
+ /**
2
+ * Web Push cryptography (RFC 8291 `aes128gcm` + RFC 8292 VAPID).
3
+ *
4
+ * Implemented with the platform WebCrypto API instead of a `web-push`
5
+ * dependency: Bun ships ECDH P-256, HKDF, AES-GCM and ECDSA, which is
6
+ * everything the protocol needs. No new supply chain for a
7
+ * security-sensitive path.
8
+ *
9
+ * Two pieces:
10
+ * - VAPID: an ES256-signed JWT proving the push originates from this server.
11
+ * - Content encryption: the payload is encrypted to the browser's per-
12
+ * subscription key, so the push service (Google/Mozilla/Apple) relaying it
13
+ * only ever sees ciphertext.
14
+ */
15
+
16
+ const textEncoder = new TextEncoder();
17
+
18
+ export function base64UrlEncode(data: Uint8Array | ArrayBuffer): string {
19
+ const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);
20
+ let binary = '';
21
+ const CHUNK = 0x8000;
22
+ for (let i = 0; i < bytes.length; i += CHUNK) {
23
+ binary += String.fromCharCode(...bytes.subarray(i, i + CHUNK));
24
+ }
25
+ return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
26
+ }
27
+
28
+ export function base64UrlDecode(input: string): Uint8Array<ArrayBuffer> {
29
+ const base64 = input.replace(/-/g, '+').replace(/_/g, '/');
30
+ const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4);
31
+ const binary = atob(padded);
32
+ const out = new Uint8Array(binary.length);
33
+ for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
34
+ return out;
35
+ }
36
+
37
+ function concat(...parts: Uint8Array[]): Uint8Array<ArrayBuffer> {
38
+ const total = parts.reduce((sum, part) => sum + part.length, 0);
39
+ const out = new Uint8Array(total);
40
+ let offset = 0;
41
+ for (const part of parts) {
42
+ out.set(part, offset);
43
+ offset += part.length;
44
+ }
45
+ return out;
46
+ }
47
+
48
+ // ============================================================================
49
+ // VAPID (RFC 8292)
50
+ // ============================================================================
51
+
52
+ export interface VapidKeypair {
53
+ /** Uncompressed P-256 public key (65 bytes), base64url. */
54
+ publicKey: string;
55
+ /** Raw P-256 private key (32 bytes), base64url. */
56
+ privateKey: string;
57
+ }
58
+
59
+ export async function generateVapidKeypair(): Promise<VapidKeypair> {
60
+ const keypair = await crypto.subtle.generateKey(
61
+ { name: 'ECDSA', namedCurve: 'P-256' },
62
+ true,
63
+ ['sign', 'verify']
64
+ );
65
+ const publicRaw = new Uint8Array(await crypto.subtle.exportKey('raw', keypair.publicKey));
66
+ const privateJwk = await crypto.subtle.exportKey('jwk', keypair.privateKey);
67
+ if (!privateJwk.d) throw new Error('Failed to export VAPID private key');
68
+ return { publicKey: base64UrlEncode(publicRaw), privateKey: privateJwk.d };
69
+ }
70
+
71
+ /**
72
+ * Build the `Authorization` header for a push request.
73
+ *
74
+ * `audience` is the push service origin (`new URL(endpoint).origin`), so a
75
+ * token minted for FCM cannot be replayed at another service. `subject`
76
+ * identifies the server operator (`mailto:` or URL).
77
+ */
78
+ export async function createVapidAuthorizationHeader(
79
+ audience: string,
80
+ subject: string,
81
+ keypair: VapidKeypair,
82
+ ttlSeconds = 12 * 3600
83
+ ): Promise<string> {
84
+ const header = base64UrlEncode(textEncoder.encode(JSON.stringify({ typ: 'JWT', alg: 'ES256' })));
85
+ const nowSeconds = Math.floor(Date.now() / 1000);
86
+ const claims = base64UrlEncode(
87
+ textEncoder.encode(
88
+ JSON.stringify({ aud: audience, exp: nowSeconds + ttlSeconds, sub: subject })
89
+ )
90
+ );
91
+ const signingInput = textEncoder.encode(`${header}.${claims}`);
92
+
93
+ const publicBytes = base64UrlDecode(keypair.publicKey);
94
+ if (publicBytes.length !== 65 || publicBytes[0] !== 0x04) {
95
+ throw new Error('Invalid VAPID public key (expected 65-byte uncompressed point)');
96
+ }
97
+ const privateKey = await crypto.subtle.importKey(
98
+ 'jwk',
99
+ {
100
+ kty: 'EC',
101
+ crv: 'P-256',
102
+ x: base64UrlEncode(publicBytes.slice(1, 33)),
103
+ y: base64UrlEncode(publicBytes.slice(33, 65)),
104
+ d: keypair.privateKey
105
+ },
106
+ { name: 'ECDSA', namedCurve: 'P-256' },
107
+ false,
108
+ ['sign']
109
+ );
110
+ const signature = await crypto.subtle.sign(
111
+ { name: 'ECDSA', hash: 'SHA-256' },
112
+ privateKey,
113
+ signingInput
114
+ );
115
+ return `vapid t=${header}.${claims}.${base64UrlEncode(signature)}, k=${keypair.publicKey}`;
116
+ }
117
+
118
+ // ============================================================================
119
+ // Content encryption (RFC 8291, `aes128gcm`, single record)
120
+ // ============================================================================
121
+
122
+ /** Record size announced in the header. 4096 is what every push service accepts. */
123
+ const RECORD_SIZE = 4096;
124
+
125
+ export interface EncryptedPushPayload {
126
+ /** Full request body: 16-byte salt + 4-byte rs + 1-byte idlen + 65-byte key + ciphertext. */
127
+ body: Uint8Array<ArrayBuffer>;
128
+ }
129
+
130
+ /**
131
+ * HKDF-Extract + first-block Expand, per RFC 5869 as used by RFC 8291.
132
+ *
133
+ * `secret = HKDF(salt, IKM, info, length)` means Extract(salt, IKM) then the
134
+ * first `length` bytes of Expand — the same construction the reference
135
+ * `web-push` implementation computes, so ciphertext decrypts in real
136
+ * browsers.
137
+ */
138
+ async function hkdf(
139
+ salt: Uint8Array<ArrayBuffer>,
140
+ ikm: Uint8Array<ArrayBuffer>,
141
+ info: Uint8Array<ArrayBuffer>,
142
+ length: number
143
+ ): Promise<Uint8Array<ArrayBuffer>> {
144
+ const extractKey = await crypto.subtle.importKey('raw', ikm, 'HKDF', false, ['deriveBits']);
145
+ return new Uint8Array(
146
+ await crypto.subtle.deriveBits(
147
+ { name: 'HKDF', hash: 'SHA-256', salt, info },
148
+ extractKey,
149
+ length * 8
150
+ )
151
+ );
152
+ }
153
+
154
+ /**
155
+ * Encrypt a payload for one subscription.
156
+ *
157
+ * Throws on malformed subscription keys — callers translate that into
158
+ * dropping the dead subscription, never into failing the whole fan-out.
159
+ */
160
+ export async function encryptPushPayload(
161
+ clientPublicKeyBase64: string,
162
+ clientAuthSecretBase64: string,
163
+ payload: Uint8Array
164
+ ): Promise<EncryptedPushPayload> {
165
+ const clientPublicBytes = base64UrlDecode(clientPublicKeyBase64);
166
+ if (clientPublicBytes.length !== 65 || clientPublicBytes[0] !== 0x04) {
167
+ throw new Error('Invalid subscription p256dh key');
168
+ }
169
+ const authSecret = base64UrlDecode(clientAuthSecretBase64);
170
+ if (authSecret.length < 16) {
171
+ throw new Error('Invalid subscription auth secret');
172
+ }
173
+
174
+ const ephemeral = await crypto.subtle.generateKey(
175
+ { name: 'ECDH', namedCurve: 'P-256' },
176
+ true,
177
+ ['deriveBits']
178
+ );
179
+ const ephemeralPublicBytes = new Uint8Array(
180
+ await crypto.subtle.exportKey('raw', ephemeral.publicKey)
181
+ );
182
+ const clientPublicKey = await crypto.subtle.importKey(
183
+ 'raw',
184
+ clientPublicBytes,
185
+ { name: 'ECDH', namedCurve: 'P-256' },
186
+ false,
187
+ []
188
+ );
189
+ const sharedSecret = new Uint8Array(
190
+ await crypto.subtle.deriveBits(
191
+ { name: 'ECDH', public: clientPublicKey },
192
+ ephemeral.privateKey,
193
+ 256
194
+ )
195
+ );
196
+
197
+ const salt = crypto.getRandomValues(new Uint8Array(16));
198
+
199
+ // `key_info` binds the secret to this exact sender/receiver pair, so a
200
+ // ciphertext cannot be transplanted onto another subscription.
201
+ const keyInfo = concat(
202
+ textEncoder.encode('WebPush: info\0'),
203
+ clientPublicBytes,
204
+ ephemeralPublicBytes
205
+ );
206
+ const secret = await hkdf(authSecret, sharedSecret, keyInfo, 32);
207
+ const contentEncryptionKey = await hkdf(
208
+ salt,
209
+ secret,
210
+ textEncoder.encode('Content-Encoding: aes128gcm\0'),
211
+ 16
212
+ );
213
+ const nonce = await hkdf(salt, secret, textEncoder.encode('Content-Encoding: nonce\0'), 12);
214
+
215
+ // Single record: payload + 0x02 delimiter, no extra padding.
216
+ const plaintext = concat(payload, new Uint8Array([0x02]));
217
+ const aesKey = await crypto.subtle.importKey('raw', contentEncryptionKey, 'AES-GCM', false, [
218
+ 'encrypt'
219
+ ]);
220
+ const ciphertext = new Uint8Array(
221
+ await crypto.subtle.encrypt({ name: 'AES-GCM', iv: nonce }, aesKey, plaintext)
222
+ );
223
+
224
+ const header = new Uint8Array(16 + 4 + 1 + ephemeralPublicBytes.length);
225
+ header.set(salt, 0);
226
+ new DataView(header.buffer).setUint32(16, RECORD_SIZE, false);
227
+ header[20] = ephemeralPublicBytes.length;
228
+ header.set(ephemeralPublicBytes, 21);
229
+
230
+ return { body: concat(header, ciphertext) };
231
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Detect on-disk skills (managed effective copies + adoptable real ones) for the
3
+ * Settings UI — the same "detect & link" surface Subagents already had, which
4
+ * Skills never got despite being the feature most likely to already exist on a
5
+ * developer's machine (`~/.claude/skills`, `~/.qwen/skills`, …).
6
+ *
7
+ * Global scope only for now — project scope is surfaced by the per-project
8
+ * detection path when a project is supplied.
9
+ */
10
+
11
+ import { detectArtifacts, ARTIFACT_ENGINES, type DetectedArtifact, type ArtifactEngine } from '$backend/artifacts';
12
+
13
+ export interface DetectedSkillGroup {
14
+ engine: ArtifactEngine;
15
+ detected: DetectedArtifact[];
16
+ }
17
+
18
+ /** Detect skills across all engines for the given scope. */
19
+ export async function detectSkills(projectPath?: string): Promise<DetectedSkillGroup[]> {
20
+ const scope = projectPath ? 'project' : 'global';
21
+ const groups = await Promise.all(
22
+ ARTIFACT_ENGINES.map(async engine => ({
23
+ engine,
24
+ detected: await detectArtifacts('skill', { engine, scope, projectPath })
25
+ }))
26
+ );
27
+ return groups.filter(g => g.detected.length > 0);
28
+ }
@@ -3,19 +3,37 @@
3
3
  *
4
4
  * The single entry point the rest of the backend imports from. Hides the split
5
5
  * between the DB metadata table, the on-disk canonical store, the marketplace
6
- * providers, and the per-engine sync layer.
6
+ * providers, the slash-invocation expander, and the per-engine sync layer.
7
+ *
8
+ * Since migration 079 this module owns what used to be two features: a skill is
9
+ * invoked by the MODEL (`auto` trigger, advertised through its description) or
10
+ * by the USER (`slash` trigger, typed as `/<slug>` and expanded here), or both.
7
11
  *
8
12
  * - SERVICE (`./service`) — CRUD used by the WS layer (Settings → Skills).
13
+ * - INVOKE (`./invoke`) — expand `/<slug> args` into the engine prompt.
9
14
  * - MARKETPLACE (`./marketplace`) — browse + install from external providers.
10
- * - SYNC (`./sync`) — materialize enabled skills for each engine,
15
+ * - DETECT (`./detect`) — on-disk skills, managed and adoptable.
16
+ * - SYNC (`./sync`) — materialize active skills for each engine,
11
17
  * called at stream start by the adapters.
12
18
  */
13
19
 
14
20
  export { skillService } from './service';
15
- export type { SkillDTO, ParsedSkillPreview } from './service';
21
+ export type { SkillDTO, SkillInputFields, ParsedSkillPreview, AvailableSkill } from './service';
22
+
23
+ export { expandSlashInvocation, parseSlashInvocation } from './invoke';
24
+ export type { ExpandedInvocation, SlashInvocation, InvocationContext } from './invoke';
16
25
 
17
26
  export { listMarketplaceSkills, fetchMarketplaceSkill } from './marketplace';
18
27
  export type { MarketplaceSkill, MarketplacePage } from './marketplace';
19
28
 
20
- export { syncSkills, syncSkillsAllEngines, buildSkillsPromptContext } from './sync';
29
+ export { detectSkills } from './detect';
30
+ export type { DetectedSkillGroup } from './detect';
31
+
32
+ export {
33
+ syncSkills,
34
+ syncSkillsAllEngines,
35
+ buildSkillsPromptContext,
36
+ stripLegacyCommandArtifacts,
37
+ skillFileReady
38
+ } from './sync';
21
39
  export type { SkillEngine } from './sync';
@@ -0,0 +1,114 @@
1
+ /**
2
+ * Slash invocation is the seam where a user's `/review-pr 123` becomes the
3
+ * prompt an engine actually runs. Two properties have to hold without a database
4
+ * or an engine in the loop, and both are easy to break silently:
5
+ *
6
+ * 1. RECOGNITION — a message is only an invocation when it really is one. The
7
+ * pattern has to reject `/usr/bin/env`, a bare `/`, and a URL path, or an
8
+ * ordinary message gets swallowed and replaced by a skill body.
9
+ * 2. SUBSTITUTION — the `$ARGUMENTS` / `$1`…`$9` contract users know from
10
+ * `.claude/commands/*.md`. Getting `consumed` wrong is what decides whether
11
+ * typed arguments reach the model at all.
12
+ */
13
+
14
+ import { describe, expect, test } from 'bun:test';
15
+ import { parseSlashInvocation, substituteArgs } from './invoke';
16
+ import { parseTriggers, stringifyTriggers, parseUses } from '$backend/database/queries';
17
+
18
+ describe('parseSlashInvocation', () => {
19
+ test('recognises a bare command', () => {
20
+ expect(parseSlashInvocation('/review-pr')).toEqual({ slug: 'review-pr', args: '' });
21
+ });
22
+
23
+ test('recognises a command with arguments', () => {
24
+ expect(parseSlashInvocation('/review-pr 123 --deep')).toEqual({ slug: 'review-pr', args: '123 --deep' });
25
+ });
26
+
27
+ test('tolerates leading whitespace and a trailing newline', () => {
28
+ expect(parseSlashInvocation(' /deploy staging\n')).toEqual({ slug: 'deploy', args: 'staging' });
29
+ });
30
+
31
+ test('keeps multi-line arguments intact', () => {
32
+ const parsed = parseSlashInvocation('/summarise first line\nsecond line');
33
+ expect(parsed?.slug).toBe('summarise');
34
+ expect(parsed?.args).toBe('first line\nsecond line');
35
+ });
36
+
37
+ test('is not fooled by a path', () => {
38
+ expect(parseSlashInvocation('/usr/bin/env python')).toBeNull();
39
+ expect(parseSlashInvocation('/')).toBeNull();
40
+ expect(parseSlashInvocation('/Users/me/notes.md')).toBeNull();
41
+ });
42
+
43
+ test('ignores a slash that is not at the start of the message', () => {
44
+ expect(parseSlashInvocation('run /review-pr for me')).toBeNull();
45
+ });
46
+
47
+ test('rejects slugs outside the skill slug grammar', () => {
48
+ expect(parseSlashInvocation('/Review-PR')).toBeNull();
49
+ expect(parseSlashInvocation('/review_pr')).toBeNull();
50
+ expect(parseSlashInvocation('/-leading')).toBeNull();
51
+ });
52
+ });
53
+
54
+ describe('substituteArgs', () => {
55
+ test('replaces $ARGUMENTS with the whole argument string', () => {
56
+ const result = substituteArgs('Review PR $ARGUMENTS now.', '123 --deep');
57
+ expect(result.text).toBe('Review PR 123 --deep now.');
58
+ expect(result.consumed).toBe(true);
59
+ });
60
+
61
+ test('replaces positional arguments', () => {
62
+ const result = substituteArgs('Compare $1 against $2.', 'main feature-x');
63
+ expect(result.text).toBe('Compare main against feature-x.');
64
+ expect(result.consumed).toBe(true);
65
+ });
66
+
67
+ test('renders a missing positional as empty rather than leaving the placeholder', () => {
68
+ const result = substituteArgs('Deploy $1 to $2.', 'app');
69
+ expect(result.text).toBe('Deploy app to .');
70
+ expect(result.consumed).toBe(true);
71
+ });
72
+
73
+ test('reports nothing consumed when the body has no placeholder', () => {
74
+ // The caller relies on this to append the arguments explicitly — otherwise
75
+ // what the user typed after the command would vanish.
76
+ const result = substituteArgs('Run the standard review.', '123');
77
+ expect(result.text).toBe('Run the standard review.');
78
+ expect(result.consumed).toBe(false);
79
+ });
80
+
81
+ test('leaves a bare dollar amount alone', () => {
82
+ const result = substituteArgs('It costs $10 and $ARGUMENTSX stays.', 'x');
83
+ expect(result.text).toBe('It costs $10 and $ARGUMENTSX stays.');
84
+ expect(result.consumed).toBe(false);
85
+ });
86
+ });
87
+
88
+ describe('trigger and uses parsing', () => {
89
+ test('an unset or unrecognised trigger list falls back to auto', () => {
90
+ // A skill with no invocable trigger would be dead weight nobody can reach,
91
+ // so the parser refuses to produce that state.
92
+ expect(parseTriggers(null)).toEqual(['auto']);
93
+ expect(parseTriggers('')).toEqual(['auto']);
94
+ expect(parseTriggers('nonsense')).toEqual(['auto']);
95
+ });
96
+
97
+ test('parses and de-duplicates a trigger list', () => {
98
+ expect(parseTriggers('slash')).toEqual(['slash']);
99
+ expect(parseTriggers(' auto , slash , auto ')).toEqual(['auto', 'slash']);
100
+ });
101
+
102
+ test('serializes triggers in canonical order', () => {
103
+ expect(stringifyTriggers(['slash', 'auto'])).toBe('auto,slash');
104
+ expect(stringifyTriggers([])).toBe('auto');
105
+ expect(stringifyTriggers(undefined)).toBe('auto');
106
+ });
107
+
108
+ test('tolerates a corrupt uses column', () => {
109
+ expect(parseUses('["a","b","a"]')).toEqual(['a', 'b']);
110
+ expect(parseUses('not json')).toEqual([]);
111
+ expect(parseUses(null)).toEqual([]);
112
+ expect(parseUses('{"a":1}')).toEqual([]);
113
+ });
114
+ });
@@ -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
+ }