@myrialabs/clopen 0.4.8 → 0.4.10

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 (107) hide show
  1. package/README.md +10 -7
  2. package/backend/artifacts/detect.ts +129 -0
  3. package/backend/artifacts/engine-map.ts +53 -0
  4. package/backend/artifacts/frontmatter.ts +68 -0
  5. package/backend/artifacts/generate.ts +105 -0
  6. package/backend/artifacts/index.ts +34 -0
  7. package/backend/artifacts/markers.ts +76 -0
  8. package/backend/artifacts/matrix.ts +247 -0
  9. package/backend/artifacts/slug.ts +35 -0
  10. package/backend/artifacts/sync.ts +130 -0
  11. package/backend/artifacts/types.ts +152 -0
  12. package/backend/auth/permissions.ts +51 -1
  13. package/backend/chat/stream-manager.ts +14 -1
  14. package/backend/commands/detect.ts +25 -0
  15. package/backend/commands/index.ts +9 -0
  16. package/backend/commands/service.ts +178 -0
  17. package/backend/commands/store.ts +45 -0
  18. package/backend/commands/sync.ts +94 -0
  19. package/backend/database/migrations/045_create_commands_table.ts +28 -0
  20. package/backend/database/migrations/046_create_subagents_table.ts +29 -0
  21. package/backend/database/migrations/047_create_instructions_table.ts +29 -0
  22. package/backend/database/migrations/048_add_mcp_tool_overrides.ts +23 -0
  23. package/backend/database/migrations/049_create_permission_sets_table.ts +50 -0
  24. package/backend/database/migrations/050_create_profiles_tables.ts +57 -0
  25. package/backend/database/migrations/051_add_profile_to_sessions.ts +20 -0
  26. package/backend/database/migrations/052_add_default_profile_to_projects.ts +20 -0
  27. package/backend/database/migrations/053_add_profile_to_permission_sets.ts +37 -0
  28. package/backend/database/migrations/054_drop_subagent_agent_type.ts +20 -0
  29. package/backend/database/migrations/055_artifact_model_tools_per_engine.ts +43 -0
  30. package/backend/database/migrations/index.ts +77 -0
  31. package/backend/database/queries/command-queries.ts +82 -0
  32. package/backend/database/queries/index.ts +12 -2
  33. package/backend/database/queries/instruction-queries.ts +62 -0
  34. package/backend/database/queries/mcp-server-queries.ts +25 -0
  35. package/backend/database/queries/permission-set-queries.ts +155 -0
  36. package/backend/database/queries/profile-queries.ts +118 -0
  37. package/backend/database/queries/project-queries.ts +14 -0
  38. package/backend/database/queries/session-queries.ts +21 -0
  39. package/backend/database/queries/subagent-queries.ts +92 -0
  40. package/backend/engine/adapters/claude/stream.ts +27 -3
  41. package/backend/engine/adapters/codex/stream.ts +46 -14
  42. package/backend/engine/adapters/copilot/stream.ts +58 -4
  43. package/backend/engine/adapters/opencode/message-converter.ts +22 -2
  44. package/backend/engine/adapters/opencode/server.ts +166 -210
  45. package/backend/engine/adapters/opencode/stream.ts +150 -24
  46. package/backend/engine/adapters/qwen/stream.ts +23 -3
  47. package/backend/engine/artifact-sync.ts +51 -0
  48. package/backend/engine/types.ts +6 -0
  49. package/backend/instructions/index.ts +8 -0
  50. package/backend/instructions/service.ts +63 -0
  51. package/backend/instructions/sync.ts +56 -0
  52. package/backend/mcp/external/config.ts +42 -20
  53. package/backend/mcp/external/proxy.ts +89 -5
  54. package/backend/mcp/external/tools.ts +88 -0
  55. package/backend/mcp/index.ts +38 -15
  56. package/backend/mcp/internal/config.ts +48 -11
  57. package/backend/mcp/internal/remote-server.ts +9 -1
  58. package/backend/permissions/index.ts +27 -0
  59. package/backend/permissions/materialize.ts +96 -0
  60. package/backend/permissions/resolve.test.ts +162 -0
  61. package/backend/permissions/resolve.ts +106 -0
  62. package/backend/permissions/service.ts +167 -0
  63. package/backend/profiles/index.ts +10 -0
  64. package/backend/profiles/service.ts +169 -0
  65. package/backend/project/status-manager.ts +7 -25
  66. package/backend/skills/index.ts +1 -1
  67. package/backend/skills/sync.ts +88 -128
  68. package/backend/subagents/detect.ts +23 -0
  69. package/backend/subagents/index.ts +10 -0
  70. package/backend/subagents/service.ts +166 -0
  71. package/backend/subagents/store.ts +44 -0
  72. package/backend/subagents/sync.ts +144 -0
  73. package/backend/utils/static-curl.ts +12 -54
  74. package/backend/ws/artifacts/generate.ts +51 -0
  75. package/backend/ws/artifacts/index.ts +8 -0
  76. package/backend/ws/chat/stream.ts +33 -2
  77. package/backend/ws/commands/crud.ts +157 -0
  78. package/backend/ws/commands/index.ts +8 -0
  79. package/backend/ws/git/branch.ts +4 -2
  80. package/backend/ws/git/remote.ts +21 -11
  81. package/backend/ws/index.ts +17 -1
  82. package/backend/ws/instructions/crud.ts +53 -0
  83. package/backend/ws/instructions/index.ts +8 -0
  84. package/backend/ws/mcp/crud.ts +7 -1
  85. package/backend/ws/mcp/index.ts +4 -1
  86. package/backend/ws/mcp/tools.ts +112 -0
  87. package/backend/ws/permissions/crud.ts +72 -0
  88. package/backend/ws/permissions/index.ts +8 -0
  89. package/backend/ws/profiles/crud.ts +149 -0
  90. package/backend/ws/profiles/index.ts +9 -0
  91. package/backend/ws/sessions/crud.ts +12 -0
  92. package/backend/ws/subagents/crud.ts +136 -0
  93. package/backend/ws/subagents/index.ts +8 -0
  94. package/dist/assets/{index-jGo0X72U.js → index-C3kp8wpM.js} +1 -1
  95. package/dist/assets/{index-B_F_OgoC.js → index-cVUk7das.js} +1 -1
  96. package/dist/assets/main-CuCxUeqZ.js +533 -0
  97. package/dist/assets/main-D4pdkiQK.css +1 -0
  98. package/dist/index.html +2 -2
  99. package/package.json +24 -24
  100. package/shared/constants/engine-tools.ts +56 -0
  101. package/shared/types/database/schema.ts +2 -0
  102. package/shared/types/stores/settings.ts +15 -0
  103. package/shared/types/unified/stream.ts +7 -0
  104. package/shared/utils/interactive-input.ts +71 -0
  105. package/shared/utils/logger.ts +6 -0
  106. package/dist/assets/main-BkCc3WEB.js +0 -481
  107. package/dist/assets/main-CWDwET4x.css +0 -1
