@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.
- package/backend/artifacts/detect.ts +129 -0
- package/backend/artifacts/engine-map.ts +53 -0
- package/backend/artifacts/frontmatter.ts +68 -0
- package/backend/artifacts/generate.ts +105 -0
- package/backend/artifacts/index.ts +34 -0
- package/backend/artifacts/markers.ts +76 -0
- package/backend/artifacts/matrix.ts +247 -0
- package/backend/artifacts/slug.ts +35 -0
- package/backend/artifacts/sync.ts +130 -0
- package/backend/artifacts/types.ts +152 -0
- package/backend/auth/permissions.ts +51 -1
- package/backend/chat/stream-manager.ts +14 -1
- package/backend/commands/detect.ts +25 -0
- package/backend/commands/index.ts +9 -0
- package/backend/commands/service.ts +178 -0
- package/backend/commands/store.ts +45 -0
- package/backend/commands/sync.ts +94 -0
- package/backend/database/migrations/045_create_commands_table.ts +28 -0
- package/backend/database/migrations/046_create_subagents_table.ts +29 -0
- package/backend/database/migrations/047_create_instructions_table.ts +29 -0
- package/backend/database/migrations/048_add_mcp_tool_overrides.ts +23 -0
- package/backend/database/migrations/049_create_permission_sets_table.ts +50 -0
- package/backend/database/migrations/050_create_profiles_tables.ts +57 -0
- package/backend/database/migrations/051_add_profile_to_sessions.ts +20 -0
- package/backend/database/migrations/052_add_default_profile_to_projects.ts +20 -0
- package/backend/database/migrations/053_add_profile_to_permission_sets.ts +37 -0
- package/backend/database/migrations/054_drop_subagent_agent_type.ts +20 -0
- package/backend/database/migrations/055_artifact_model_tools_per_engine.ts +43 -0
- package/backend/database/migrations/index.ts +77 -0
- package/backend/database/queries/command-queries.ts +82 -0
- package/backend/database/queries/index.ts +12 -2
- package/backend/database/queries/instruction-queries.ts +62 -0
- package/backend/database/queries/mcp-server-queries.ts +25 -0
- package/backend/database/queries/permission-set-queries.ts +155 -0
- package/backend/database/queries/profile-queries.ts +118 -0
- package/backend/database/queries/project-queries.ts +14 -0
- package/backend/database/queries/session-queries.ts +10 -0
- package/backend/database/queries/subagent-queries.ts +92 -0
- package/backend/db-client/drivers/mysql.ts +21 -0
- package/backend/db-client/drivers/postgres.ts +20 -0
- package/backend/db-client/drivers/sqlite.ts +21 -0
- package/backend/db-client/drivers/types.ts +19 -0
- package/backend/db-client/query-executor.ts +89 -1
- package/backend/engine/adapters/claude/stream.ts +27 -3
- package/backend/engine/adapters/codex/stream.ts +46 -14
- package/backend/engine/adapters/copilot/stream.ts +58 -4
- package/backend/engine/adapters/opencode/message-converter.ts +22 -2
- package/backend/engine/adapters/opencode/server.ts +166 -210
- package/backend/engine/adapters/opencode/stream.ts +150 -24
- package/backend/engine/adapters/qwen/stream.ts +23 -3
- package/backend/engine/artifact-sync.ts +51 -0
- package/backend/engine/types.ts +6 -0
- package/backend/instructions/index.ts +8 -0
- package/backend/instructions/service.ts +63 -0
- package/backend/instructions/sync.ts +56 -0
- package/backend/mcp/external/config.ts +42 -20
- package/backend/mcp/external/proxy.ts +89 -5
- package/backend/mcp/external/tools.ts +88 -0
- package/backend/mcp/index.ts +38 -15
- package/backend/mcp/internal/config.ts +48 -11
- package/backend/mcp/internal/remote-server.ts +9 -1
- package/backend/permissions/index.ts +27 -0
- package/backend/permissions/materialize.ts +96 -0
- package/backend/permissions/resolve.test.ts +162 -0
- package/backend/permissions/resolve.ts +106 -0
- package/backend/permissions/service.ts +167 -0
- package/backend/profiles/index.ts +10 -0
- package/backend/profiles/service.ts +169 -0
- package/backend/skills/index.ts +1 -1
- package/backend/skills/sync.ts +88 -128
- package/backend/subagents/detect.ts +23 -0
- package/backend/subagents/index.ts +10 -0
- package/backend/subagents/service.ts +166 -0
- package/backend/subagents/store.ts +44 -0
- package/backend/subagents/sync.ts +144 -0
- package/backend/ws/artifacts/generate.ts +51 -0
- package/backend/ws/artifacts/index.ts +8 -0
- package/backend/ws/chat/stream.ts +33 -2
- package/backend/ws/commands/crud.ts +157 -0
- package/backend/ws/commands/index.ts +8 -0
- package/backend/ws/db-client/query-history-retention.test.ts +217 -0
- package/backend/ws/db-client/query.ts +77 -2
- package/backend/ws/git/branch.ts +4 -2
- package/backend/ws/git/ignored.ts +65 -0
- package/backend/ws/git/index.ts +3 -1
- package/backend/ws/git/remote.ts +21 -11
- package/backend/ws/index.ts +17 -1
- package/backend/ws/instructions/crud.ts +53 -0
- package/backend/ws/instructions/index.ts +8 -0
- package/backend/ws/mcp/crud.ts +7 -1
- package/backend/ws/mcp/index.ts +4 -1
- package/backend/ws/mcp/tools.ts +112 -0
- package/backend/ws/permissions/crud.ts +72 -0
- package/backend/ws/permissions/index.ts +8 -0
- package/backend/ws/profiles/crud.ts +149 -0
- package/backend/ws/profiles/index.ts +9 -0
- package/backend/ws/subagents/crud.ts +136 -0
- package/backend/ws/subagents/index.ts +8 -0
- package/dist/assets/__vite-browser-external-BIHI7g3E.js +1 -0
- package/dist/assets/index-BdRui-1z.js +1 -0
- package/dist/assets/{index-xrB3zcfA.js → index-BjaIjmd4.js} +1 -1
- package/dist/assets/{main-LBI3a0n5.js → main-Cf8SUfQ1.js} +387 -302
- package/dist/assets/main-D4pdkiQK.css +1 -0
- package/dist/assets/zipkit-engine-CaR0t_Uy.wasm +0 -0
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/shared/constants/engine-tools.ts +56 -0
- package/shared/types/database/schema.ts +2 -0
- package/shared/types/db-client/query.ts +33 -0
- package/shared/types/stores/settings.ts +15 -0
- package/shared/types/unified/stream.ts +7 -0
- package/shared/utils/db-client/split-sql.test.ts +88 -0
- package/shared/utils/db-client/split-sql.ts +132 -0
- package/shared/utils/logger.ts +6 -0
- package/dist/assets/main-BXS8bjJ6.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
|
+
}
|
package/backend/skills/index.ts
CHANGED
|
@@ -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';
|
package/backend/skills/sync.ts
CHANGED
|
@@ -1,40 +1,29 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Engine sync —
|
|
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
|
-
*
|
|
5
|
-
* - NATIVE (Claude, Qwen, Copilot):
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
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
|
|
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 {
|
|
33
|
-
|
|
34
|
-
|
|
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
|
-
|
|
37
|
-
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
129
|
-
|
|
130
|
-
|
|
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
|
-
|
|
138
|
-
|
|
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
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
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
|
-
|
|
151
|
-
|
|
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
|
|
162
|
-
const
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
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';
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Subagent service — keeps the `subagents` table and the on-disk canonical store
|
|
3
|
+
* in lockstep for Settings → Subagents. Skills-shaped, plus a per-engine tool
|
|
4
|
+
* allowlist and per-engine model override (JSON maps keyed by EngineType). The
|
|
5
|
+
* canonical `.md` holds only name/description/body; model & tools are injected
|
|
6
|
+
* per engine at sync time.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { subagentQueries, type SubagentRow } from '$backend/database/queries';
|
|
10
|
+
import { parseDoc, serializeDoc, uniqueSlug, parseEngineMap, stringifyEngineMap, normalizeToolList, type EngineMap } from '$backend/artifacts';
|
|
11
|
+
import { debug } from '$shared/utils/logger';
|
|
12
|
+
import {
|
|
13
|
+
writeSubagentMd,
|
|
14
|
+
readSubagentMd,
|
|
15
|
+
deleteSubagentMd,
|
|
16
|
+
subagentFileExists
|
|
17
|
+
} from './store';
|
|
18
|
+
|
|
19
|
+
export interface SubagentDTO {
|
|
20
|
+
id: number;
|
|
21
|
+
slug: string;
|
|
22
|
+
name: string;
|
|
23
|
+
description: string;
|
|
24
|
+
/** Per-engine tool allowlist (EngineType → comma list; absent = all tools). */
|
|
25
|
+
toolsByEngine: EngineMap;
|
|
26
|
+
/** Per-engine model override (EngineType → model id; absent = inherit). */
|
|
27
|
+
modelByEngine: EngineMap;
|
|
28
|
+
source: 'custom' | 'imported';
|
|
29
|
+
enabled: boolean;
|
|
30
|
+
present: boolean;
|
|
31
|
+
createdAt: string;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface SubagentInputFields {
|
|
35
|
+
name: string;
|
|
36
|
+
description: string;
|
|
37
|
+
toolsByEngine?: EngineMap;
|
|
38
|
+
modelByEngine?: EngineMap;
|
|
39
|
+
body: string;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const FRONTMATTER_ORDER = ['name', 'description'];
|
|
43
|
+
|
|
44
|
+
function toDTO(row: SubagentRow, present: boolean): SubagentDTO {
|
|
45
|
+
return {
|
|
46
|
+
id: row.id,
|
|
47
|
+
slug: row.slug,
|
|
48
|
+
name: row.name,
|
|
49
|
+
description: row.description,
|
|
50
|
+
toolsByEngine: parseEngineMap(row.tools_by_engine),
|
|
51
|
+
modelByEngine: parseEngineMap(row.model_by_engine),
|
|
52
|
+
source: row.source,
|
|
53
|
+
enabled: row.is_enabled === 1,
|
|
54
|
+
present,
|
|
55
|
+
createdAt: row.created_at
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Normalise each per-engine tool allowlist string into `a, b, c`. */
|
|
60
|
+
function normalizeToolsMap(map: EngineMap | undefined): EngineMap {
|
|
61
|
+
const out: EngineMap = {};
|
|
62
|
+
for (const [engine, list] of Object.entries(map ?? {})) {
|
|
63
|
+
const normalized = normalizeToolList(list);
|
|
64
|
+
if (normalized) out[engine as keyof EngineMap] = normalized;
|
|
65
|
+
}
|
|
66
|
+
return out;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** An imported Claude-shaped `.md` maps its single frontmatter value → claude slot. */
|
|
70
|
+
function singleToMap(value: string | undefined): EngineMap {
|
|
71
|
+
return value?.trim() ? { 'claude-code': value.trim() } : {};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Canonical doc holds name + description only; model/tools are per-engine (sync-injected). */
|
|
75
|
+
function buildDocument(slug: string, fields: SubagentInputFields): string {
|
|
76
|
+
const frontmatter: Record<string, string> = { name: slug };
|
|
77
|
+
if (fields.description.trim()) frontmatter.description = fields.description.trim();
|
|
78
|
+
return serializeDoc({ frontmatter, body: fields.body }, FRONTMATTER_ORDER);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export const subagentService = {
|
|
82
|
+
async list(): Promise<SubagentDTO[]> {
|
|
83
|
+
const rows = subagentQueries.getAll();
|
|
84
|
+
const presence = await Promise.all(rows.map(r => subagentFileExists(r.slug)));
|
|
85
|
+
return rows.map((row, i) => toDTO(row, presence[i]));
|
|
86
|
+
},
|
|
87
|
+
|
|
88
|
+
async get(id: number): Promise<{ subagent: SubagentDTO; body: string } | null> {
|
|
89
|
+
const row = subagentQueries.getById(id);
|
|
90
|
+
if (!row) return null;
|
|
91
|
+
const raw = await readSubagentMd(row.slug);
|
|
92
|
+
const body = raw ? parseDoc(raw).body : '';
|
|
93
|
+
return { subagent: toDTO(row, raw !== null), body };
|
|
94
|
+
},
|
|
95
|
+
|
|
96
|
+
async create(input: SubagentInputFields): Promise<SubagentDTO> {
|
|
97
|
+
if (!input.name.trim()) throw new Error('A subagent name is required');
|
|
98
|
+
if (!input.description.trim()) throw new Error('A subagent description is required');
|
|
99
|
+
const slug = uniqueSlug(input.name, s => !!subagentQueries.getBySlug(s));
|
|
100
|
+
await writeSubagentMd(slug, buildDocument(slug, input));
|
|
101
|
+
const row = subagentQueries.insert({
|
|
102
|
+
slug,
|
|
103
|
+
name: input.name.trim(),
|
|
104
|
+
description: input.description.trim(),
|
|
105
|
+
toolsByEngine: stringifyEngineMap(normalizeToolsMap(input.toolsByEngine)),
|
|
106
|
+
modelByEngine: stringifyEngineMap(input.modelByEngine),
|
|
107
|
+
source: 'custom'
|
|
108
|
+
});
|
|
109
|
+
debug.log('subagents', `📦 Created subagent: ${slug}`);
|
|
110
|
+
return toDTO(row, true);
|
|
111
|
+
},
|
|
112
|
+
|
|
113
|
+
async update(id: number, input: SubagentInputFields): Promise<SubagentDTO> {
|
|
114
|
+
const row = subagentQueries.getById(id);
|
|
115
|
+
if (!row) throw new Error('Subagent not found');
|
|
116
|
+
if (!input.description.trim()) throw new Error('A subagent description is required');
|
|
117
|
+
await writeSubagentMd(row.slug, buildDocument(row.slug, input));
|
|
118
|
+
subagentQueries.updateMeta(
|
|
119
|
+
id,
|
|
120
|
+
input.name.trim(),
|
|
121
|
+
input.description.trim(),
|
|
122
|
+
stringifyEngineMap(normalizeToolsMap(input.toolsByEngine)),
|
|
123
|
+
stringifyEngineMap(input.modelByEngine)
|
|
124
|
+
);
|
|
125
|
+
debug.log('subagents', `🔧 Updated subagent: ${row.slug}`);
|
|
126
|
+
return toDTO(subagentQueries.getById(id)!, true);
|
|
127
|
+
},
|
|
128
|
+
|
|
129
|
+
parsePreview(raw: string): { name: string; description: string; toolsByEngine: EngineMap; modelByEngine: EngineMap; body: string } {
|
|
130
|
+
const parsed = parseDoc(raw);
|
|
131
|
+
return {
|
|
132
|
+
name: parsed.frontmatter.name || '',
|
|
133
|
+
description: parsed.frontmatter.description || '',
|
|
134
|
+
toolsByEngine: singleToMap(parsed.frontmatter.tools),
|
|
135
|
+
modelByEngine: singleToMap(parsed.frontmatter.model),
|
|
136
|
+
body: parsed.body
|
|
137
|
+
};
|
|
138
|
+
},
|
|
139
|
+
|
|
140
|
+
async import(raw: string, nameHint?: string): Promise<SubagentDTO> {
|
|
141
|
+
const parsed = parseDoc(raw);
|
|
142
|
+
const displayName = (nameHint?.trim() || parsed.frontmatter.name || 'subagent').trim();
|
|
143
|
+
return this.create({
|
|
144
|
+
name: displayName,
|
|
145
|
+
description: parsed.frontmatter.description || '',
|
|
146
|
+
toolsByEngine: singleToMap(parsed.frontmatter.tools),
|
|
147
|
+
modelByEngine: singleToMap(parsed.frontmatter.model),
|
|
148
|
+
body: parsed.body
|
|
149
|
+
});
|
|
150
|
+
},
|
|
151
|
+
|
|
152
|
+
toggle(id: number, enabled: boolean): SubagentDTO {
|
|
153
|
+
const row = subagentQueries.getById(id);
|
|
154
|
+
if (!row) throw new Error('Subagent not found');
|
|
155
|
+
subagentQueries.setEnabled(id, enabled);
|
|
156
|
+
return toDTO(subagentQueries.getById(id)!, true);
|
|
157
|
+
},
|
|
158
|
+
|
|
159
|
+
async remove(id: number): Promise<void> {
|
|
160
|
+
const row = subagentQueries.getById(id);
|
|
161
|
+
if (!row) throw new Error('Subagent not found');
|
|
162
|
+
await deleteSubagentMd(row.slug);
|
|
163
|
+
subagentQueries.remove(id);
|
|
164
|
+
debug.log('subagents', `🗑️ Deleted subagent: ${row.slug}`);
|
|
165
|
+
}
|
|
166
|
+
};
|