@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,129 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Detect & link — discover artifacts that already exist on disk (in Clopen's
|
|
3
|
+
* effective engine dirs AND in the user's real standard locations), and adopt a
|
|
4
|
+
* real one into the effective dir via symlink so it takes effect for Clopen's
|
|
5
|
+
* engines without moving the user's file.
|
|
6
|
+
*
|
|
7
|
+
* "Honest to on-disk" (we report what's actually there) AND "effective for
|
|
8
|
+
* Clopen" (adoption uses a symlink into the isolated engine dir). Only slugs the
|
|
9
|
+
* user chooses to adopt are ever touched.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { join } from 'path';
|
|
13
|
+
import { readdir, readFile, stat, symlink, mkdir, lstat, rm } from 'node:fs/promises';
|
|
14
|
+
import { debug } from '$shared/utils/logger';
|
|
15
|
+
import { resolveArtifact } from './matrix';
|
|
16
|
+
import { readManagedBlock, markersFor } from './markers';
|
|
17
|
+
import type { ArtifactContext, ArtifactType, DetectedArtifact } from './types';
|
|
18
|
+
|
|
19
|
+
async function pathExists(path: string): Promise<boolean> {
|
|
20
|
+
try {
|
|
21
|
+
await stat(path);
|
|
22
|
+
return true;
|
|
23
|
+
} catch {
|
|
24
|
+
return false;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Cheap frontmatter name/description reader (no full YAML parse). */
|
|
29
|
+
async function readMeta(file: string): Promise<{ name?: string; description?: string }> {
|
|
30
|
+
try {
|
|
31
|
+
const raw = await readFile(file, 'utf8');
|
|
32
|
+
const m = /^---[ \t]*\r?\n([\s\S]*?)\r?\n---/.exec(raw.replace(/^\uFEFF/, ''));
|
|
33
|
+
if (!m) return {};
|
|
34
|
+
const out: { name?: string; description?: string } = {};
|
|
35
|
+
for (const line of m[1].split(/\r?\n/)) {
|
|
36
|
+
const kv = /^(name|description):\s*(.*)$/.exec(line);
|
|
37
|
+
if (kv) out[kv[1] as 'name' | 'description'] = kv[2].replace(/^["']|["']$/g, '').trim();
|
|
38
|
+
}
|
|
39
|
+
return out;
|
|
40
|
+
} catch {
|
|
41
|
+
return {};
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** List `<slug>` artifacts inside a folder-md / single-md directory. */
|
|
46
|
+
async function scanDir(dir: string, format: 'folder-md' | 'single-md', managed: boolean, adoptable: boolean): Promise<DetectedArtifact[]> {
|
|
47
|
+
if (!(await pathExists(dir))) return [];
|
|
48
|
+
const out: DetectedArtifact[] = [];
|
|
49
|
+
for (const entry of await readdir(dir, { withFileTypes: true })) {
|
|
50
|
+
if (entry.name.startsWith('.')) continue;
|
|
51
|
+
if (format === 'folder-md') {
|
|
52
|
+
if (!entry.isDirectory()) continue;
|
|
53
|
+
const slug = entry.name;
|
|
54
|
+
const meta = await readMeta(join(dir, slug, 'SKILL.md'));
|
|
55
|
+
out.push({ slug, name: meta.name || slug, description: meta.description || '', path: join(dir, slug), managed, adoptable });
|
|
56
|
+
} else {
|
|
57
|
+
if (!entry.isFile() || !entry.name.endsWith('.md')) continue;
|
|
58
|
+
const slug = entry.name.replace(/\.md$/, '');
|
|
59
|
+
const meta = await readMeta(join(dir, entry.name));
|
|
60
|
+
out.push({ slug, name: meta.name || slug, description: meta.description || '', path: join(dir, entry.name), managed, adoptable });
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return out;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Detect artifacts of a type for one engine/scope. Merges Clopen-managed
|
|
68
|
+
* effective locations with the user's real standard locations (deduped by slug,
|
|
69
|
+
* effective winning) so the UI can show what exists and what can be adopted.
|
|
70
|
+
*/
|
|
71
|
+
export async function detectArtifacts(type: ArtifactType, ctx: ArtifactContext): Promise<DetectedArtifact[]> {
|
|
72
|
+
const resolution = resolveArtifact(type, ctx);
|
|
73
|
+
if (!resolution.supported) return [];
|
|
74
|
+
|
|
75
|
+
const bySlug = new Map<string, DetectedArtifact>();
|
|
76
|
+
|
|
77
|
+
if (resolution.format === 'preamble-region') {
|
|
78
|
+
const file = resolution.locateEffective(ctx);
|
|
79
|
+
if (file && (await pathExists(file))) {
|
|
80
|
+
const block = readManagedBlock(await readFile(file, 'utf8'), markersFor('INSTRUCTIONS'));
|
|
81
|
+
if (block != null) {
|
|
82
|
+
bySlug.set('instructions', { slug: 'instructions', name: 'Project instructions', description: '', path: file, managed: true, adoptable: false });
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return [...bySlug.values()];
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// Detection only applies to the directory-backed formats (Skills' `folder-md`,
|
|
89
|
+
// Commands'/Subagents' `single-md`). Other formats (`json`/`toml`/preamble)
|
|
90
|
+
// have no scannable artifact directory — nothing to detect on disk.
|
|
91
|
+
if (resolution.format !== 'folder-md' && resolution.format !== 'single-md') return [];
|
|
92
|
+
const format = resolution.format;
|
|
93
|
+
const effective = await scanDir(resolution.locateEffective(ctx), format, true, false);
|
|
94
|
+
for (const a of effective) bySlug.set(a.slug, a);
|
|
95
|
+
|
|
96
|
+
for (const real of resolution.locateReal?.(ctx) ?? []) {
|
|
97
|
+
for (const a of await scanDir(real, format, false, true)) {
|
|
98
|
+
if (!bySlug.has(a.slug)) bySlug.set(a.slug, a);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
return [...bySlug.values()];
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Adopt a real on-disk artifact into the engine's effective dir via symlink, so
|
|
107
|
+
* it takes effect for Clopen's isolated engine without relocating the user's
|
|
108
|
+
* file. Returns the symlink path created.
|
|
109
|
+
*/
|
|
110
|
+
export async function adoptArtifact(type: ArtifactType, ctx: ArtifactContext, realPath: string, slug: string): Promise<string> {
|
|
111
|
+
const resolution = resolveArtifact(type, ctx);
|
|
112
|
+
if (!resolution.supported || resolution.format === 'preamble-region') {
|
|
113
|
+
throw new Error(`Artifact type "${type}" cannot be adopted by link`);
|
|
114
|
+
}
|
|
115
|
+
const effectiveDir = resolution.locateEffective(ctx);
|
|
116
|
+
await mkdir(effectiveDir, { recursive: true });
|
|
117
|
+
const linkPath = join(effectiveDir, resolution.format === 'single-md' ? `${slug}.md` : slug);
|
|
118
|
+
|
|
119
|
+
// Replace any existing entry at the link path (idempotent adoption).
|
|
120
|
+
try {
|
|
121
|
+
await lstat(linkPath);
|
|
122
|
+
await rm(linkPath, { recursive: true, force: true });
|
|
123
|
+
} catch {
|
|
124
|
+
/* nothing there */
|
|
125
|
+
}
|
|
126
|
+
await symlink(realPath, linkPath);
|
|
127
|
+
debug.log('artifacts', `🔗 Adopted ${type} "${slug}" → ${linkPath}`);
|
|
128
|
+
return linkPath;
|
|
129
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-engine value maps for artifacts (command/subagent model & tool overrides).
|
|
3
|
+
*
|
|
4
|
+
* Stored in the DB as a JSON object keyed by `EngineType` ('claude-code',
|
|
5
|
+
* 'opencode', …). An absent/blank entry means "inherit" (model) or "all tools"
|
|
6
|
+
* (tool allowlist) for that engine. Keyed by `EngineType` — the frontend's
|
|
7
|
+
* canonical engine id — so the editor round-trips without translation; the sync
|
|
8
|
+
* layer maps its `ArtifactEngine` ('claude') to `EngineType` ('claude-code')
|
|
9
|
+
* when reading a value (see `artifactEngineToType`).
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import type { EngineType } from '$shared/types/unified';
|
|
13
|
+
import type { ArtifactEngine } from './types';
|
|
14
|
+
|
|
15
|
+
export type EngineMap = Partial<Record<EngineType, string>>;
|
|
16
|
+
|
|
17
|
+
/** Parse a stored JSON map, tolerating null/blank/corrupt values. */
|
|
18
|
+
export function parseEngineMap(json: string | null | undefined): EngineMap {
|
|
19
|
+
if (!json) return {};
|
|
20
|
+
try {
|
|
21
|
+
const parsed = JSON.parse(json);
|
|
22
|
+
if (!parsed || typeof parsed !== 'object') return {};
|
|
23
|
+
const out: EngineMap = {};
|
|
24
|
+
for (const [k, v] of Object.entries(parsed)) {
|
|
25
|
+
if (typeof v === 'string' && v.trim()) out[k as EngineType] = v.trim();
|
|
26
|
+
}
|
|
27
|
+
return out;
|
|
28
|
+
} catch {
|
|
29
|
+
return {};
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Serialize a map to JSON, dropping blank entries so `{}` means "no overrides". */
|
|
34
|
+
export function stringifyEngineMap(map: EngineMap | undefined): string {
|
|
35
|
+
if (!map) return '{}';
|
|
36
|
+
const out: EngineMap = {};
|
|
37
|
+
for (const [k, v] of Object.entries(map)) {
|
|
38
|
+
if (typeof v === 'string' && v.trim()) out[k as EngineType] = v.trim();
|
|
39
|
+
}
|
|
40
|
+
return JSON.stringify(out);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** The sync layer iterates `ArtifactEngine`; resolve the map key for one engine. */
|
|
44
|
+
export function artifactEngineToType(engine: ArtifactEngine): EngineType {
|
|
45
|
+
return engine === 'claude' ? 'claude-code' : engine;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Normalise a tool allowlist string (comma/space separated) into `a, b, c` (null when empty). */
|
|
49
|
+
export function normalizeToolList(tools?: string | null): string | null {
|
|
50
|
+
if (!tools) return null;
|
|
51
|
+
const list = tools.split(/[\s,]+/).map(t => t.trim()).filter(Boolean);
|
|
52
|
+
return list.length ? list.join(', ') : null;
|
|
53
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minimal flat-frontmatter parse/serialize, shared by the single-md artifact
|
|
3
|
+
* features (Commands, Subagents). Deliberately tiny — a flat `key: value` map
|
|
4
|
+
* plus a Markdown body — mirroring the hand-rolled approach in
|
|
5
|
+
* `backend/skills/spec.ts` so we avoid a YAML dependency. Unknown keys are
|
|
6
|
+
* preserved verbatim for lossless round-trips.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export interface ParsedDoc {
|
|
10
|
+
frontmatter: Record<string, string>;
|
|
11
|
+
body: string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Strip matching single/double quotes from a scalar value. */
|
|
15
|
+
function unquote(value: string): string {
|
|
16
|
+
const v = value.trim();
|
|
17
|
+
if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) {
|
|
18
|
+
return v.slice(1, -1);
|
|
19
|
+
}
|
|
20
|
+
return v;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Quote a scalar for YAML output only when it could otherwise be misparsed. */
|
|
24
|
+
function quoteIfNeeded(value: string): string {
|
|
25
|
+
if (value === '') return '""';
|
|
26
|
+
if (/[:#"'\n]|^[\s]|[\s]$|^[[{>|&*!%@`]/.test(value)) {
|
|
27
|
+
return `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
|
|
28
|
+
}
|
|
29
|
+
return value;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Split a document into its frontmatter block and body (null if no fence). */
|
|
33
|
+
function splitFrontmatter(raw: string): { fm: string; body: string } | null {
|
|
34
|
+
const text = raw.replace(/^\uFEFF/, '');
|
|
35
|
+
const match = /^---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n([\s\S]*))?$/.exec(text);
|
|
36
|
+
if (!match) return null;
|
|
37
|
+
return { fm: match[1], body: (match[2] ?? '').replace(/^\r?\n/, '') };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Parse a flat-frontmatter Markdown document. A missing fence yields an empty map + full body. */
|
|
41
|
+
export function parseDoc(raw: string): ParsedDoc {
|
|
42
|
+
const split = splitFrontmatter(raw);
|
|
43
|
+
if (!split) return { frontmatter: {}, body: raw.trim() };
|
|
44
|
+
const frontmatter: Record<string, string> = {};
|
|
45
|
+
for (const line of split.fm.split(/\r?\n/)) {
|
|
46
|
+
if (line.trim() === '' || line.trim().startsWith('#')) continue;
|
|
47
|
+
const m = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(line);
|
|
48
|
+
if (m) frontmatter[m[1]] = unquote(m[2]);
|
|
49
|
+
}
|
|
50
|
+
return { frontmatter, body: split.body };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Serialize a flat-frontmatter document. `order` lists keys to emit first (in
|
|
55
|
+
* order); remaining keys follow in insertion order. Empty values are skipped.
|
|
56
|
+
*/
|
|
57
|
+
export function serializeDoc(doc: ParsedDoc, order: string[] = []): string {
|
|
58
|
+
const keys = [...order.filter(k => doc.frontmatter[k]), ...Object.keys(doc.frontmatter).filter(k => !order.includes(k))];
|
|
59
|
+
const lines = ['---'];
|
|
60
|
+
for (const k of keys) {
|
|
61
|
+
const v = doc.frontmatter[k];
|
|
62
|
+
if (v == null || v === '') continue;
|
|
63
|
+
lines.push(`${k}: ${quoteIfNeeded(v)}`);
|
|
64
|
+
}
|
|
65
|
+
lines.push('---');
|
|
66
|
+
const body = doc.body.replace(/^\s+/, '').replace(/\s+$/, '');
|
|
67
|
+
return `${lines.join('\n')}\n\n${body}\n`;
|
|
68
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AI authoring — generate a draft artifact (Skill / Command / Subagent /
|
|
3
|
+
* Instruction) from a single "purpose" sentence, so the user fills one input
|
|
4
|
+
* instead of every field by hand. Reuses the engines' one-shot
|
|
5
|
+
* `generateStructured` (the same path as git commit-message generation), so no
|
|
6
|
+
* new model plumbing is introduced.
|
|
7
|
+
*
|
|
8
|
+
* Schemas follow the strict structured-output convention (OpenAI/Codex): every
|
|
9
|
+
* object declares `additionalProperties: false`, every property is `required`,
|
|
10
|
+
* and optional fields are nullable unions rather than omitted.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { initializeEngine } from '$backend/engine';
|
|
14
|
+
import { getClopenDir } from '$backend/utils/paths';
|
|
15
|
+
import type { EngineType } from '$shared/types/unified';
|
|
16
|
+
import { debug } from '$shared/utils/logger';
|
|
17
|
+
|
|
18
|
+
export type GeneratableType = 'skill' | 'command' | 'subagent' | 'instruction';
|
|
19
|
+
|
|
20
|
+
const SCHEMAS: Record<GeneratableType, Record<string, unknown>> = {
|
|
21
|
+
skill: {
|
|
22
|
+
type: 'object',
|
|
23
|
+
additionalProperties: false,
|
|
24
|
+
properties: {
|
|
25
|
+
name: { type: 'string', description: 'Short human name for the skill' },
|
|
26
|
+
description: { type: 'string', description: 'What it does AND when to use it (one or two sentences)' },
|
|
27
|
+
body: { type: 'string', description: 'Markdown instructions the agent follows when the skill is active' }
|
|
28
|
+
},
|
|
29
|
+
required: ['name', 'description', 'body']
|
|
30
|
+
},
|
|
31
|
+
command: {
|
|
32
|
+
type: 'object',
|
|
33
|
+
additionalProperties: false,
|
|
34
|
+
properties: {
|
|
35
|
+
name: { type: 'string', description: 'Short human name for the command' },
|
|
36
|
+
description: { type: 'string', description: 'One line describing what the command does' },
|
|
37
|
+
argumentHint: { type: ['string', 'null'], description: 'Hint for expected arguments, e.g. "[pr-number]". Null if none.' },
|
|
38
|
+
body: { type: 'string', description: 'The prompt the command runs. Use $ARGUMENTS where user input belongs.' }
|
|
39
|
+
},
|
|
40
|
+
required: ['name', 'description', 'argumentHint', 'body']
|
|
41
|
+
},
|
|
42
|
+
subagent: {
|
|
43
|
+
type: 'object',
|
|
44
|
+
additionalProperties: false,
|
|
45
|
+
properties: {
|
|
46
|
+
name: { type: 'string', description: 'Short human name for the subagent' },
|
|
47
|
+
description: { type: 'string', description: 'What it does and when to delegate to it' },
|
|
48
|
+
tools: { type: ['string', 'null'], description: 'Comma-separated tool allowlist (e.g. "Read, Grep, Bash"). Null = all tools.' },
|
|
49
|
+
body: { type: 'string', description: 'The subagent system prompt (its role and behavior).' }
|
|
50
|
+
},
|
|
51
|
+
required: ['name', 'description', 'tools', 'body']
|
|
52
|
+
},
|
|
53
|
+
instruction: {
|
|
54
|
+
type: 'object',
|
|
55
|
+
additionalProperties: false,
|
|
56
|
+
properties: {
|
|
57
|
+
content: { type: 'string', description: 'The instruction block: concise directives the agent should always follow.' }
|
|
58
|
+
},
|
|
59
|
+
required: ['content']
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
const GUIDANCE: Record<GeneratableType, string> = {
|
|
64
|
+
skill: 'Author a reusable Agent Skill. The description must state what it does and when to use it. The body is step-by-step Markdown instructions.',
|
|
65
|
+
command: 'Author a reusable slash-command prompt. The body is the prompt template; put $ARGUMENTS where the user-supplied text should be inserted.',
|
|
66
|
+
subagent: 'Author a specialized subagent. The description tells the parent agent when to delegate. The body is the subagent system prompt. Only set tools if the purpose implies a restricted allowlist; otherwise null.',
|
|
67
|
+
instruction: 'Author a shared instruction block — concise, imperative directives the agent should always follow. No preamble, just the directives.'
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
export interface GenerateModel {
|
|
71
|
+
engine: EngineType;
|
|
72
|
+
providerSlug: string;
|
|
73
|
+
modelId: string;
|
|
74
|
+
/** Optional cwd for the engine process; defaults to the Clopen data dir. */
|
|
75
|
+
projectPath?: string;
|
|
76
|
+
accountId?: number;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Generate a draft artifact of `type` from a free-text purpose. */
|
|
80
|
+
export async function generateArtifact(type: GeneratableType, purpose: string, model: GenerateModel): Promise<Record<string, unknown>> {
|
|
81
|
+
const engine = await initializeEngine(model.engine);
|
|
82
|
+
if (!engine.generateStructured) {
|
|
83
|
+
throw new Error(`Engine "${model.engine}" does not support AI generation`);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const prompt = `${GUIDANCE[type]}
|
|
87
|
+
|
|
88
|
+
Produce a high-quality draft from this purpose:
|
|
89
|
+
"""
|
|
90
|
+
${purpose.trim()}
|
|
91
|
+
"""
|
|
92
|
+
|
|
93
|
+
Always write the draft in English, regardless of the language of the purpose. Be specific and immediately usable.`;
|
|
94
|
+
|
|
95
|
+
debug.log('artifacts', `✨ Generating ${type} draft via ${model.engine}/${model.modelId}`);
|
|
96
|
+
|
|
97
|
+
return engine.generateStructured<Record<string, unknown>>({
|
|
98
|
+
prompt,
|
|
99
|
+
providerSlug: model.providerSlug,
|
|
100
|
+
modelId: model.modelId,
|
|
101
|
+
schema: SCHEMAS[type],
|
|
102
|
+
projectPath: model.projectPath || getClopenDir(),
|
|
103
|
+
accountId: model.accountId
|
|
104
|
+
});
|
|
105
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Artifact framework — public facade.
|
|
3
|
+
*
|
|
4
|
+
* The shared capability-matrix foundation used by every engine-artifact feature
|
|
5
|
+
* (Skills, Commands, Subagents, Instructions). See `types.ts` for the model and
|
|
6
|
+
* the reserved `'mcp'` slot rationale.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export type {
|
|
10
|
+
ArtifactEngine,
|
|
11
|
+
ArtifactType,
|
|
12
|
+
ArtifactScope,
|
|
13
|
+
ArtifactFormat,
|
|
14
|
+
ArtifactOwnership,
|
|
15
|
+
ArtifactContext,
|
|
16
|
+
ManagedArtifact,
|
|
17
|
+
DetectedArtifact,
|
|
18
|
+
ArtifactResolution,
|
|
19
|
+
ArtifactMarkers
|
|
20
|
+
} from './types';
|
|
21
|
+
export { ARTIFACT_ENGINES } from './types';
|
|
22
|
+
|
|
23
|
+
export { resolveArtifact, isBestEffortTarget, isPromptScopedEngine, PROMPT_SCOPED_ENGINES, memoryFileName } from './matrix';
|
|
24
|
+
export { materializeArtifacts } from './sync';
|
|
25
|
+
export type { MaterializeInput } from './sync';
|
|
26
|
+
export { detectArtifacts, adoptArtifact } from './detect';
|
|
27
|
+
export { markersFor, writeManagedBlock, readManagedBlock, stripManagedBlock } from './markers';
|
|
28
|
+
export { parseDoc, serializeDoc } from './frontmatter';
|
|
29
|
+
export type { ParsedDoc } from './frontmatter';
|
|
30
|
+
export { slugify, uniqueSlug, isValidSlug } from './slug';
|
|
31
|
+
export { parseEngineMap, stringifyEngineMap, artifactEngineToType, normalizeToolList } from './engine-map';
|
|
32
|
+
export type { EngineMap } from './engine-map';
|
|
33
|
+
export { generateArtifact } from './generate';
|
|
34
|
+
export type { GeneratableType, GenerateModel } from './generate';
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Marker-region file editing — the shared primitive for `preamble-region` and
|
|
3
|
+
* `marker-region` ownership. Clopen owns only the delimited block; everything
|
|
4
|
+
* outside it is the user's (or another engine's) hand-written content and is
|
|
5
|
+
* preserved verbatim on every rewrite.
|
|
6
|
+
*
|
|
7
|
+
* Extracted from the original Skills sync so Instructions, synthetic Skills,
|
|
8
|
+
* Commands and Subagents all share one idempotent implementation.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { mkdir, readFile, writeFile, stat } from 'node:fs/promises';
|
|
12
|
+
import { join } from 'path';
|
|
13
|
+
import type { ArtifactMarkers } from './types';
|
|
14
|
+
|
|
15
|
+
/** Build a START/END marker pair for a given managed block id (e.g. `SKILLS`). */
|
|
16
|
+
export function markersFor(id: string): ArtifactMarkers {
|
|
17
|
+
return {
|
|
18
|
+
start: `<!-- CLOPEN:${id}:START — managed block, do not edit -->`,
|
|
19
|
+
end: `<!-- CLOPEN:${id}:END -->`
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function escapeRe(s: string): string {
|
|
24
|
+
return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async function pathExists(path: string): Promise<boolean> {
|
|
28
|
+
try {
|
|
29
|
+
await stat(path);
|
|
30
|
+
return true;
|
|
31
|
+
} catch {
|
|
32
|
+
return false;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Strip any existing managed block, returning the surrounding user content trimmed. */
|
|
37
|
+
export function stripManagedBlock(existing: string, markers: ArtifactMarkers): string {
|
|
38
|
+
const blockRe = new RegExp(`\\n*${escapeRe(markers.start)}[\\s\\S]*?${escapeRe(markers.end)}\\n*`, 'g');
|
|
39
|
+
return existing.replace(blockRe, '\n').replace(/\n{3,}/g, '\n\n').trim();
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Extract the inner body of the managed block (between the markers), or null. */
|
|
43
|
+
export function readManagedBlock(content: string, markers: ArtifactMarkers): string | null {
|
|
44
|
+
const re = new RegExp(`${escapeRe(markers.start)}\\r?\\n?([\\s\\S]*?)\\r?\\n?${escapeRe(markers.end)}`);
|
|
45
|
+
const m = re.exec(content);
|
|
46
|
+
return m ? m[1] : null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Rewrite the managed block inside `filePath` idempotently. `block` is the inner
|
|
51
|
+
* content WITHOUT the markers (they are added here); pass an empty string to
|
|
52
|
+
* remove the managed block entirely while keeping the user's content.
|
|
53
|
+
*
|
|
54
|
+
* Returns true when the file changed on disk.
|
|
55
|
+
*/
|
|
56
|
+
export async function writeManagedBlock(
|
|
57
|
+
filePath: string,
|
|
58
|
+
block: string,
|
|
59
|
+
markers: ArtifactMarkers
|
|
60
|
+
): Promise<boolean> {
|
|
61
|
+
const existing = (await pathExists(filePath)) ? await readFile(filePath, 'utf8') : '';
|
|
62
|
+
const base = stripManagedBlock(existing, markers);
|
|
63
|
+
const wrapped = block.trim() ? `${markers.start}\n${block.trim()}\n${markers.end}` : '';
|
|
64
|
+
const next = wrapped
|
|
65
|
+
? base
|
|
66
|
+
? `${base}\n\n${wrapped}\n`
|
|
67
|
+
: `${wrapped}\n`
|
|
68
|
+
: base
|
|
69
|
+
? `${base}\n`
|
|
70
|
+
: '';
|
|
71
|
+
|
|
72
|
+
if (next === existing) return false;
|
|
73
|
+
await mkdir(join(filePath, '..'), { recursive: true });
|
|
74
|
+
await writeFile(filePath, next, 'utf8');
|
|
75
|
+
return true;
|
|
76
|
+
}
|