@@ -0,0 +1,169 @@
1
+ /**
2
+ * Profile service — the bundle layer (Settings → Profiles) and the stream-time
3
+ * resolution consumed by the artifact/MCP sync path.
4
+ *
5
+ * A Profile is a reusable, named set of references to existing artifacts
6
+ * (Skills, Commands, Subagents, MCP Connectors). It NARROWS which of the
7
+ * instance-global artifacts are active for a session, without duplicating any
8
+ * artifact data — `profile_items` only stores slugs.
9
+ *
10
+ * ── Activation resolution ──
11
+ * effective profile = chat_sessions.profile_id ?? projects.default_profile_id
12
+ * resolved once at stream start (see {@link resolveActiveProfileId}) and passed
13
+ * down through the existing per-engine sync via `mcpContext.profileId`.
14
+ *
15
+ * ── Presence-per-type filtering ──
16
+ * A profile only constrains the artifact TYPES it actually references. For a
17
+ * given type, {@link artifactFilter} returns:
18
+ * - `null` when the profile references NO item of that type → unconstrained
19
+ * (the sync keeps its normal "all enabled" behaviour — no regression), and
20
+ * also when there is no active profile at all;
21
+ * - a `Set<slug>` when the profile references ≥1 item → the sync intersects its
22
+ * enabled set with these slugs.
23
+ * This means a profile that only curates Commands never silently disables every
24
+ * Skill, and a NULL/absent profile behaves exactly like today.
25
+ */
26
+
27
+ import { profileQueries, projectQueries, mcpServerQueries } from '$backend/database/queries';
28
+ import type { ProfileItemType, ProfileItemInput } from '$backend/database/queries';
29
+ import { PROFILE_ITEM_TYPES } from '$backend/database/queries';
30
+ import { skillQueries, commandQueries, subagentQueries } from '$backend/database/queries';
31
+ import { debug } from '$shared/utils/logger';
32
+
33
+ /** A profile with its items grouped by type, for the Settings UI. */
34
+ export interface ProfileDTO {
35
+ id: number;
36
+ slug: string;
37
+ name: string;
38
+ description: string;
39
+ items: Record<ProfileItemType, string[]>;
40
+ itemCount: number;
41
+ createdAt: string;
42
+ updatedAt: string;
43
+ }
44
+
45
+ /** One selectable artifact in the profile editor. */
46
+ export interface ProfileInventoryEntry {
47
+ slug: string;
48
+ name: string;
49
+ enabled: boolean;
50
+ }
51
+
52
+ /** The artifacts a profile can bundle, grouped by type. */
53
+ export type ProfileInventory = Record<ProfileItemType, ProfileInventoryEntry[]>;
54
+
55
+ function emptyItems(): Record<ProfileItemType, string[]> {
56
+ return { skill: [], command: [], subagent: [], mcp: [] };
57
+ }
58
+
59
+ function toDTO(id: number): ProfileDTO | null {
60
+ const row = profileQueries.getById(id);
61
+ if (!row) return null;
62
+ const items = emptyItems();
63
+ for (const item of profileQueries.getItems(id)) {
64
+ if (PROFILE_ITEM_TYPES.includes(item.artifact_type)) items[item.artifact_type].push(item.ref);
65
+ }
66
+ const itemCount = PROFILE_ITEM_TYPES.reduce((n, t) => n + items[t].length, 0);
67
+ return {
68
+ id: row.id,
69
+ slug: row.slug,
70
+ name: row.name,
71
+ description: row.description,
72
+ items,
73
+ itemCount,
74
+ createdAt: row.created_at,
75
+ updatedAt: row.updated_at
76
+ };
77
+ }
78
+
79
+ /**
80
+ * The effective profile for a stream: the session's explicit choice, else the
81
+ * project's shared default, else none. Returns a numeric profile id or null.
82
+ */
83
+ export function resolveActiveProfileId(
84
+ sessionProfileId: number | null | undefined,
85
+ projectId: string | undefined
86
+ ): number | null {
87
+ if (sessionProfileId != null) return sessionProfileId;
88
+ if (projectId) return projectQueries.getDefaultProfileId(projectId);
89
+ return null;
90
+ }
91
+
92
+ /**
93
+ * The slug allow-set for one artifact type under an active profile, or null when
94
+ * the type is unconstrained (see file header). `profileId == null` → always null.
95
+ */
96
+ export function artifactFilter(profileId: number | null | undefined, type: ProfileItemType): Set<string> | null {
97
+ if (profileId == null) return null;
98
+ const refs = profileQueries.getRefsByType(profileId, type);
99
+ return refs.length > 0 ? new Set(refs) : null;
100
+ }
101
+
102
+ export const profileService = {
103
+ /** All profiles (metadata + grouped items) for the admin listing. */
104
+ list(): ProfileDTO[] {
105
+ return profileQueries.getAll().map(r => toDTO(r.id)!).filter(Boolean);
106
+ },
107
+
108
+ get(id: number): ProfileDTO | null {
109
+ return toDTO(id);
110
+ },
111
+
112
+ create(name: string, description: string, items: ProfileItemInput[]): ProfileDTO {
113
+ const slug = uniqueProfileSlug(name);
114
+ const row = profileQueries.insert({ slug, name, description });
115
+ profileQueries.setItems(row.id, items);
116
+ debug.log('profiles', `🎛️ Created profile "${name}" (${items.length} item(s))`);
117
+ return toDTO(row.id)!;
118
+ },
119
+
120
+ update(id: number, name: string, description: string, items: ProfileItemInput[]): ProfileDTO {
121
+ const row = profileQueries.getById(id);
122
+ if (!row) throw new Error('Profile not found');
123
+ profileQueries.updateMeta(id, name, description);
124
+ profileQueries.setItems(id, items);
125
+ debug.log('profiles', `🎛️ Updated profile "${name}" (${items.length} item(s))`);
126
+ return toDTO(id)!;
127
+ },
128
+
129
+ remove(id: number): void {
130
+ profileQueries.remove(id);
131
+ debug.log('profiles', `🎛️ Deleted profile #${id}`);
132
+ },
133
+
134
+ /** Artifacts selectable in the profile editor, grouped by type. */
135
+ inventory(): ProfileInventory {
136
+ const inv: ProfileInventory = { skill: [], command: [], subagent: [], mcp: [] };
137
+ for (const s of skillQueries.getAll()) inv.skill.push({ slug: s.slug, name: s.name, enabled: s.is_enabled === 1 });
138
+ for (const c of commandQueries.getAll()) inv.command.push({ slug: c.slug, name: c.name, enabled: c.is_enabled === 1 });
139
+ for (const a of subagentQueries.getAll()) inv.subagent.push({ slug: a.slug, name: a.name, enabled: a.is_enabled === 1 });
140
+ // Both external AND built-in (internal) connectors are selectable — a profile
141
+ // can scope Clopen's own tools (e.g. browser-automation) too.
142
+ for (const m of mcpServerQueries.getAll()) {
143
+ inv.mcp.push({ slug: m.slug, name: m.name, enabled: m.is_enabled === 1 });
144
+ }
145
+ return inv;
146
+ },
147
+
148
+ /** Lightweight list for the non-admin per-session picker (id + name only). */
149
+ available(): { id: number; slug: string; name: string; description: string }[] {
150
+ return profileQueries.getAll().map(r => ({ id: r.id, slug: r.slug, name: r.name, description: r.description }));
151
+ }
152
+ };
153
+
154
+ function uniqueProfileSlug(name: string): string {
155
+ // Local import to avoid a top-level cycle through the artifacts barrel.
156
+ const base = name
157
+ .toLowerCase()
158
+ .normalize('NFKD')
159
+ .replace(/[^a-z0-9]+/g, '-')
160
+ .replace(/^-+|-+$/g, '')
161
+ .slice(0, 64)
162
+ .replace(/-+$/g, '') || 'profile';
163
+ if (!profileQueries.getBySlug(base)) return base;
164
+ for (let i = 2; i < 1000; i++) {
165
+ const candidate = `${base}-${i}`.slice(0, 64).replace(/-+$/g, '');
166
+ if (!profileQueries.getBySlug(candidate)) return candidate;
167
+ }
168
+ return `${base}-x`;
169
+ }
@@ -6,41 +6,23 @@
6
6
  import { streamManager, type StreamState } from '../chat/stream-manager.js';
