@myrialabs/clopen 0.4.7 → 0.4.9

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 (115) hide show
  1. package/backend/artifacts/detect.ts +129 -0
  2. package/backend/artifacts/engine-map.ts +53 -0
  3. package/backend/artifacts/frontmatter.ts +68 -0
  4. package/backend/artifacts/generate.ts +105 -0
  5. package/backend/artifacts/index.ts +34 -0
  6. package/backend/artifacts/markers.ts +76 -0
  7. package/backend/artifacts/matrix.ts +247 -0
  8. package/backend/artifacts/slug.ts +35 -0
  9. package/backend/artifacts/sync.ts +130 -0
  10. package/backend/artifacts/types.ts +152 -0
  11. package/backend/auth/permissions.ts +51 -1
  12. package/backend/chat/stream-manager.ts +14 -1
  13. package/backend/commands/detect.ts +25 -0
  14. package/backend/commands/index.ts +9 -0
  15. package/backend/commands/service.ts +178 -0
  16. package/backend/commands/store.ts +45 -0
  17. package/backend/commands/sync.ts +94 -0
  18. package/backend/database/migrations/045_create_commands_table.ts +28 -0
  19. package/backend/database/migrations/046_create_subagents_table.ts +29 -0
  20. package/backend/database/migrations/047_create_instructions_table.ts +29 -0
  21. package/backend/database/migrations/048_add_mcp_tool_overrides.ts +23 -0
  22. package/backend/database/migrations/049_create_permission_sets_table.ts +50 -0
  23. package/backend/database/migrations/050_create_profiles_tables.ts +57 -0
  24. package/backend/database/migrations/051_add_profile_to_sessions.ts +20 -0
  25. package/backend/database/migrations/052_add_default_profile_to_projects.ts +20 -0
  26. package/backend/database/migrations/053_add_profile_to_permission_sets.ts +37 -0
  27. package/backend/database/migrations/054_drop_subagent_agent_type.ts +20 -0
  28. package/backend/database/migrations/055_artifact_model_tools_per_engine.ts +43 -0
  29. package/backend/database/migrations/index.ts +77 -0
  30. package/backend/database/queries/command-queries.ts +82 -0
  31. package/backend/database/queries/index.ts +12 -2
  32. package/backend/database/queries/instruction-queries.ts +62 -0
  33. package/backend/database/queries/mcp-server-queries.ts +25 -0
  34. package/backend/database/queries/permission-set-queries.ts +155 -0
  35. package/backend/database/queries/profile-queries.ts +118 -0
  36. package/backend/database/queries/project-queries.ts +14 -0
  37. package/backend/database/queries/session-queries.ts +10 -0
  38. package/backend/database/queries/subagent-queries.ts +92 -0
  39. package/backend/db-client/drivers/mysql.ts +21 -0
  40. package/backend/db-client/drivers/postgres.ts +20 -0
  41. package/backend/db-client/drivers/sqlite.ts +21 -0
  42. package/backend/db-client/drivers/types.ts +19 -0
  43. package/backend/db-client/query-executor.ts +89 -1
  44. package/backend/engine/adapters/claude/stream.ts +27 -3
  45. package/backend/engine/adapters/codex/stream.ts +46 -14
  46. package/backend/engine/adapters/copilot/stream.ts +58 -4
  47. package/backend/engine/adapters/opencode/message-converter.ts +22 -2
  48. package/backend/engine/adapters/opencode/server.ts +166 -210
  49. package/backend/engine/adapters/opencode/stream.ts +150 -24
  50. package/backend/engine/adapters/qwen/stream.ts +23 -3
  51. package/backend/engine/artifact-sync.ts +51 -0
  52. package/backend/engine/types.ts +6 -0
  53. package/backend/instructions/index.ts +8 -0
  54. package/backend/instructions/service.ts +63 -0
  55. package/backend/instructions/sync.ts +56 -0
  56. package/backend/mcp/external/config.ts +42 -20
  57. package/backend/mcp/external/proxy.ts +89 -5
  58. package/backend/mcp/external/tools.ts +88 -0
  59. package/backend/mcp/index.ts +38 -15
  60. package/backend/mcp/internal/config.ts +48 -11
  61. package/backend/mcp/internal/remote-server.ts +9 -1
  62. package/backend/permissions/index.ts +27 -0
  63. package/backend/permissions/materialize.ts +96 -0
  64. package/backend/permissions/resolve.test.ts +162 -0
  65. package/backend/permissions/resolve.ts +106 -0
  66. package/backend/permissions/service.ts +167 -0
  67. package/backend/profiles/index.ts +10 -0
  68. package/backend/profiles/service.ts +169 -0
  69. package/backend/skills/index.ts +1 -1
  70. package/backend/skills/sync.ts +88 -128
  71. package/backend/subagents/detect.ts +23 -0
  72. package/backend/subagents/index.ts +10 -0
  73. package/backend/subagents/service.ts +166 -0
  74. package/backend/subagents/store.ts +44 -0
  75. package/backend/subagents/sync.ts +144 -0
  76. package/backend/ws/artifacts/generate.ts +51 -0
  77. package/backend/ws/artifacts/index.ts +8 -0
  78. package/backend/ws/chat/stream.ts +33 -2
  79. package/backend/ws/commands/crud.ts +157 -0
  80. package/backend/ws/commands/index.ts +8 -0
  81. package/backend/ws/db-client/query-history-retention.test.ts +217 -0
  82. package/backend/ws/db-client/query.ts +77 -2
  83. package/backend/ws/git/branch.ts +4 -2
  84. package/backend/ws/git/ignored.ts +65 -0
  85. package/backend/ws/git/index.ts +3 -1
  86. package/backend/ws/git/remote.ts +21 -11
  87. package/backend/ws/index.ts +17 -1
  88. package/backend/ws/instructions/crud.ts +53 -0
  89. package/backend/ws/instructions/index.ts +8 -0
  90. package/backend/ws/mcp/crud.ts +7 -1
  91. package/backend/ws/mcp/index.ts +4 -1
  92. package/backend/ws/mcp/tools.ts +112 -0
  93. package/backend/ws/permissions/crud.ts +72 -0
  94. package/backend/ws/permissions/index.ts +8 -0
  95. package/backend/ws/profiles/crud.ts +149 -0
  96. package/backend/ws/profiles/index.ts +9 -0
  97. package/backend/ws/subagents/crud.ts +136 -0
  98. package/backend/ws/subagents/index.ts +8 -0
  99. package/dist/assets/__vite-browser-external-BIHI7g3E.js +1 -0
  100. package/dist/assets/index-BdRui-1z.js +1 -0
  101. package/dist/assets/{index-xrB3zcfA.js → index-BjaIjmd4.js} +1 -1
  102. package/dist/assets/{main-LBI3a0n5.js → main-Cf8SUfQ1.js} +387 -302
  103. package/dist/assets/main-D4pdkiQK.css +1 -0
  104. package/dist/assets/zipkit-engine-CaR0t_Uy.wasm +0 -0
  105. package/dist/index.html +2 -2
  106. package/package.json +1 -1
  107. package/shared/constants/engine-tools.ts +56 -0
  108. package/shared/types/database/schema.ts +2 -0
  109. package/shared/types/db-client/query.ts +33 -0
  110. package/shared/types/stores/settings.ts +15 -0
  111. package/shared/types/unified/stream.ts +7 -0
  112. package/shared/utils/db-client/split-sql.test.ts +88 -0
  113. package/shared/utils/db-client/split-sql.ts +132 -0
  114. package/shared/utils/logger.ts +6 -0
  115. package/dist/assets/main-BXS8bjJ6.css +0 -1
