@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,315 @@
1
+ /**
2
+ * Worktree database branching — shared vocabulary.
3
+ *
4
+ * The worktree manager talks about a BRANCH DATABASE, not about Neon. Every
5
+ * provider that can offer the `worktree-branching` capability is normalised
6
+ * into these shapes by an adapter, and the manager never learns which one
7
+ * answered — the same test `Task 2` and `Task 3` set for their surfaces: if
8
+ * Turso needs a second dialog, these types are wrong and fixing them is the
9
+ * work.
10
+ *
11
+ * The word "branch" is deliberately NOT baked into the copy. Neon cuts a real
12
+ * copy-on-write branch; Turso seeds a whole new database from a parent. Both
13
+ * are "an isolated database derived from a parent", and `BranchProviderInfo`
14
+ * carries the noun each provider uses so the dialog can say what actually
15
+ * happens rather than calling a seeded database a branch.
16
+ *
17
+ * Nothing here carries a credential. The connection string a branch answers on
18
+ * is resolved on the server, sealed on the branch row, and written into the
19
+ * worktree's environment — it never crosses this line.
20
+ */
21
+
22
+ import type { DbDriver, DbSslMode } from './db-client';
23
+
24
+ /**
25
+ * Where a worktree's database comes from.
26
+ *
27
+ * `account` is a provider that branches natively — Neon cuts a copy-on-write
28
+ * branch through its API. `connection` is everything else: a database Clopen
29
+ * can already reach, copied with that engine's own primitives. The second is
30
+ * the general case and the first is the optimisation, which is the opposite of
31
+ * how this feature started.
32
+ */
33
+ export type BranchSourceKind = 'account' | 'connection';
34
+
35
+ /** How much of the parent a worktree's database starts with. */
36
+ export type BranchDataMode = 'schema-data' | 'schema' | 'empty';
37
+
38
+ /**
39
+ * A place worktree databases can come from, as the setup dialog lists them.
40
+ *
41
+ * Accounts and connections are one list rather than two tabs: the user is
42
+ * choosing WHICH DATABASE, and whether the copy happens through a vendor API or
43
+ * through `CREATE DATABASE` is an implementation detail they should be told
44
+ * about, not asked to navigate.
45
+ */
46
+ export interface BranchSourceOption {
47
+ kind: BranchSourceKind;
48
+ /** The account id, or the DB Client connection id. */
49
+ id: string;
50
+ label: string;
51
+ /** Integration provider id for an account, driver id for a connection. */
52
+ provider: string;
53
+ providerName: string;
54
+ /** What this source calls one — "branch" for Neon, "copy" for the rest. */
55
+ noun: string;
56
+ /** True when the provider branches natively rather than Clopen copying. */
57
+ isNative: boolean;
58
+ /** One sentence naming what a copy here does not carry, or null. */
59
+ notice: string | null;
60
+ /** Health, for the same strip the accounts list uses. */
61
+ status: string;
62
+ }
63
+
64
+ /** A parent database a worktree's branch is cut from. */
65
+ export interface BranchParent {
66
+ /** The provider's own id for the parent — a Neon project id. */
67
+ ref: string;
68
+ name: string;
69
+ /** Region, plan — whatever tells two similarly named parents apart. */
70
+ detail: string | null;
71
+ /** The owning container's name, so which organisation is billed is visible. */
72
+ group: string | null;
73
+ /** Whether a branch can be cut from it right now. The ADAPTER decides. */
74
+ isReady: boolean;
75
+ }
76
+
77
+ /** Where a created branch answers. The password is server-side only. */
78
+ export interface BranchConnection {
79
+ /** The full URI, which is what lands in the worktree's environment. */
80
+ uri: string;
81
+ host: string;
82
+ port: number;
83
+ username: string;
84
+ password: string;
85
+ database: string;
86
+ sslMode: DbSslMode;
87
+ }
88
+
89
+ /** What an adapter hands back after cutting one. */
90
+ export interface CreatedBranch {
91
+ /** The provider's own id for the branch. */
92
+ ref: string;
93
+ /** The name it was actually given, which may differ from the one requested. */
94
+ name: string;
95
+ connection: BranchConnection;
96
+ }
97
+
98
+ /** A branch as it exists at the provider, for the orphan sweep. */
99
+ export interface RemoteBranch {
100
+ ref: string;
101
+ name: string;
102
+ createdAt: string | null;
103
+ /** A provider's default branch is never ours and is never offered for delete. */
104
+ isDefault: boolean;
105
+ /** Logical size in bytes, when the provider reports one. */
106
+ sizeBytes: number | null;
107
+ }
108
+
109
+ /** A branching provider as the setup dialog renders it. */
110
+ export interface BranchProviderInfo {
111
+ /** Matches the integration provider id, so the brand mark is the same one. */
112
+ id: string;
113
+ name: string;
114
+ /**
115
+ * What this provider calls one, singular and lowercase — "branch" for Neon,
116
+ * "database" for Turso. Used in copy so a seeded Turso database is never
117
+ * described as a branch.
118
+ */
119
+ noun: string;
120
+ /** What the parent is called — "Neon project". */
121
+ parentLabel: string;
122
+ description: string;
123
+ /** One sentence naming what cutting one actually costs. */
124
+ notice: string;
125
+ /** True when the provider can hand back a pooled endpoint as well. */
126
+ supportsPooled: boolean;
127
+ }
128
+
129
+ /**
130
+ * Per-project settings for branching.
131
+ *
132
+ * `envFile` has NO default worth guessing, which is why it is asked for at
133
+ * setup. Next.js and Vite read `.env.local` in PREFERENCE to `.env`, so writing
134
+ * the wrong one produces the worst possible outcome: the branch is created, the
135
+ * variable is written, and nothing reads it.
136
+ */
137
+ export interface WorktreeBranchConfig {
138
+ /** The variable the connection URI is written to. */
139
+ envVar: string;
140
+ /** Which dotenv file inside the worktree receives the managed block. */
141
+ envFile: string;
142
+ /** Offer it, ticked, on every worktree create. */
143
+ autoCreate: boolean;
144
+ /** Ask the provider for a pooled endpoint instead of a direct one. */
145
+ pooled: boolean;
146
+ /**
147
+ * How much of the parent a new worktree's database starts with.
148
+ *
149
+ * Remembered per project and overridable per worktree, because the right
150
+ * answer depends on the database rather than on the feature: a seeded dev
151
+ * database is worth copying whole, and a forty-gigabyte one is not.
152
+ */
153
+ dataMode: BranchDataMode;
154
+ }
155
+
156
+ export const DEFAULT_WORKTREE_BRANCH_CONFIG: WorktreeBranchConfig = {
157
+ envVar: 'DATABASE_URL',
158
+ envFile: '.env',
159
+ autoCreate: true,
160
+ // Direct, not pooled, and the default is not a question to ask. A worktree is
161
+ // where an agent runs migrations: a transaction-mode pooler breaks prepared
162
+ // statements and some DDL, and the failure arrives as a confusing driver
163
+ // error rather than as a configuration one.
164
+ pooled: false,
165
+ // Copying the data is what makes a worktree feel like the project rather
166
+ // than like an empty shell of it — the app starts, the fixtures are there,
167
+ // and an agent can actually run what it just changed.
168
+ dataMode: 'schema-data'
169
+ };
170
+
171
+ /** The binding for one project, as the worktree manager sees it. */
172
+ export interface WorktreeBranchBindingInfo {
173
+ projectId: string;
174
+ sourceKind: BranchSourceKind;
175
+ /** The account id, or the DB Client connection id. */
176
+ sourceId: string;
177
+ provider: string;
178
+ providerName: string;
179
+ /** The account's label, or the connection's name. */
180
+ sourceLabel: string;
181
+ parentRef: string;
182
+ parentName: string;
183
+ isNative: boolean;
184
+ config: WorktreeBranchConfig;
185
+ updatedAt: string;
186
+ }
187
+
188
+ /**
189
+ * What happened when the connection string was written into the worktree.
190
+ *
191
+ * `skipped-tracked` is the one that matters. A dotenv file that git TRACKS
192
+ * would be carried back to the main project by "Apply to Main", overwriting the
193
+ * real connection string with one that points at a database this worktree's
194
+ * deletion destroys. So it is refused rather than written, and the refusal is
195
+ * reported instead of being logged and forgotten.
196
+ */
197
+ export type BranchEnvStatus = 'written' | 'skipped-tracked' | 'failed';
198
+
199
+ /** A live or orphaned branch, as the manager sees it. */
200
+ export interface WorktreeBranchInfo {
201
+ id: string;
202
+ /** Null once the worktree is gone — which is what makes a row an orphan. */
203
+ worktreeId: string | null;
204
+ worktreeName: string | null;
205
+ sourceKind: BranchSourceKind;
206
+ provider: string;
207
+ providerName: string;
208
+ /** What this source calls one, so copy reads right per source. */
209
+ noun: string;
210
+ /** The account id, or the DB Client connection id. */
211
+ sourceId: string;
212
+ sourceLabel: string;
213
+ /** Which mechanism made it — `template`, `row-copy`, `file-copy`, … */
214
+ strategy: string | null;
215
+ /** One sentence naming what the copy did not carry, or null. */
216
+ notice: string | null;
217
+ parentRef: string;
218
+ branchRef: string;
219
+ branchName: string;
220
+ envVar: string;
221
+ envFile: string;
222
+ envStatus: BranchEnvStatus;
223
+ envDetail: string | null;
224
+ status: 'active' | 'orphaned';
225
+ /** Why it is orphaned — the provider's own words for the failed delete. */
226
+ error: string | null;
227
+ /** The projected DB Client connection, so the branch can be inspected. */
228
+ connectionId: string | null;
229
+ createdAt: string;
230
+ }
231
+
232
+ /**
233
+ * A branch at the provider that Clopen has no row for.
234
+ *
235
+ * The second half of orphan detection. A crash between "the provider created
236
+ * it" and "the row was written" leaves a branch nothing here knows about, and
237
+ * the only thing tying it back is the name — which is why branch names are
238
+ * deterministic and prefixed.
239
+ */
240
+ export interface UnknownRemoteBranch {
241
+ sourceKind: BranchSourceKind;
242
+ /** The account id, or the DB Client connection id. */
243
+ sourceId: string;
244
+ provider: string;
245
+ parentRef: string;
246
+ branch: RemoteBranch;
247
+ }
248
+
249
+ /** Everything the worktree manager's branching dialog renders. */
250
+ export interface WorktreeBranchingState {
251
+ providers: BranchProviderInfo[];
252
+ /**
253
+ * Everywhere a worktree database could come from — accounts AND connections.
254
+ *
255
+ * One list, because "which database" is one question. See
256
+ * `BranchSourceOption`.
257
+ */
258
+ sources: BranchSourceOption[];
259
+ binding: WorktreeBranchBindingInfo | null;
260
+ /** Dotenv files that already exist in the project, most-precedent first. */
261
+ envFiles: string[];
262
+ branches: WorktreeBranchInfo[];
263
+ }
264
+
265
+ /** The result of attaching a branch to a freshly created worktree. */
266
+ export interface BranchAttachResult {
267
+ branch: WorktreeBranchInfo | null;
268
+ /** What the copy did not carry, when it carried less than everything. */
269
+ notice?: string | null;
270
+ /**
271
+ * Why no branch was attached, when one was expected.
272
+ *
273
+ * Fail-soft is the rule: a provider outage must never cost the user the
274
+ * worktree they asked for, so this is reported alongside a worktree that was
275
+ * created successfully rather than thrown.
276
+ */
277
+ error: string | null;
278
+ }
279
+
280
+ /** The branch-name prefix every source-side name carries. */
281
+ export const BRANCH_NAME_PREFIX = 'clopen';
282
+
283
+ /**
284
+ * The binding a project would get if it asked for one.
285
+ *
286
+ * Derived from the project's own `.env` and Clopen's connection list, so the
287
+ * dialog can offer "also give it its own database" without the user having
288
+ * configured anything first. Null when the URL in the project's environment
289
+ * corresponds to no saved connection — Clopen would have the address but not
290
+ * the password, and an offer that fails at the moment of use is worse than no
291
+ * offer.
292
+ */
293
+ export interface BranchSuggestion {
294
+ sourceKind: 'connection';
295
+ sourceId: string;
296
+ sourceLabel: string;
297
+ providerName: string;
298
+ /** The database to copy — a name, or a file path for SQLite. */
299
+ parentRef: string;
300
+ parentName: string;
301
+ /** The variable the copy's URL should be written to. */
302
+ envVar: string;
303
+ /** Which dotenv file that variable already lives in. */
304
+ envFile: string;
305
+ /** What a copy here does not carry, or null. */
306
+ notice: string | null;
307
+ }
308
+
309
+ /** A database on a connection that a worktree copy could be made from. */
310
+ export interface BranchConnectionParent {
311
+ /** The database name, its file path for SQLite, its index for Redis. */
312
+ ref: string;
313
+ name: string;
314
+ driver: DbDriver;
315
+ }
@@ -48,6 +48,7 @@ export type LogLabel =
48
48
  | 'notes'