7
7
  import { ws } from '../utils/ws.js';
8
8
  import type { UnifiedMessage } from '$shared/types/unified';
9
-
10
- // Interactive tools that block the stream waiting for user input
11
- const INTERACTIVE_TOOLS = new Set(['AskUserQuestion']);
9
+ import { isWaitingForInteractiveInput } from '$shared/utils/interactive-input';
12
10
 
13
11
  /**
14
12
  * Check if an active stream is waiting for user input.
15
- * Scans stream messages for unanswered interactive tool_use blocks.
13
+ * Delegates to the shared derivation so backend presence and the frontend
14
+ * chat service can never disagree on what "waiting for input" means.
16
15
  * This is the backend single source of truth — works even when the
17
16
  * user is on a different project and not receiving chat events.
18
17
  */
19
18
  function detectStreamWaitingInput(stream: StreamState): boolean {
20
19
  if (stream.status !== 'active') return false;
21
20
 
22
- const answeredToolIds = new Set<string>();
23
- for (const event of stream.messages) {
24
- const msg = (event as { message?: UnifiedMessage }).message;
25
- if (!msg || msg.type !== 'user') continue;
26
- for (const block of msg.content) {
27
- if (block.type === 'tool_result' && block.toolUseId) {
28
- answeredToolIds.add(block.toolUseId);
29
- }
30
- }
31
- }
32
-
33
- for (const event of stream.messages) {
34
- const msg = (event as { message?: UnifiedMessage }).message;
35
- if (!msg || msg.type !== 'assistant') continue;
36
- if (msg.content.some(block =>
37
- block.type === 'tool_use' && INTERACTIVE_TOOLS.has(block.name) && block.id && !answeredToolIds.has(block.id)
38
- )) {
39
- return true;
40
- }
41
- }
21
+ const messages = stream.messages
22
+ .map(event => (event as { message?: UnifiedMessage }).message)
23
+ .filter((msg): msg is UnifiedMessage => Boolean(msg));
42
24
 
43
- return false;
25
+ return isWaitingForInteractiveInput(messages);
44
26
  }