@@ -0,0 +1,247 @@
1
+ /**
2
+ * Capability matrix — resolves, for a given `artifactType × engine × scope`, WHERE
3
+ * and in WHAT SHAPE the artifact is materialized. This is the single table the
4
+ * generic writer/scanner consult; adding a feature means adding rows here, not
5
+ * new sync code.
6
+ *
7
+ * Path conventions:
8
+ * - Global effective paths live in the engine's ISOLATED config dir
9
+ * (`getEngineUserConfigDir`) so Clopen never mixes with the user's own CLI
10
+ * usage — except Qwen/Copilot skills, which resolve their dir from `$HOME`
11
+ * with no override (see the original Skills sync rationale).
12
+ * - Project effective paths live inside the repo (`.claude/…`, `CLAUDE.md`, …).
13
+ * - `locateReal` returns the user's REAL standard locations (`~/.claude/…`),
14
+ * scanned by "detect & link" so existing on-disk artifacts can be adopted.
15
+ *
16
+ * Non-Claude synthetic targets follow each engine's documented global-memory
17
+ * convention but are BEST-EFFORT / unverified — surfaced with a marker so the UI
18
+ * never claims they definitely take effect.
19
+ */
20
+
21
+ import { join } from 'path';
22
+ import { homedir } from 'os';
23
+ import { getEngineUserConfigDir } from '$backend/utils/paths';
24
+ import type {
25
+ ArtifactContext,
26
+ ArtifactEngine,
27
+ ArtifactFormat,
28
+ ArtifactResolution,
29
+ ArtifactType,
30
+ ArtifactScope
31
+ } from './types';
32
+
33
+ /** Per-engine global memory file that synthetic artifacts / instructions target. */
34
+ function memoryFileName(engine: ArtifactEngine): string {
35
+ switch (engine) {
36
+ case 'claude': return 'CLAUDE.md';
37
+ case 'qwen': return 'QWEN.md';
38
+ // Codex, OpenCode and Copilot all standardise on AGENTS.md.
39
+ default: return 'AGENTS.md';
40
+ }
41
+ }
42
+
43
+ /** Absolute path to the engine's global memory file (isolated dir). */
44
+ function globalMemoryFile(engine: ArtifactEngine): string {
45
+ const base = getEngineUserConfigDir(engine);
46
+ // OpenCode nests its config under an `opencode/` subdir (XDG layout).
47
+ if (engine === 'opencode') return join(base, 'opencode', memoryFileName(engine));
48
+ return join(base, memoryFileName(engine));
49
+ }
50
+
51
+ /** Absolute path to a project-repo memory file. */
52
+ function projectMemoryFile(engine: ArtifactEngine, projectPath: string): string {
53
+ return join(projectPath, memoryFileName(engine));
54
+ }
55
+
56
+ /**
57
+ * Native artifact directory for a `(type, engine, scope)`, or null when that
58
+ * engine has NO native location for the type (→ falls back to a synthetic
59
+ * preamble). Each engine's directory/format differs, so this is an explicit
60
+ * table rather than a `<subdir>` convention:
61
+ * - Claude: `<config>/{skills,commands,agents}` (global) or `.claude/…` (project).
62
+ * - OpenCode: markdown commands in `<config>/opencode/command/` and subagents in
63
+ * `<config>/opencode/agent/` — https://opencode.ai/docs/commands, /docs/agents.
64
+ * - Codex: markdown custom prompts in `$CODEX_HOME/prompts/` (global only).
65
+ * - Qwen/Copilot: only skills, resolved from the real `$HOME`.
66
+ */
67
+ function nativeDir(type: ArtifactType, ctx: ArtifactContext): string | null {
68
+ const { engine, scope, projectPath } = ctx;
69
+ const base = getEngineUserConfigDir(engine);
70
+ const proj = scope === 'project' ? projectPath : undefined;
71
+
72
+ if (type === 'skill') {
73
+ switch (engine) {
74
+ case 'claude': return scope === 'global' ? join(base, 'skills') : proj ? join(proj, '.claude', 'skills') : null;
75
+ case 'qwen': return scope === 'global' ? join(homedir(), '.qwen', 'skills') : null;
76
+ case 'copilot': return scope === 'global' ? join(homedir(), '.copilot', 'skills') : null;
77
+ default: return null;
78
+ }
79
+ }
80
+ if (type === 'command') {
81
+ switch (engine) {
82
+ case 'claude': return scope === 'global' ? join(base, 'commands') : proj ? join(proj, '.claude', 'commands') : null;
83
+ case 'opencode': return scope === 'global' ? join(base, 'opencode', 'command') : proj ? join(proj, '.opencode', 'command') : null;
84
+ case 'codex': return scope === 'global' ? join(base, 'prompts') : null;
85
+ default: return null;
86
+ }
87
+ }
88
+ if (type === 'subagent') {
89
+ switch (engine) {
90
+ case 'claude': return scope === 'global' ? join(base, 'agents') : proj ? join(proj, '.claude', 'agents') : null;
91
+ case 'opencode': return scope === 'global' ? join(base, 'opencode', 'agent') : proj ? join(proj, '.opencode', 'agent') : null;
92
+ default: return null;
93
+ }
94
+ }
95
+ return null;
96
+ }
97
+
98
+ /** The user's REAL standard global locations for detect & link. */
99
+ function realGlobalLocations(type: ArtifactType, engine: ArtifactEngine): string[] {
100
+ const home = homedir();
101
+ if (type === 'skill') {
102
+ if (engine === 'claude') return [join(home, '.claude', 'skills')];
103
+ if (engine === 'qwen') return [join(home, '.qwen', 'skills')];
104
+ if (engine === 'copilot') return [join(home, '.copilot', 'skills')];
105
+ }
106
+ if (type === 'command') {
107
+ if (engine === 'claude') return [join(home, '.claude', 'commands')];
108
+ if (engine === 'opencode') return [join(home, '.config', 'opencode', 'command')];
109
+ if (engine === 'codex') return [join(home, '.codex', 'prompts')];
110
+ }
111
+ if (type === 'subagent') {
112
+ if (engine === 'claude') return [join(home, '.claude', 'agents')];
113
+ if (engine === 'opencode') return [join(home, '.config', 'opencode', 'agent')];
114
+ }
115
+ return [];
116
+ }
117
+
118
+ const FORMAT_BY_TYPE: Partial<Record<ArtifactType, ArtifactFormat>> = {
119
+ // Skills mirror a whole folder; commands/subagents are one file each.
120
+ skill: 'folder-md',
121
+ command: 'single-md',
122
+ subagent: 'single-md'
123
+ };
124
+
125
+ /**
126
+ * Resolve the materialization contract for one artifact in one engine/scope.
127
+ * Returns `{ supported: false }` for combinations with no file representation
128
+ * (notably `'mcp'`, which is handled by the config-object path, not here).
129
+ */
130
+ export function resolveArtifact(type: ArtifactType, ctx: ArtifactContext): ArtifactResolution {
131
+ const { engine, scope } = ctx;
132
+
133
+ // Instructions are always a marker-region inside the engine memory file.
134
+ if (type === 'instruction') {
135
+ return {
136
+ supported: true,
137
+ format: 'preamble-region',
138
+ ownership: 'marker-region',
139
+ locateEffective: (c) =>
140
+ c.scope === 'project' && c.projectPath
141
+ ? projectMemoryFile(engine, c.projectPath)
142
+ : globalMemoryFile(engine),
143
+ locateReal: (c) =>
144
+ c.scope === 'global' ? [join(homedir(), `.${engine === 'claude' ? 'claude' : engine}`, memoryFileName(engine))] : []
145
+ };
146
+ }
147
+
148
+ // Permissions: enforcement is a RUNTIME hook (see backend/permissions/); the
149
+ // matrix only describes the optional on-disk "honesty" file. Only Claude reads
150
+ // one Clopen can safely manage — an isolated `settings.json` with a managed
151
+ // `permissions` key (JSON). Other engines are hook-only (Qwen/Copilot) or
152
+ // have no clean per-tool primitive (Codex/OpenCode) → no file to write; their
153
+ // rules live purely in the DB and, where a hook exists, are enforced there.
154
+ if (type === 'permission') {
155
+ if (engine === 'claude') {
156
+ return {
157
+ supported: true,
158
+ format: 'json',
159
+ // Managed-KEYS, not whole-file: the isolated `settings.json` is also
160
+ // Claude's own settings store, so materialization merges the
161
+ // `permissions` key and preserves everything else.
162
+ ownership: 'marker-region',
163
+ exclusive: scope === 'global',
164
+ locateEffective: (c) =>
165
+ c.scope === 'project' && c.projectPath
166
+ ? join(c.projectPath, '.claude', 'settings.json')
167
+ : join(getEngineUserConfigDir('claude'), 'settings.json')
168
+ };
169
+ }
170
+ return unsupported();
171
+ }
172
+
173
+ // MCP has no file representation in this framework (reserved slot).
174
+ if (type === 'mcp') {
175
+ return unsupported();
176
+ }
177
+
178
+ const format = FORMAT_BY_TYPE[type];
179
+ if (!format) return unsupported();
180
+
181
+ if (nativeDir(type, ctx) !== null) {
182
+ // Native engines read a real artifact directory; mirror folders/files there.
183
+ // Exclusive when the effective dir is an ISOLATED engine config dir Clopen
184
+ // fully owns (global scope, non-shared-home engine). Qwen/Copilot resolve
185
+ // their skills dir from the real `$HOME`, so those are shared (not exclusive);
186
+ // project dirs live in the user's repo, also not exclusive.
187
+ const exclusive = scope === 'global' && engine !== 'qwen' && engine !== 'copilot';
188
+ return {
189
+ supported: true,
190
+ format,
191
+ ownership: 'whole-file',
192
+ exclusive,
193
+ locateEffective: (c) => nativeDir(type, c) ?? '',
194
+ locateReal: (c) => (c.scope === 'global' ? realGlobalLocations(type, engine) : [])
195
+ };
196
+ }
197
+
198
+ // Synthetic engines: inject a managed preamble block into the memory file.
199
+ return {
200
+ supported: true,
201
+ format: 'preamble-region',
202
+ ownership: 'marker-region',
203
+ locateEffective: (c) =>
204
+ c.scope === 'project' && c.projectPath
205
+ ? projectMemoryFile(engine, c.projectPath)
206
+ : globalMemoryFile(engine)
207
+ };
208
+ }
209
+
210
+ function unsupported(): ArtifactResolution {
211
+ return {
212
+ supported: false,
213
+ format: 'single-md',
214
+ ownership: 'whole-file',
215
+ locateEffective: () => ''
216
+ };
217
+ }
218
+
219
+ /**
220
+ * Engines whose runtime reads artifacts through a channel that is SHARED across
221
+ * sessions and NOT reliably re-read per turn — a persistent server/client
222
+ * (OpenCode `opencode serve`, Codex/Copilot long-lived clients) and/or a shared
223
+ * global memory file. For these, an on-disk/global-file filter can't express a
224
+ * per-session Profile choice (it leaks across concurrent sessions and/or is
225
+ * served stale), so the adapter ALSO advertises the profile-scoped set
226
+ * per-session by injecting a preamble into the prompt (see
227
+ * `buildArtifactsPromptContext`). Claude and Qwen are excluded: each spawns a
228
+ * fresh per-query CLI over an isolated/pruned dir, so the on-disk filter alone
229
+ * already scopes correctly.
230
+ */
231
+ export const PROMPT_SCOPED_ENGINES: readonly ArtifactEngine[] = ['opencode', 'codex', 'copilot'];
232
+ export function isPromptScopedEngine(engine: ArtifactEngine): boolean {
233
+ return PROMPT_SCOPED_ENGINES.includes(engine);
234
+ }
235
+
236
+ /** Whether a synthetic (non-native) target is best-effort/unverified for the UI. */
237
+ export function isBestEffortTarget(type: ArtifactType, engine: ArtifactEngine): boolean {
238
+ if (type === 'instruction') return engine !== 'claude';
239
+ // Permissions are enforced at a runtime hook on Claude/Qwen/Copilot/OpenCode
240
+ // (OpenCode resolves the tool via its permission event's callID). Only Codex
241
+ // has no per-call hook, so it alone is best-effort.
242
+ if (type === 'permission') return engine === 'codex';
243
+ return nativeDir(type, { engine, scope: 'global' }) === null;
244
+ }
245
+
246
+ export { memoryFileName };
247
+ export type { ArtifactScope };
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Slug helpers shared by the single-md artifact features. A slug is the machine
3
+ * id that matches the on-disk file name and the frontmatter `name`: lowercase
4
+ * ASCII alphanumerics and single hyphens, capped at 64.
5
+ */
6
+
7
+ const NAME_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
8
+
9
+ export function isValidSlug(slug: string): boolean {
10
+ return NAME_RE.test(slug) && slug.length <= 64;
11
+ }
12
+
13
+ /** Normalise an arbitrary string into a valid slug. */
14
+ export function slugify(input: string): string {
15
+ const slug = input
16
+ .toLowerCase()
17
+ .normalize('NFKD')
18
+ .replace(/[^a-z0-9]+/g, '-')
19
+ .replace(/^-+|-+$/g, '')
20
+ .replace(/-{2,}/g, '-')
21
+ .slice(0, 64)
22
+ .replace(/-+$/g, '');
23
+ return slug || 'item';
24
+ }
25
+
26
+ /** Derive a slug that doesn't collide, using `exists` to probe taken slugs. */
27
+ export function uniqueSlug(base: string, exists: (slug: string) => boolean): string {
28
+ const root = slugify(base);
29
+ if (!exists(root)) return root;
30
+ for (let i = 2; i < 1000; i++) {
31
+ const candidate = `${root}-${i}`.slice(0, 64).replace(/-+$/g, '');
32
+ if (!exists(candidate)) return candidate;
33
+ }
34
+ return slugify(`${root}-${String(root.length)}-x`);
35
+ }
@@ -0,0 +1,130 @@
1
+ /**
2
+ * Generic artifact materializer — the single writer all file-shaped artifact
3
+ * features route through. Given the resolved contract for an engine, it either
4
+ * mirrors folders/files into a native directory (pruning only Clopen-managed
5
+ * slugs) or rewrites a marker-delimited preamble block in a shared memory file.
6
+ *
7
+ * This replaces the per-feature sync copies: Skills, Commands and Subagents all
8
+ * call {@link materializeArtifacts} with their own item set and (optionally) a
9
+ * custom preamble builder, so behavior stays identical across features.
10
+ */
11
+
12
+ import { join } from 'path';
13
+ import { mkdir, readdir, rm, writeFile, cp, stat } from 'node:fs/promises';
14
+ import { resolveArtifact } from './matrix';
15
+ import { markersFor, writeManagedBlock } from './markers';
16
+ import type { ArtifactContext, ArtifactType, ManagedArtifact } from './types';
17
+
18
+ /**
19
+ * Managed-block marker id per artifact type (uppercased feature name). `'mcp'`
20
+ * and `'permission'` are excluded: neither routes through this generic
21
+ * file-materializer (MCP is a config-object path; permissions have their own
22
+ * runtime-hook enforcement + `backend/permissions/materialize.ts`).
23
+ */
24
+ const MARKER_ID: Record<Exclude<ArtifactType, 'mcp' | 'permission'>, string> = {
25
+ skill: 'SKILLS',
26
+ command: 'COMMANDS',
27
+ subagent: 'SUBAGENTS',
28
+ instruction: 'INSTRUCTIONS'
29
+ };
30
+
31
+ async function pathExists(path: string): Promise<boolean> {
32
+ try {
33
+ await stat(path);
34
+ return true;
35
+ } catch {
36
+ return false;
37
+ }
38
+ }
39
+
40
+ /** Mirror one canonical folder into a destination dir under `<slug>/` (replacing any stale copy). */
41
+ async function mirrorFolder(sourceDir: string, destDir: string, slug: string): Promise<void> {
42
+ if (!(await pathExists(sourceDir))) return;
43
+ const dest = join(destDir, slug);
44
+ await rm(dest, { recursive: true, force: true });
45
+ await mkdir(destDir, { recursive: true });
46
+ await cp(sourceDir, dest, { recursive: true });
47
+ }
48
+
49
+ /** Default synthetic preamble — a generic "these artifacts exist" block. */
50
+ function defaultPreamble(type: ArtifactType, items: ManagedArtifact[]): string {
51
+ if (items.length === 0) return '';
52
+ const label = type === 'command' ? 'Commands' : type === 'subagent' ? 'Subagents' : 'Items';
53
+ const lines = [`# Available ${label}`, ''];
54
+ for (const item of items) lines.push(`- **${item.name}** — ${item.description}`);
55
+ return lines.join('\n');
56
+ }
57
+
58
+ export interface MaterializeInput {
59
+ /** Items that should exist after the sync (enabled set). */
60
+ enabled: ManagedArtifact[];
61
+ /** Every slug this feature manages — used to prune safely without touching user files. */
62
+ managedSlugs: string[];
63
+ /** Optional custom synthetic preamble (Skills keeps its exact original text). */
64
+ buildPreamble?: (items: ManagedArtifact[]) => string;
65
+ }
66
+
67
+ /**
68
+ * Materialize a feature's artifacts for one engine. Safe to call at every stream
69
+ * start: native dirs are reconciled and synthetic blocks are rewritten in place.
70
+ */
71
+ export async function materializeArtifacts(
72
+ type: Exclude<ArtifactType, 'mcp' | 'instruction'>,
73
+ ctx: ArtifactContext,
74
+ input: MaterializeInput
75
+ ): Promise<void> {
76
+ const resolution = resolveArtifact(type, ctx);
77
+ if (!resolution.supported) return;
78
+
79
+ const target = resolution.locateEffective(ctx);
80
+ if (!target) return;
81
+
82
+ const enabledSlugs = new Set(input.enabled.map(i => i.slug));
83
+ const managedSlugs = new Set(input.managedSlugs);
84
+
85
+ if (resolution.format === 'folder-md' || resolution.format === 'single-md') {
86
+ await mkdir(target, { recursive: true });
87
+
88
+ // Prune stale copies. In an EXCLUSIVE (Clopen-owned isolated) dir we remove
89
+ // anything not currently enabled — this is what reclaims artifacts whose DB
90
+ // row was deleted (their slug is gone from managedSlugs). In a SHARED dir we
91
+ // only prune known managed slugs, never the user's own files.
92
+ for (const entry of await readdir(target, { withFileTypes: true })) {
93
+ if (entry.name.startsWith('.')) continue;
94
+ const slug = resolution.format === 'single-md' ? entry.name.replace(/\.md$/, '') : entry.name;
95
+ const stale = resolution.exclusive
96
+ ? !enabledSlugs.has(slug)
97
+ : managedSlugs.has(slug) && !enabledSlugs.has(slug);
98
+ if (stale) {
99
+ await rm(join(target, entry.name), { recursive: true, force: true });
100
+ }
101
+ }
102
+
103
+ for (const item of input.enabled) {
104
+ if (resolution.format === 'folder-md') {
105
+ if (item.sourceDir) await mirrorFolder(item.sourceDir, target, item.slug);
106
+ } else if (item.document != null) {
107
+ await writeFile(join(target, `${item.slug}.md`), item.document, 'utf8');
108
+ }
109
+ }
110
+
111
+ // A type that is NATIVE for this engine must not ALSO leave a stale synthetic
112
+ // managed block in the memory file. Engines that USED to be synthetic for a
113
+ // type before a native dir was added (OpenCode subagents/commands, Codex
114
+ // commands) still carry an orphaned `CLOPEN:<TYPE>` block in AGENTS.md that
115
+ // the native sync never touches — so a deleted/renamed artifact would linger
116
+ // there forever (e.g. a removed subagent still "available"). Strip it here;
117
+ // writeManagedBlock is a no-op when no such block exists.
118
+ const staleMemoryFile = resolveArtifact('instruction', ctx).locateEffective(ctx);
119
+ if (staleMemoryFile) {
120
+ await writeManagedBlock(staleMemoryFile, '', markersFor(MARKER_ID[type as keyof typeof MARKER_ID]));
121
+ }
122
+ return;
123
+ }
124
+
125
+ // preamble-region → managed block inside the engine memory file. `type` is
126
+ // always one of the file-materialized kinds here (mcp/permission never route
127
+ // through this writer), so the MARKER_ID lookup is total in practice.
128
+ const build = input.buildPreamble ?? ((items) => defaultPreamble(type, items));
129
+ await writeManagedBlock(target, build(input.enabled), markersFor(MARKER_ID[type as keyof typeof MARKER_ID]));
130
+ }
@@ -0,0 +1,152 @@
1
+ /**
2
+ * Artifact framework — shared capability matrix for engine "extension" artifacts.
3
+ *
4
+ * Clopen manages several kinds of engine artifact (Agent Skills, custom slash
5
+ * Commands, Subagents, project Instructions). They differ in file shape but share
6
+ * one mechanic: a canonical source (DB metadata + on-disk store, or a repo file)
7
+ * is MATERIALIZED into the shape each engine consumes at stream start.
8
+ *
9
+ * Rather than hardcode that mechanic per feature (as the original Skills sync
10
+ * did), every `artifactType × engine × scope` combination is described by a
11
+ * single {@link ArtifactResolution}. Generic writers/scanners (see `sync.ts` and
12
+ * `detect.ts`) act on that description, so a new feature is a configuration in
13
+ * `matrix.ts` — not a new copy of the sync/detect logic.
14
+ *
15
+ * Two materialization strategies recur, mirroring the two engine families:
16
+ * - NATIVE (Claude, Qwen, Copilot): the engine reads a real artifact directory.
17
+ * Clopen mirrors each managed folder/file there (`folder-md` / `single-md`),
18
+ * touching only the slugs it owns.
19
+ * - SYNTHETIC (Codex, OpenCode): no native concept, so Clopen injects a
20
+ * marker-delimited block (`preamble-region`) into the engine's global
21
+ * instructions file.
22
+ *
23
+ * `'mcp'` is intentionally reserved in {@link ArtifactType} but has NO adapter
24
+ * here: MCP servers are not file artifacts — they are config objects composed
25
+ * per engine and proxied through the `/mcp/ext/<slug>` bridge (see
26
+ * `backend/mcp/`). Forcing MCP through a file writer/detector would be a
27
+ * mis-fit, so it keeps its existing config-object path. The slot exists only so
28
+ * the type is extensible if a file-shaped MCP concern ever appears.
29
+ */
30
+
31
+ /**
32
+ * Engine keys used across the framework. These are the *config-dir* slugs (e.g.
33
+ * `'claude'`, not the `EngineType` `'claude-code'`) so they line up with
34
+ * {@link getEngineUserConfigDir} and the original Skills sync.
35
+ */
36
+ export type ArtifactEngine = 'claude' | 'codex' | 'copilot' | 'qwen' | 'opencode';
37
+
38
+ export const ARTIFACT_ENGINES: ArtifactEngine[] = ['claude', 'codex', 'copilot', 'qwen', 'opencode'];
39
+
40
+ /**
41
+ * Kinds of artifact the framework can materialize. `'mcp'` is reserved (see file
42
+ * header). `'permission'` describes engine tool allow/deny config: its ENFORCEMENT
43
+ * is a runtime hook (see `backend/permissions/`), and the matrix entry only
44
+ * describes the optional on-disk "honesty" file (Claude `settings.json`, Codex
45
+ * `config.toml`) for engines that read one.
46
+ */
47
+ export type ArtifactType = 'skill' | 'command' | 'subagent' | 'instruction' | 'mcp' | 'permission';
48
+
49
+ /** Where an artifact lives: instance-global (per engine) or inside a project repo. */
50
+ export type ArtifactScope = 'global' | 'project';
51
+
52
+ /**
53
+ * On-disk shape of a materialized artifact.
54
+ * - `folder-md` : a folder whose entry file carries frontmatter (Skills).
55
+ * - `single-md` : one `.md` file per artifact (Commands, Subagents).
56
+ * - `preamble-region`: a managed block inside a shared instructions file.
57
+ * - `json` : a JSON config file with Clopen-managed keys (Claude
58
+ * `settings.json` permissions).
59
+ * - `toml` : a TOML config file with a Clopen-managed marker-region
60
+ * (Codex `config.toml`).
61
+ */
62
+ export type ArtifactFormat = 'folder-md' | 'single-md' | 'preamble-region' | 'json' | 'toml';
63
+
64
+ /**
65
+ * How much of the target file Clopen owns.
66
+ * - `whole-file` : Clopen created and fully owns the file/folder.
67
+ * - `marker-region`: Clopen owns only a marker-delimited region; the rest is
68
+ * the user's hand-written content and must never be touched.
69
+ */
70
+ export type ArtifactOwnership = 'whole-file' | 'marker-region';
71
+
72
+ /**
73
+ * Minimal context for resolving/writing an artifact. Designed to be extended
74
+ * later (e.g. a `profileId?` for Prompt 4's Profiles) WITHOUT changing the
75
+ * signature of `resolve()` — callers pass a richer context, adapters ignore
76
+ * fields they don't use.
77
+ */
78
+ export interface ArtifactContext {
79
+ engine: ArtifactEngine;
80
+ scope: ArtifactScope;
81
+ /** Project association for `scope: 'project'` (repo-scoped artifacts). */
82
+ projectId?: string;
83
+ /** Absolute path to the project repo root, for project-scoped resolution. */
84
+ projectPath?: string;
85
+ /** Reserved for Prompt 4 — active profile scoping. Unused today. */
86
+ profileId?: string;
87
+ }
88
+
89
+ /** A single managed artifact ready to be written to an engine target. */
90
+ export interface ManagedArtifact {
91
+ slug: string;
92
+ name: string;
93
+ description: string;
94
+ /**
95
+ * The canonical source folder for `folder-md` artifacts (mirrored wholesale),
96
+ * or `undefined` when the content is produced inline.
97
+ */
98
+ sourceDir?: string;
99
+ /** Serialized document for `single-md` artifacts (frontmatter + body). */
100
+ document?: string;
101
+ }
102
+
103
+ /** An artifact discovered on disk (managed by Clopen or pre-existing / user-owned). */
104
+ export interface DetectedArtifact {
105
+ slug: string;
106
+ name: string;
107
+ description: string;
108
+ /** Absolute path to the artifact (folder or file). */
109
+ path: string;
110
+ /** True when the path is a Clopen-managed effective location. */
111
+ managed: boolean;
112
+ /** True when the path is a real standard location eligible for adopt/link. */
113
+ adoptable: boolean;
114
+ }
115
+
116
+ /**
117
+ * The capability descriptor for one `artifactType × engine × scope`. Generic
118
+ * writers/scanners consume this; concrete file mechanics live in `sync.ts` /
119
+ * `detect.ts`, keyed off `format`/`ownership`.
120
+ */
121
+ export interface ArtifactResolution {
122
+ supported: boolean;
123
+ format: ArtifactFormat;
124
+ ownership: ArtifactOwnership;
125
+ /**
126
+ * True when Clopen EXCLUSIVELY owns the effective directory (an isolated
127
+ * engine config dir the user never writes to). Such dirs can be pruned of
128
+ * ANY entry not currently enabled — which is required to remove artifacts
129
+ * whose DB row was deleted (their slug is gone from `managedSlugs`, so a
130
+ * managed-slug-only prune would orphan the file forever). Shared dirs (e.g.
131
+ * the user's real `~/.qwen/skills`) are NOT exclusive: only known managed
132
+ * slugs are pruned there, never the user's own files.
133
+ */
134
+ exclusive?: boolean;
135
+ /**
136
+ * The location Clopen writes to for this engine/scope — an isolated engine
137
+ * dir (global) or a repo path (project). Returns a directory for
138
+ * `folder-md`/`single-md`, a file for `preamble-region`.
139
+ */
140
+ locateEffective(ctx: ArtifactContext): string;
141
+ /**
142
+ * Real standard locations to scan for "detect & link" (global only) — e.g.
143
+ * `~/.claude/commands`. Absent when there is nothing outside Clopen's dirs.
144
+ */
145
+ locateReal?(ctx: ArtifactContext): string[];
146
+ }
147
+
148
+ /** Marker used to delimit Clopen-managed regions inside shared files. */
149
+ export interface ArtifactMarkers {
150
+ start: string;
151
+ end: string;
152
+ }
@@ -113,6 +113,11 @@ export const ADMIN_ONLY_ROUTES = new Set([
113
113
  'mcp:status',
114
114
  'mcp:oauth-start',
115
115
  'mcp:oauth-complete',
116
+ // Per-tool control + inspector — introspects/filters an installed server's
117
+ // tools and can invoke them, so it stays within the admin-only MCP surface.
118
+ 'mcp:tools',
119
+ 'mcp:set-tool-overrides',
120
+ 'mcp:call-tool',
116
121
  // Agent Skills — creating/importing/installing skills writes to the shared
117
122
  // canonical store and applies to every engine, so the whole surface is
118
123
  // admin-only, mirroring MCP and System Tools.
@@ -125,7 +130,52 @@ export const ADMIN_ONLY_ROUTES = new Set([
125
130
  'skills:toggle',
126
131
  'skills:delete',
127
132
  'skills:catalog',
128
- 'skills:install'
133
+ 'skills:install',
134
+ // Custom Commands — same shared-store rationale as Skills; admin-only surface.
135
+ 'commands:list',
136
+ 'commands:get',
137
+ 'commands:create',
138
+ 'commands:update',
139
+ 'commands:parse-import',
140
+ 'commands:import',
141
+ 'commands:toggle',
142
+ 'commands:delete',
143
+ 'commands:detect',
144
+ // Subagents — shared canonical store applied to every engine; admin-only.
145
+ 'subagents:list',
146
+ 'subagents:get',
147
+ 'subagents:create',
148
+ 'subagents:update',
149
+ 'subagents:parse-import',
150
+ 'subagents:import',
151
+ 'subagents:toggle',
152
+ 'subagents:delete',
153
+ 'subagents:detect',
154
+ // Project Instructions — writes managed regions into engine memory files; admin-only.
155
+ 'instructions:get-global',
156
+ 'instructions:save-global',
157
+ 'instructions:get-project',
158
+ 'instructions:save-project',
159
+ // Permissions — per-engine tool allow/deny applied to every engine/project;
160
+ // same shared-store rationale as Skills/MCP, admin-only surface.
161
+ 'permissions:list',
162
+ 'permissions:inventory',
163
+ 'permissions:save',
164
+ // AI authoring of artifacts — part of the admin artifact editors.
165
+ 'artifacts:generate',
166
+ // Profiles — reusable artifact bundles applied to every collaborator's
167
+ // sessions; same shared-store rationale as Skills/MCP, admin-only surface.
168
+ // (profiles:available / profiles:project-default stay non-admin — choosing a
169
+ // profile for a session is a run choice like the model.)
170
+ 'profiles:list',
171
+ 'profiles:get',
172
+ 'profiles:inventory',
173
+ 'profiles:create',
174
+ 'profiles:update',
175
+ 'profiles:delete',
176
+ 'profiles:get-permissions',
177
+ 'profiles:save-permissions',
178
+ 'profiles:set-project-default'
129
179
  ]);
130
180
 
131
181
  /**
@@ -36,6 +36,7 @@ import { getProjectEngine, initializeProjectEngine } from '../engine';
36
36
  import { messageQueries, sessionQueries } from '../database/queries';
37
37
  import { snapshotService } from '../snapshot/snapshot-service';
38
38
  import { projectContextService, refreshExpiringExternalOAuth } from '../mcp';
39
+ import { resolveActiveProfileId } from '../profiles';
39
40
  import { browserMcpControl } from '../preview';
40
41
  import { extractMessageText } from '../snapshot/helpers';
41
42
  import { debug } from '$shared/utils/logger';
@@ -319,6 +320,12 @@ class StreamManager extends EventEmitter {
319
320
  if (request.engine.account.id) {
320
321
  sessionQueries.updateAccount(request.chatSessionId, request.engine.account.id, request.engine.account.name || null);
321
322
  }
323
+ // Persist the session's explicit profile choice (number or null).
324
+ // `undefined` (older client that doesn't send one) leaves it untouched
325
+ // so the session keeps inheriting the project default.
326
+ if (request.profileId !== undefined) {
327
+ sessionQueries.updateProfile(request.chatSessionId, request.profileId);
328
+ }
322
329
  } catch (error) {
323
330
  debug.error('chat', 'Failed to save engine/model to session:', error);
324
331
  }
@@ -530,6 +537,12 @@ class StreamManager extends EventEmitter {
530
537
  let lastAssistantTextContent: string | null = null;
531
538
  const projectId = streamState.projectId || 'default';
532
539
 
540
+ // Resolve the effective Profile once per stream: the session's explicit
541
+ // choice, else the project's shared default (see backend/profiles). Passed
542
+ // down via mcpContext so the existing per-engine sync + MCP config path
543
+ // scopes artifacts/connectors to the profile's bundle — no new sync path.
544
+ const activeProfileId = resolveActiveProfileId(requestData.profileId, streamState.projectId);
545
+
533
546
  if ((streamState.status as string) === 'cancelled' || streamState.abortController?.signal.aborted) {
534
547
  debug.log('chat', 'Stream cancelled before engine initialization, skipping query');
535
548
  return;
@@ -625,7 +638,7 @@ class StreamManager extends EventEmitter {
625
638
  abortController: streamState.abortController,
626
639
  ...(requestEngine.account.id !== 0 && { accountId: requestEngine.account.id }),
627
640
  ...(projectId && chatSessionId && {
628
- mcpContext: { projectId, chatSessionId, streamId: streamState.streamId }
641
+ mcpContext: { projectId, chatSessionId, streamId: streamState.streamId, ...(activeProfileId != null && { profileId: activeProfileId }) }
629
642
  }),
630
643
  });
631
644