49
49
  | 'settings'
50
50
  | 'engine'
51
+ | 'env-files'
51
52
  | 'tunnel'
52
53
  | 'remote-access'
53
54
  | 'db-client'
@@ -1,25 +0,0 @@
1
- /**
2
- * Detect on-disk commands (managed effective copies + adoptable real ones) for
3
- * the Settings UI. Global scope only for now — project scope is surfaced by the
4
- * per-project detection path when a project is supplied.
5
- */
6
-
7
- import { detectArtifacts, type DetectedArtifact, type ArtifactEngine } from '$backend/artifacts';
8
-
9
- export interface DetectedCommandGroup {
10
- engine: ArtifactEngine;
11
- detected: DetectedArtifact[];
12
- }
13
-
14
- /** Detect commands across all engines for the given scope. */
15
- export async function detectCommands(projectPath?: string): Promise<DetectedCommandGroup[]> {
16
- const engines: ArtifactEngine[] = ['claude', 'codex', 'copilot', 'qwen', 'opencode', 'pi'];
17
- const scope = projectPath ? 'project' : 'global';
18
- const groups = await Promise.all(
19
- engines.map(async engine => ({
20
- engine,
21
- detected: await detectArtifacts('command', { engine, scope, projectPath })
22
- }))
23
- );
24
- return groups.filter(g => g.detected.length > 0);
25
- }
@@ -1,9 +0,0 @@
1
- /**
2
- * Custom Commands — public facade. Settings → Commands manages reusable slash
3
- * command prompts, materialized into each engine at stream start.
4
- */
5
-
6
- export { commandService } from './service';
7
- export type { CommandDTO, CommandInputFields } from './service';
8
- export { syncCommands, syncCommandsAllEngines, buildCommandsPromptContext } from './sync';
9
- export { detectCommands } from './detect';
@@ -1,178 +0,0 @@
1
- /**
2
- * Command service — keeps the `commands` table and the on-disk canonical store
3
- * (`{clopenDir}/commands/<slug>.md`) in lockstep for the Settings → Commands
4
- * CRUD surface. Mirrors the Skills service shape, minus the marketplace.
5
- */
6
-
7
- import { commandQueries, type CommandRow } from '$backend/database/queries';
8
- import { parseDoc, serializeDoc, uniqueSlug, parseEngineMap, stringifyEngineMap, type EngineMap } from '$backend/artifacts';
9
- import { debug } from '$shared/utils/logger';
10
- import {
11
- writeCommandMd,
12
- readCommandMd,
13
- deleteCommandMd,
14
- commandFileExists
15
- } from './store';
16
-
17
- export interface CommandDTO {
18
- id: number;
19
- slug: string;
20
- name: string;
21
- description: string;
22
- argumentHint: string | null;
23
- /** Per-engine model override (EngineType → model id; absent = inherit). */
24
- modelByEngine: EngineMap;
25
- source: 'custom' | 'imported';
26
- enabled: boolean;
27
- /** False when the DB row exists but its `.md` is missing on disk. */
28
- present: boolean;
29
- createdAt: string;
30
- }
31
-
32
- export interface CommandInputFields {
33
- name: string;
34
- description: string;
35
- argumentHint?: string | null;
36
- modelByEngine?: EngineMap;
37
- body: string;
38
- }
39
-
40
- const FRONTMATTER_ORDER = ['description', 'argument-hint'];
41
-
42
- function toDTO(row: CommandRow, present: boolean): CommandDTO {
43
- return {
44
- id: row.id,
45
- slug: row.slug,
46
- name: row.name,
47
- description: row.description,
48
- argumentHint: row.argument_hint,
49
- modelByEngine: parseEngineMap(row.model_by_engine),
50
- source: row.source,
51
- enabled: row.is_enabled === 1,
52
- present,
53
- createdAt: row.created_at
54
- };
55
- }
56
-
57
- /** An imported `.md` carries a single Claude-shaped model → map to the claude slot. */
58
- function singleModelToMap(model: string | undefined): EngineMap {
59
- return model?.trim() ? { 'claude-code': model.trim() } : {};
60
- }
61
-
62
- /**
63
- * Serialize editor fields into the canonical command `.md` document. Model is
64
- * per-engine and injected at sync time, so it is NOT written here.
65
- */
66
- function buildDocument(fields: CommandInputFields): string {
67
- const frontmatter: Record<string, string> = {};
68
- if (fields.description.trim()) frontmatter.description = fields.description.trim();
69
- if (fields.argumentHint?.trim()) frontmatter['argument-hint'] = fields.argumentHint.trim();
70
- return serializeDoc({ frontmatter, body: fields.body }, FRONTMATTER_ORDER);
71
- }
72
-
73
- export const commandService = {
74
- async list(): Promise<CommandDTO[]> {
75
- const rows = commandQueries.getAll();
76
- const presence = await Promise.all(rows.map(r => commandFileExists(r.slug)));
77
- return rows.map((row, i) => toDTO(row, presence[i]));
78
- },
79
-
80
- /**
81
- * Minimal list of commands for the chat "/" picker. Non-admin surface
82
- * (any user can invoke a command), so it exposes only display fields — no
83
- * bodies, no source/disk metadata.
84
- *
85
- * `profileFilter` mirrors {@link syncCommands}'s semantics: when an active
86
- * profile references ≥1 command, the picker shows exactly that set (even if
87
- * a referenced command is globally disabled) instead of the enabled set.
88
- */
89
- available(profileFilter?: Set<string> | null): { slug: string; name: string; description: string; argumentHint: string | null }[] {
90
- const rows = profileFilter
91
- ? commandQueries.getAll().filter(r => profileFilter.has(r.slug))
92
- : commandQueries.getEnabled();
93
- return rows.map(r => ({
94
- slug: r.slug,
95
- name: r.name,
96
- description: r.description,
97
- argumentHint: r.argument_hint
98
- }));
99
- },
100
-
101
- async get(id: number): Promise<{ command: CommandDTO; body: string } | null> {
102
- const row = commandQueries.getById(id);
103
- if (!row) return null;
104
- const raw = await readCommandMd(row.slug);
105
- const body = raw ? parseDoc(raw).body : '';
106
- return { command: toDTO(row, raw !== null), body };
107
- },
108
-
109
- async create(input: CommandInputFields): Promise<CommandDTO> {
110
- if (!input.name.trim()) throw new Error('A command name is required');
111
- const slug = uniqueSlug(input.name, s => !!commandQueries.getBySlug(s));
112
- await writeCommandMd(slug, buildDocument(input));
113
- const row = commandQueries.insert({
114
- slug,
115
- name: input.name.trim(),
116
- description: input.description.trim(),
117
- argumentHint: input.argumentHint?.trim() || null,
118
- modelByEngine: stringifyEngineMap(input.modelByEngine),
119
- source: 'custom'
120
- });
121
- debug.log('commands', `📦 Created command: ${slug}`);
122
- return toDTO(row, true);
123
- },
124
-
125
- async update(id: number, input: CommandInputFields): Promise<CommandDTO> {
126
- const row = commandQueries.getById(id);
127
- if (!row) throw new Error('Command not found');
128
- await writeCommandMd(row.slug, buildDocument(input));
129
- commandQueries.updateMeta(
130
- id,
131
- input.name.trim(),
132
- input.description.trim(),
133
- input.argumentHint?.trim() || null,
134
- stringifyEngineMap(input.modelByEngine)
135
- );
136
- debug.log('commands', `🔧 Updated command: ${row.slug}`);
137
- return toDTO(commandQueries.getById(id)!, true);
138
- },
139
-
140
- /** Preview a pasted command `.md` (its frontmatter + body) before importing. */
141
- parsePreview(raw: string): { name: string; description: string; argumentHint: string | null; modelByEngine: EngineMap; body: string } {
142
- const parsed = parseDoc(raw);
143
- return {
144
- name: parsed.frontmatter.name || '',
145
- description: parsed.frontmatter.description || '',
146
- argumentHint: parsed.frontmatter['argument-hint'] || null,
147
- modelByEngine: singleModelToMap(parsed.frontmatter.model),
148
- body: parsed.body
149
- };
150
- },
151
-
152
- async import(raw: string, nameHint?: string): Promise<CommandDTO> {
153
- const parsed = parseDoc(raw);
154
- const displayName = (nameHint?.trim() || parsed.frontmatter.name || 'command').trim();
155
- return this.create({
156
- name: displayName,
157
- description: parsed.frontmatter.description || '',
158
- argumentHint: parsed.frontmatter['argument-hint'] || null,
159
- modelByEngine: singleModelToMap(parsed.frontmatter.model),
160
- body: parsed.body
161
- });
162
- },
163
-
164
- toggle(id: number, enabled: boolean): CommandDTO {
165
- const row = commandQueries.getById(id);
166
- if (!row) throw new Error('Command not found');
167
- commandQueries.setEnabled(id, enabled);
168
- return toDTO(commandQueries.getById(id)!, true);
169
- },
170
-
171
- async remove(id: number): Promise<void> {
172
- const row = commandQueries.getById(id);
173
- if (!row) throw new Error('Command not found');
174
- await deleteCommandMd(row.slug);
175
- commandQueries.remove(id);
176
- debug.log('commands', `🗑️ Deleted command: ${row.slug}`);
177
- }
178
- };
@@ -1,45 +0,0 @@
1
- /**
2
- * Canonical command store — the single source of truth on disk. Every managed
3
- * command is one Markdown file under `{clopenDir}/commands/<slug>.md` (a
4
- * `single-md` artifact). The DB (`commands` table) tracks only metadata + the
5
- * enable toggle; the sync layer mirrors enabled commands into each engine's
6
- * commands dir (native) or a synthetic preamble.
7
- */
8
-
9
- import { join } from 'path';
10
- import { mkdir, rm, stat, writeFile, readFile } from 'node:fs/promises';
11
- import { getClopenDir } from '$backend/utils/paths';
12
- import { debug } from '$shared/utils/logger';
13
-
14
- export function getCommandsRootDir(): string {
15
- return join(getClopenDir(), 'commands');
16
- }
17
-
18
- export function getCommandPath(slug: string): string {
19
- return join(getCommandsRootDir(), `${slug}.md`);
20
- }
21
-
22
- async function pathExists(path: string): Promise<boolean> {
23
- try { await stat(path); return true; } catch { return false; }
24
- }
25
-
26
- export function commandFileExists(slug: string): Promise<boolean> {
27
- return pathExists(getCommandPath(slug));
28
- }
29
-
30
- export async function readCommandMd(slug: string): Promise<string | null> {
31
- const path = getCommandPath(slug);
32
- if (!(await pathExists(path))) return null;
33
- return readFile(path, 'utf8');
34
- }
35
-
36
- export async function writeCommandMd(slug: string, content: string): Promise<void> {
37
- await mkdir(getCommandsRootDir(), { recursive: true });
38
- await writeFile(getCommandPath(slug), content, 'utf8');
39
- debug.log('commands', `💾 Wrote command ${slug}.md`);
40
- }
41
-
42
- export async function deleteCommandMd(slug: string): Promise<void> {
43
- await rm(getCommandPath(slug), { force: true });
44
- debug.log('commands', `🗑️ Removed command ${slug}.md`);
45
- }
@@ -1,94 +0,0 @@
1
- /**
2
- * Engine sync for Commands — a thin adapter over the shared artifact framework.
3
- * Enabled commands are mirrored as `<slug>.md` into each engine's native
4
- * commands dir (Claude: `.../commands/`) or listed in a synthetic preamble for
5
- * engines with no native command concept (best-effort/unverified).
6
- *
7
- * Never throws — a stream never breaks because commands couldn't sync.
8
- */
9
-
10
- import { commandQueries } from '$backend/database/queries';
11
- import { debug } from '$shared/utils/logger';
12
- import { materializeArtifacts, resolveArtifact, isPromptScopedEngine, parseDoc, serializeDoc, parseEngineMap, artifactEngineToType, type ManagedArtifact, type ArtifactEngine } from '$backend/artifacts';
13
- import { artifactFilter } from '$backend/profiles';
14
- import { readCommandMd } from './store';
15
-
16
- /**
17
- * Shape a command document for the engine's native format, injecting that
18
- * engine's model override (per-engine; the canonical `.md` carries no model):
19
- * - Codex custom prompts are PLAIN markdown (no frontmatter, no model) — emit the body.
20
- * - Claude / OpenCode read frontmatter — re-serialize with the injected model.
21
- */
22
- function documentForEngine(engine: ArtifactEngine, raw: string, model?: string): string {
23
- const { frontmatter, body } = parseDoc(raw);
24
- if (engine === 'codex') return body;
25
- const fm: Record<string, string> = {};
26
- if (frontmatter.description) fm.description = frontmatter.description;
27
- if (frontmatter['argument-hint']) fm['argument-hint'] = frontmatter['argument-hint'];
28
- if (model) fm.model = model;
29
- return serializeDoc({ frontmatter: fm, body }, ['description', 'argument-hint', 'model']);
30
- }
31
-
32
- function buildCommandsPreamble(items: ManagedArtifact[]): string {
33
- if (items.length === 0) return '';
34
- const lines = ['# Available Commands', '', 'User-defined command prompts you can follow when the user invokes one by name:', ''];
35
- for (const c of items) lines.push(`- **/${c.slug}** — ${c.description || c.name}`);
36
- return lines.join('\n');
37
- }
38
-
39
- /** The commands active for a stream, narrowed by the active Profile (metadata only). */
40
- function resolveEnabledCommandsMeta(profileId?: number): ManagedArtifact[] {
41
- const filter = artifactFilter(profileId, 'command');
42
- return (filter ? commandQueries.getAll() : commandQueries.getEnabled())
43
- .filter(r => !filter || filter.has(r.slug))
44
- .map(r => ({ slug: r.slug, name: r.name, description: r.description }));
45
- }
46
-
47
- /**
48
- * The profile-scoped commands preamble for PER-SESSION injection into a
49
- * prompt-scoped engine's prompt (OpenCode/Codex/Copilot). Returns '' when none
50
- * apply. Advisory: it scopes what the model surfaces/uses, on top of whatever the
51
- * engine's own (possibly stale/shared) command registry exposes.
52
- */
53
- export function buildCommandsPromptContext(profileId?: number): string {
54
- return buildCommandsPreamble(resolveEnabledCommandsMeta(profileId));
55
- }
56
-
57
- export async function syncCommands(engine: ArtifactEngine, profileId?: number): Promise<void> {
58
- try {
59
- // On a prompt-scoped engine, a SYNTHETIC command target (no native command
60
- // dir — Copilot) is delivered per-session via prompt injection instead, so
61
- // materialize an empty set to strip any shared global block that would leak
62
- // across sessions. NATIVE command engines (Claude/OpenCode/Codex) keep the
63
- // filtered files on disk; Qwen (per-query) keeps its synthetic preamble.
64
- const synthetic = resolveArtifact('command', { engine, scope: 'global' }).format === 'preamble-region';
65
- const viaPrompt = synthetic && isPromptScopedEngine(engine);
66
- const filter = artifactFilter(profileId, 'command');
67
- // A profile activates the commands it references even if globally disabled;
68
- // with no profile filter, only the enabled set applies (unchanged).
69
- const rows = viaPrompt ? [] : (filter ? commandQueries.getAll() : commandQueries.getEnabled())
70
- .filter(r => !filter || filter.has(r.slug));
71
- const engineType = artifactEngineToType(engine);
72
- const enabled: ManagedArtifact[] = [];
73
- for (const row of rows) {
74
- const raw = await readCommandMd(row.slug);
75
- if (raw == null) continue; // file missing on disk — skip silently
76
- const model = parseEngineMap(row.model_by_engine)[engineType];
77
- enabled.push({ slug: row.slug, name: row.name, description: row.description, document: documentForEngine(engine, raw, model) });
78
- }
79
- const managedSlugs = commandQueries.getAll().map(r => r.slug);
80
- await materializeArtifacts('command', { engine, scope: 'global' }, {
81
- enabled,
82
- managedSlugs,
83
- buildPreamble: buildCommandsPreamble
84
- });
85
- debug.log('commands', `⌨️ Synced ${enabled.length} command(s) → ${engine}`);
86
- } catch (error) {
87
- debug.warn('commands', `⚠️ Command sync for ${engine} failed (continuing without):`, error);
88
- }
89
- }
90
-
91
- export async function syncCommandsAllEngines(): Promise<void> {
92
- const engines: ArtifactEngine[] = ['claude', 'codex', 'copilot', 'qwen', 'opencode', 'pi'];
93
- await Promise.all(engines.map(syncCommands));
94
- }