45
27
 
46
28
  // Store active users per project (shared with main endpoint)
@@ -17,5 +17,5 @@ export type { SkillDTO, ParsedSkillPreview } from './service';
17
17
  export { listMarketplaceSkills, fetchMarketplaceSkill } from './marketplace';
18
18
  export type { MarketplaceSkill, MarketplacePage } from './marketplace';
19
19
 
20
- export { syncSkills, syncSkillsAllEngines } from './sync';
20
+ export { syncSkills, syncSkillsAllEngines, buildSkillsPromptContext } from './sync';
21
21
  export type { SkillEngine } from './sync';
@@ -1,40 +1,29 @@
1
1
  /**
2
- * Engine sync — materialize enabled skills into the shape each engine consumes.
2
+ * Engine sync for Skills — now a thin adapter over the shared artifact framework
3
+ * (`backend/artifacts/`). Skills were the original per-feature sync; that logic
4
+ * has been generalized into {@link materializeArtifacts}, and this module simply
5
+ * supplies the skill item set plus the exact preamble text skills have always
6
+ * emitted (preserved verbatim so retrofitting introduces no behavior change).
3
7
  *
4
- * Skills are an open standard, but engines surface them differently:
5
- * - NATIVE (Claude, Qwen, Copilot): read a real skills directory and do their
6
- * own progressive disclosure. We mirror each enabled skill folder there.
7
- * Claude's dir is inside its isolated CLAUDE_CONFIG_DIR; Qwen and Copilot
8
- * resolve theirs from $HOME (`~/.qwen/skills`, `~/.copilot/skills`) with no
9
- * relocation env, so for those we manage the user's real global skills dir —
10
- * touching only the slugs we own, never the user's own skills.
11
- * - SYNTHETIC (Codex, OpenCode): no native skills concept, so we emit a
12
- * "skills preamble" — name + description + the absolute path to each skill's
13
- * SKILL.md — into a managed, marker-delimited block of the engine's global
14
- * instructions file (inside its isolated home). The engine reads the body on
15
- * demand with its own file tool, emulating progressive disclosure.
8
+ * Materialization by engine (unchanged):
9
+ * - NATIVE (Claude, Qwen, Copilot): mirror each enabled skill folder into the
10
+ * engine's skills dir.
11
+ * - SYNTHETIC (Codex, OpenCode): inject a marker-delimited "skills preamble"
12
+ * (name + description + absolute SKILL.md path) into the engine's global
13
+ * memory file. These synthetic targets are best-effort/unverified.
16
14
  *
17
- * Sync is wrapped so a failure degrades gracefully — a stream never breaks
18
- * because skills couldn't sync.
19
- *
20
- * NOTE: the synthetic target paths (Codex/OpenCode) follow each engine's
21
- * documented global-memory convention but are best-effort; if an engine ignores
22
- * the path, its skills simply don't surface (no error, no data loss) until the
23
- * mapping is verified against that engine.
15
+ * Sync never throws — a stream never breaks because skills couldn't sync.
24
16
  */
25
17
 
26
- import { join } from 'path';
27
- import { homedir } from 'os';
28
- import { mkdir, readFile, writeFile, readdir, rm, stat } from 'node:fs/promises';
29
- import { getEngineUserConfigDir } from '$backend/utils/paths';
30
18
  import { skillQueries } from '$backend/database/queries';
31
19
  import { debug } from '$shared/utils/logger';
32
- import { getSkillMdPath, copySkillInto } from './store';
33
-
34
- export type SkillEngine = 'claude' | 'codex' | 'copilot' | 'qwen' | 'opencode';
20
+ import { materializeArtifacts, resolveArtifact, isPromptScopedEngine, type ManagedArtifact, type ArtifactEngine } from '$backend/artifacts';
21
+ import { artifactFilter } from '$backend/profiles';
22
+ import { getSkillMdPath, getSkillDir } from './store';
23
+ import { stat } from 'node:fs/promises';
35
24
 
36
- const MARKER_START = '<!-- CLOPEN:SKILLS:START — managed block, do not edit -->';
37
- const MARKER_END = '<!-- CLOPEN:SKILLS:END -->';
25
+ /** Kept for backwards-compatible imports; identical to {@link ArtifactEngine}. */
26
+ export type SkillEngine = ArtifactEngine;
38
27
 
39
28
  interface EnabledSkill {
40
29
  slug: string;
@@ -46,69 +35,10 @@ function getEnabledSkills(): EnabledSkill[] {
46
35
  return skillQueries.getEnabled().map(r => ({ slug: r.slug, name: r.name, description: r.description }));
47
36
  }
48
37
 
49
- /**
50
- * Native engines read a real skills directory; this is where we mirror to.
51
- *
52
- * Claude's skills dir lives under its isolated `CLAUDE_CONFIG_DIR`, so it stays
53
- * fully inside Clopen's sandbox. Qwen and Copilot DO support skills natively but
54
- * resolve the user-level dir from `$HOME` (`~/.qwen/skills`, `~/.copilot/skills`)
55
- * — neither `QWEN_RUNTIME_DIR` nor `COPILOT_HOME` relocates it, and there is no
56
- * config-dir override. So for those two we manage the user's real global skills
57
- * dir, touching ONLY the slugs we own (see syncNative's prune guard) and never
58
- * the user's own skills.
59
- */
60
- function nativeSkillsDir(engine: SkillEngine): string | null {
61
- switch (engine) {
62
- case 'claude': return join(getEngineUserConfigDir('claude'), 'skills');
63
- case 'qwen': return join(homedir(), '.qwen', 'skills');
64
- case 'copilot': return join(homedir(), '.copilot', 'skills');
65
- default: return null;
66
- }
67
- }
68
-
69
- /**
70
- * Synthetic engines have no native skills concept — we inject the preamble into
71
- * the global instructions file each one auto-loads from its (isolated) home.
72
- */
73
- function syntheticMemoryFile(engine: SkillEngine): string | null {
74
- switch (engine) {
75
- // Codex loads global guidance from `$CODEX_HOME/AGENTS.md`.
76
- case 'codex': return join(getEngineUserConfigDir('codex'), 'AGENTS.md');
77
- // OpenCode reads `AGENTS.md` from its XDG config dir (`$XDG_CONFIG_HOME/opencode`).
78
- case 'opencode': return join(getEngineUserConfigDir('opencode'), 'opencode', 'AGENTS.md');
79
- default: return null;
80
- }
81
- }
82
-
83
- async function pathExists(path: string): Promise<boolean> {
84
- try { await stat(path); return true; } catch { return false; }
85
- }
86
-
87
- /** Mirror enabled skill folders into a native engine's skills dir; prune the rest. */
88
- async function syncNative(destDir: string, enabled: EnabledSkill[]): Promise<void> {
89
- await mkdir(destDir, { recursive: true });
90
- const enabledSlugs = new Set(enabled.map(s => s.slug));
91
- const managedSlugs = new Set(skillQueries.getAll().map(s => s.slug));
92
-
93
- // Remove copies of managed skills that are no longer enabled. Folders we
94
- // don't manage (e.g. user-placed skills) are left untouched.
95
- for (const entry of await readdir(destDir, { withFileTypes: true })) {
96
- if (!entry.isDirectory()) continue;
97
- if (managedSlugs.has(entry.name) && !enabledSlugs.has(entry.name)) {
98
- await rm(join(destDir, entry.name), { recursive: true, force: true });
99
- }
100
- }
101
-
102
- for (const skill of enabled) {
103
- await copySkillInto(skill.slug, destDir);
104
- }
105
- }
106
-
107
- /** Build the synthetic preamble block listing each enabled skill. */
108
- function buildPreamble(enabled: EnabledSkill[]): string {
109
- if (enabled.length === 0) return '';
38
+ /** The skills preamble — exact original wording, without the markers (added by the writer). */
39
+ function buildSkillsPreamble(items: ManagedArtifact[]): string {
40
+ if (items.length === 0) return '';
110
41
  const lines: string[] = [
111
- MARKER_START,
112
42
  '# Available Skills',
113
43
  '',
114
44
  'You have access to the following skills. Each is a set of instructions for a',
@@ -117,59 +47,89 @@ function buildPreamble(enabled: EnabledSkill[]): string {
117
47
  'before proceeding. Only load a skill when it is relevant.',
118
48
  ''
119
49
  ];
120
- for (const skill of enabled) {
50
+ for (const skill of items) {
121
51
  lines.push(`- **${skill.name}** — ${skill.description}`);
122
52
  lines.push(` Instructions: ${getSkillMdPath(skill.slug)}`);
123
53
  }
124
- lines.push(MARKER_END);
125
54
  return lines.join('\n');
126
55
  }
127
56
 
128
- /** Replace (or remove) the managed skills block inside an engine memory file. */
129
- async function syncSynthetic(filePath: string, enabled: EnabledSkill[]): Promise<void> {
130
- let existing = '';
131
- if (await pathExists(filePath)) existing = await readFile(filePath, 'utf8');
132
-
133
- // Strip any prior managed block so updates are idempotent and never duplicate.
134
- const blockRe = new RegExp(`\\n*${escapeRe(MARKER_START)}[\\s\\S]*?${escapeRe(MARKER_END)}\\n*`, 'g');
135
- const base = existing.replace(blockRe, '\n').replace(/\n{3,}/g, '\n\n').trim();
57
+ async function pathExists(path: string): Promise<boolean> {
58
+ try { await stat(path); return true; } catch { return false; }
59
+ }
136
60
 
137
- const block = buildPreamble(enabled);
138
- const next = block ? (base ? `${base}\n\n${block}\n` : `${block}\n`) : (base ? `${base}\n` : '');
61
+ /**
62
+ * The skills that apply to a stream, already narrowed by the active Profile.
63
+ * Shared by the native file materializer ({@link syncSkills}) and the synthetic
64
+ * per-session prompt injection ({@link buildSkillsPromptContext}) so both see an
65
+ * identical set.
66
+ *
67
+ * A profile is the source of truth for what's active: an item it references is
68
+ * included even if globally disabled, and its enable toggle is ignored. With no
69
+ * profile filter, only the globally-enabled set applies (unchanged behaviour).
70
+ */
71
+ export function resolveEnabledSkills(profileId?: number): ManagedArtifact[] {
72
+ const filter = artifactFilter(profileId, 'skill');
73
+ const source = filter
74
+ ? skillQueries.getAll().map(r => ({ slug: r.slug, name: r.name, description: r.description }))
75
+ : getEnabledSkills();
76
+ return source
77
+ .filter(s => !filter || filter.has(s.slug))
78
+ .map(s => ({
79
+ slug: s.slug,
80
+ name: s.name,
81
+ description: s.description,
82
+ sourceDir: getSkillDir(s.slug)
83
+ }));
84
+ }
139
85
 
140
- if (next === existing) return;
141
- if (next === '') {
142
- // Nothing managed and nothing else in the file — leave any empty file as-is.
143
- await writeFile(filePath, '', 'utf8');
144
- return;
145
- }
146
- await mkdir(join(filePath, '..'), { recursive: true });
147
- await writeFile(filePath, next, 'utf8');
86
+ /**
87
+ * Whether skills for this engine are delivered per-session via prompt injection
88
+ * INSTEAD of the shared global memory file — true only for a synthetic (no native
89
+ * dir) skill target on a prompt-scoped engine. Native skill engines
90
+ * (Claude/Qwen/Copilot) keep the folder mirror+prune.
91
+ */
92
+ function skillsViaPromptInjection(engine: SkillEngine): boolean {
93
+ const synthetic = resolveArtifact('skill', { engine, scope: 'global' }).format === 'preamble-region';
94
+ return synthetic && isPromptScopedEngine(engine);
148
95
  }
149
96
 
150
- function escapeRe(s: string): string {
151
- return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
97
+ /**
98
+ * The profile-scoped skills preamble for PER-SESSION injection into a synthetic
99
+ * engine's prompt (OpenCode/Codex). Returns '' when no skill applies. Uses the
100
+ * exact wording of the old global block, so model behaviour is unchanged apart
101
+ * from now being correctly scoped to the session's active Profile.
102
+ */
103
+ export function buildSkillsPromptContext(profileId?: number): string {
104
+ return buildSkillsPreamble(resolveEnabledSkills(profileId));
152
105
  }
153
106
 
154
107
  /**
155
- * Sync enabled skills for one engine. Safe to call at every stream start —
156
- * native dirs are reconciled and the synthetic block is rewritten in place.
108
+ * Sync enabled skills for one engine. Safe to call at every stream start.
157
109
  * Never throws: failures are logged and swallowed so streaming is unaffected.
110
+ *
111
+ * NATIVE engines (Claude/Qwen/Copilot) mirror the profile-narrowed skill folders
112
+ * into the engine's skills dir and prune the rest — a per-query-correct filter.
113
+ *
114
+ * SYNTHETIC engines (OpenCode/Codex) do NOT advertise skills through the shared
115
+ * global memory file here: a single global file can't encode a per-session
116
+ * profile choice and would leak across concurrent sessions (and their persistent
117
+ * server may not re-read it). Instead they inject the resolved preamble into each
118
+ * turn's prompt (see the adapters + {@link buildSkillsPromptContext}). We still
119
+ * materialize an EMPTY set for them so any legacy `CLOPEN:SKILLS` block left in
120
+ * AGENTS.md is stripped.
158
121
  */
159
- export async function syncSkills(engine: SkillEngine): Promise<void> {
122
+ export async function syncSkills(engine: SkillEngine, profileId?: number): Promise<void> {
160
123
  try {
161
- const enabled = getEnabledSkills();
162
- const native = nativeSkillsDir(engine);
163
- if (native) {
164
- await syncNative(native, enabled);
165
- debug.log('skills', `🧩 Synced ${enabled.length} skill(s) → ${engine} (native)`);
166
- return;
167
- }
168
- const memoryFile = syntheticMemoryFile(engine);
169
- if (memoryFile) {
170
- await syncSynthetic(memoryFile, enabled);
171
- debug.log('skills', `🧩 Synced ${enabled.length} skill(s) → ${engine} (synthetic)`);
172
- }
124
+ const viaPrompt = skillsViaPromptInjection(engine);
125
+ const enabled: ManagedArtifact[] = viaPrompt ? [] : resolveEnabledSkills(profileId);
126
+ const managedSlugs = skillQueries.getAll().map(s => s.slug);
127
+ await materializeArtifacts('skill', { engine, scope: 'global' }, {
128
+ enabled,
129
+ managedSlugs,
130
+ buildPreamble: buildSkillsPreamble
131
+ });
132
+ debug.log('skills', `🧩 Synced ${enabled.length} skill(s) → ${engine}${viaPrompt ? ' (per-session injection)' : ''}`);
173
133
  } catch (error) {
174
134
  debug.warn('skills', `⚠️ Skill sync for ${engine} failed (continuing without):`, error);
175
135
  }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Detect on-disk subagents (managed effective copies + adoptable real ones) for
3
+ * the Settings UI.
4
+ */
5
+
6
+ import { detectArtifacts, type DetectedArtifact, type ArtifactEngine } from '$backend/artifacts';
7
+
8
+ export interface DetectedSubagentGroup {
9
+ engine: ArtifactEngine;
10
+ detected: DetectedArtifact[];
11
+ }
12
+
13
+ export async function detectSubagents(projectPath?: string): Promise<DetectedSubagentGroup[]> {
14
+ const engines: ArtifactEngine[] = ['claude', 'codex', 'copilot', 'qwen', 'opencode'];
15
+ const scope = projectPath ? 'project' : 'global';
16
+ const groups = await Promise.all(
17
+ engines.map(async engine => ({
18
+ engine,
19
+ detected: await detectArtifacts('subagent', { engine, scope, projectPath })
20
+ }))
21
+ );
22
+ return groups.filter(g => g.detected.length > 0);
23
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Subagents — public facade. Settings → Subagents manages reusable specialized
3
+ * agent definitions, materialized into each engine at stream start.
4
+ */
5
+
6
+ export { subagentService } from './service';
7
+ export type { SubagentDTO, SubagentInputFields } from './service';
8
+ export { syncSubagents, syncSubagentsAllEngines, buildSubagentsPromptContext, buildOpenCodeInlineAgents } from './sync';
9
+ export type { OpenCodeInlineAgent } from './sync';
10
+ export { detectSubagents } from './detect';