@myrialabs/clopen 0.4.44 → 0.4.45
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/project/bridge.ts +218 -0
- package/backend/artifacts/project/edit.ts +243 -0
- package/backend/artifacts/project/index.ts +38 -0
- package/backend/artifacts/project/project.test.ts +181 -0
- package/backend/artifacts/project/scan.ts +368 -0
- package/backend/artifacts/project/sources.ts +100 -0
- package/backend/artifacts/sync.ts +1 -1
- package/backend/auth/permissions.ts +15 -0
- package/backend/chat/stream-manager.ts +20 -3
- package/backend/database/migrations/083_create_project_mcp_trust.ts +32 -0
- package/backend/database/migrations/index.ts +7 -0
- package/backend/database/queries/index.ts +2 -0
- package/backend/database/queries/project-mcp-trust-queries.ts +43 -0
- package/backend/engine/adapters/claude/stream.ts +27 -1
- package/backend/engine/adapters/cline/mcp-tools.ts +26 -4
- package/backend/engine/adapters/cline/stream.ts +20 -6
- package/backend/engine/adapters/codex/stream.ts +21 -4
- package/backend/engine/adapters/copilot/stream.ts +6 -3
- package/backend/engine/adapters/cursor/stream.ts +19 -8
- package/backend/engine/adapters/opencode/server.ts +14 -4
- package/backend/engine/adapters/opencode/stream.ts +18 -3
- package/backend/engine/adapters/pi/mcp-tools.ts +26 -4
- package/backend/engine/adapters/pi/stream.ts +35 -3
- package/backend/engine/adapters/qwen/stream.ts +8 -0
- package/backend/engine/artifact-sync.ts +12 -5
- package/backend/files/file-watcher.test.ts +77 -0
- package/backend/files/file-watcher.ts +92 -60
- package/backend/files/watch-ignore.test.ts +182 -0
- package/backend/files/watch-ignore.ts +244 -0
- package/backend/git/git-executor.ts +14 -4
- package/backend/index.ts +11 -1
- package/backend/instructions/service.ts +5 -3
- package/backend/instructions/sync.ts +10 -27
- package/backend/mcp/external/config.ts +65 -23
- package/backend/mcp/external/project.ts +124 -0
- package/backend/mcp/external/proxy.ts +65 -11
- package/backend/mcp/index.ts +14 -9
- package/backend/mcp/internal/remote-server.ts +11 -1
- package/backend/skills/marketplace.ts +1 -1
- package/backend/snapshot/blob-store.ts +9 -5
- package/backend/snapshot/git-attribution.test.ts +42 -0
- package/backend/snapshot/git-attribution.ts +306 -0
- package/backend/snapshot/gitignore.test.ts +62 -0
- package/backend/snapshot/gitignore.ts +158 -78
- package/backend/snapshot/snapshot-service.test.ts +270 -0
- package/backend/snapshot/snapshot-service.ts +412 -136
- package/backend/snapshot/turn-activity.test.ts +52 -0
- package/backend/snapshot/turn-activity.ts +83 -0
- package/backend/snapshot/turn-changes.test.ts +58 -1
- package/backend/snapshot/turn-changes.ts +66 -0
- package/backend/worktrees/tree.ts +1 -1
- package/backend/ws/chat/composer.ts +504 -0
- package/backend/ws/chat/index.ts +3 -1
- package/backend/ws/chat/stream.ts +252 -440
- package/backend/ws/index.ts +4 -0
- package/backend/ws/project-artifacts/index.ts +236 -0
- package/backend/ws/snapshot/changes.ts +66 -31
- package/dist/assets/{index-BWyhqUi5.js → index-Am-rJRxA.js} +1 -1
- package/dist/assets/{index-DX5OwLOc.js → index-D-Ad1N96.js} +1 -1
- package/dist/assets/main--PLCDxSy.css +1 -0
- package/dist/assets/main-DelPm2Xt.js +1239 -0
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/shared/types/stores/settings.ts +5 -0
- package/shared/types/unified/message.ts +2 -0
- package/dist/assets/main-DOkwqXRU.js +0 -1215
- package/dist/assets/main-DzCY0n-j.css +0 -1
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Project bridge — per stream, delivers the repository's artifacts to an engine
|
|
3
|
+
* that does not read them on its own.
|
|
4
|
+
*
|
|
5
|
+
* What gets bridged comes straight from {@link scanProject}'s coverage: an item
|
|
6
|
+
* marked `bridged` for this engine. Everything is delivered through per-query
|
|
7
|
+
* channels only — prompt text, SDK options, a Clopen-owned plugin dir — and
|
|
8
|
+
* NEVER by writing into the repository or into an engine's shared global dir.
|
|
9
|
+
* Two sessions on two projects therefore can't see each other's artifacts, and
|
|
10
|
+
* the working tree never changes because a chat started.
|
|
11
|
+
*
|
|
12
|
+
* Instructions have two project layers:
|
|
13
|
+
* - `AGENTS.md` (committed, shared with every tool) — bridged to the engines
|
|
14
|
+
* that don't read it: Claude (unless `CLAUDE.md` imports it), Cline, Cursor.
|
|
15
|
+
* - The Clopen-only block (Settings → Instructions → This project, stored in
|
|
16
|
+
* the database, never committed) — delivered to every engine.
|
|
17
|
+
*
|
|
18
|
+
* Never throws: a repo Clopen can't read yields an empty bridge.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import { join } from 'path';
|
|
22
|
+
import { createHash } from 'node:crypto';
|
|
23
|
+
import { mkdir, readdir, rm, writeFile, readFile, realpath } from 'node:fs/promises';
|
|
24
|
+
import { instructionQueries } from '$backend/database/queries';
|
|
25
|
+
import { getClopenDir } from '$backend/utils/paths';
|
|
26
|
+
import { debug } from '$shared/utils/logger';
|
|
27
|
+
import type { ArtifactEngine } from '../types';
|
|
28
|
+
import { parseDoc } from '../frontmatter';
|
|
29
|
+
import { mirrorFolder } from '../sync';
|
|
30
|
+
import { scanProject, readSmallFile, type ProjectItem } from './scan';
|
|
31
|
+
|
|
32
|
+
export interface BridgedSkill {
|
|
33
|
+
slug: string;
|
|
34
|
+
name: string;
|
|
35
|
+
description: string;
|
|
36
|
+
/** Absolute skill folder. */
|
|
37
|
+
dir: string;
|
|
38
|
+
/** Absolute `SKILL.md`. */
|
|
39
|
+
skillMd: string;
|
|
40
|
+
/** Where it lives in the repo, for the preamble. */
|
|
41
|
+
path: string;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface BridgedSubagent {
|
|
45
|
+
slug: string;
|
|
46
|
+
name: string;
|
|
47
|
+
description: string;
|
|
48
|
+
/** The subagent's instructions (document body). */
|
|
49
|
+
prompt: string;
|
|
50
|
+
tools?: string[];
|
|
51
|
+
model?: string;
|
|
52
|
+
path: string;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export interface ProjectBridge {
|
|
56
|
+
engine: ArtifactEngine;
|
|
57
|
+
root: string;
|
|
58
|
+
skills: BridgedSkill[];
|
|
59
|
+
subagents: BridgedSubagent[];
|
|
60
|
+
/** `AGENTS.md` content, when this engine doesn't read the file itself. */
|
|
61
|
+
agentsMd: string | null;
|
|
62
|
+
/** The Clopen-only project instruction block (database layer). */
|
|
63
|
+
clopenInstructions: string | null;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Cap on bridged `AGENTS.md` so a huge file can't swamp every prompt. */
|
|
67
|
+
const MAX_AGENTS_MD_CHARS = 64 * 1024;
|
|
68
|
+
|
|
69
|
+
export function emptyBridge(engine: ArtifactEngine, root = ''): ProjectBridge {
|
|
70
|
+
return { engine, root, skills: [], subagents: [], agentsMd: null, clopenInstructions: null };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function splitList(value: string | undefined): string[] | undefined {
|
|
74
|
+
if (!value) return undefined;
|
|
75
|
+
const list = value.replace(/^\[|\]$/g, '').split(/[\s,]+/).map(t => t.replace(/^["']|["']$/g, '').trim()).filter(Boolean);
|
|
76
|
+
return list.length ? list : undefined;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async function toSubagent(item: ProjectItem): Promise<BridgedSubagent | null> {
|
|
80
|
+
const raw = await readSmallFile(item.entryFile);
|
|
81
|
+
if (raw == null) return null;
|
|
82
|
+
const { frontmatter, body } = parseDoc(raw);
|
|
83
|
+
return {
|
|
84
|
+
slug: item.slug,
|
|
85
|
+
name: item.name,
|
|
86
|
+
description: item.description,
|
|
87
|
+
prompt: body.trim() || `You are the ${item.name} subagent. ${item.description}`,
|
|
88
|
+
tools: splitList(frontmatter.tools),
|
|
89
|
+
model: frontmatter.model || undefined,
|
|
90
|
+
path: item.path
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Resolve what Clopen must deliver to `engine` for the repository at `root`.
|
|
96
|
+
* `projectId` adds the Clopen-only instruction layer; omit it for a bare path.
|
|
97
|
+
*/
|
|
98
|
+
export async function resolveProjectBridge(engine: ArtifactEngine, root: string, projectId?: string | null): Promise<ProjectBridge> {
|
|
99
|
+
const bridge = emptyBridge(engine, root);
|
|
100
|
+
try {
|
|
101
|
+
if (projectId) {
|
|
102
|
+
const row = instructionQueries.getForProject(projectId);
|
|
103
|
+
const content = row && row.is_enabled === 1 ? row.content.trim() : '';
|
|
104
|
+
bridge.clopenInstructions = content || null;
|
|
105
|
+
}
|
|
106
|
+
if (!root) return bridge;
|
|
107
|
+
|
|
108
|
+
const scan = await scanProject(root);
|
|
109
|
+
bridge.skills = scan.skills
|
|
110
|
+
.filter(i => i.coverage[engine] === 'bridged')
|
|
111
|
+
.map(i => ({ slug: i.slug, name: i.name, description: i.description, dir: join(root, i.path), skillMd: i.entryFile, path: i.path }));
|
|
112
|
+
for (const item of scan.subagents.filter(i => i.coverage[engine] === 'bridged')) {
|
|
113
|
+
const sub = await toSubagent(item);
|
|
114
|
+
if (sub) bridge.subagents.push(sub);
|
|
115
|
+
}
|
|
116
|
+
const agentsMd = scan.instructions.find(f => f.sourceId === 'agents-md');
|
|
117
|
+
if (agentsMd?.coverage[engine] === 'bridged') {
|
|
118
|
+
const content = (await readSmallFile(join(root, 'AGENTS.md')))?.trim();
|
|
119
|
+
if (content) {
|
|
120
|
+
bridge.agentsMd = content.length > MAX_AGENTS_MD_CHARS
|
|
121
|
+
? `${content.slice(0, MAX_AGENTS_MD_CHARS)}\n\n[AGENTS.md truncated — read the file for the rest]`
|
|
122
|
+
: content;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
} catch (error) {
|
|
126
|
+
debug.warn('artifacts', `⚠️ Project bridge for ${engine} at ${root} failed (continuing without):`, error);
|
|
127
|
+
}
|
|
128
|
+
return bridge;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export interface PromptContextParts {
|
|
132
|
+
skills?: boolean;
|
|
133
|
+
subagents?: boolean;
|
|
134
|
+
instructions?: boolean;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* The bridged artifacts as prompt text — for engines whose only per-session
|
|
139
|
+
* channel is the prompt (or an appended system prompt). Choose the parts the
|
|
140
|
+
* engine can't receive through a better channel. Returns '' when empty.
|
|
141
|
+
*/
|
|
142
|
+
export function buildProjectPromptContext(bridge: ProjectBridge, parts: PromptContextParts = { skills: true, subagents: true, instructions: true }): string {
|
|
143
|
+
const sections: string[] = [];
|
|
144
|
+
if (parts.instructions && bridge.agentsMd) {
|
|
145
|
+
sections.push(['# Project Instructions (AGENTS.md)', '', 'Standing instructions from this repository\'s AGENTS.md:', '', bridge.agentsMd].join('\n'));
|
|
146
|
+
}
|
|
147
|
+
if (parts.instructions && bridge.clopenInstructions) {
|
|
148
|
+
sections.push(['# Project Instructions', '', 'Always-on directives for this project:', '', bridge.clopenInstructions].join('\n'));
|
|
149
|
+
}
|
|
150
|
+
if (parts.skills && bridge.skills.length > 0) {
|
|
151
|
+
const lines = [
|
|
152
|
+
'# Project Skills',
|
|
153
|
+
'',
|
|
154
|
+
'This repository provides the following skills. When the user\'s request matches a',
|
|
155
|
+
'skill\'s purpose, READ its SKILL.md with your file-reading tool before proceeding.',
|
|
156
|
+
'Only load a skill when it is relevant.',
|
|
157
|
+
''
|
|
158
|
+
];
|
|
159
|
+
for (const skill of bridge.skills) {
|
|
160
|
+
lines.push(`- **${skill.name}** — ${skill.description}`);
|
|
161
|
+
lines.push(` Instructions: ${skill.skillMd}`);
|
|
162
|
+
}
|
|
163
|
+
sections.push(lines.join('\n'));
|
|
164
|
+
}
|
|
165
|
+
if (parts.subagents && bridge.subagents.length > 0) {
|
|
166
|
+
const lines = ['# Project Subagents', '', 'Specialized agents from this repository you can delegate matching tasks to:', ''];
|
|
167
|
+
for (const s of bridge.subagents) lines.push(`- **${s.name}** (${s.slug}) — ${s.description}`);
|
|
168
|
+
sections.push(lines.join('\n'));
|
|
169
|
+
}
|
|
170
|
+
return sections.join('\n\n');
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
174
|
+
// Claude — skills through a Clopen-owned local plugin
|
|
175
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
176
|
+
|
|
177
|
+
/** Plugin name Claude namespaces bridged skills under (`project:<skill>`). */
|
|
178
|
+
const CLAUDE_PLUGIN_NAME = 'project';
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Materialize the bridged skills as a local Claude plugin OUTSIDE the repo and
|
|
182
|
+
* return its path, or null when there is nothing to bridge.
|
|
183
|
+
*
|
|
184
|
+
* A plugin is the only per-query way to hand Claude extra skills: its native
|
|
185
|
+
* `skills/` dirs are either the repo (must not be written) or the isolated
|
|
186
|
+
* config dir (shared by every concurrent session, so one project's skills would
|
|
187
|
+
* leak into another's). Skill folders are COPIED, not symlinked — Claude skips
|
|
188
|
+
* symlinked project entries for safety — and re-copied only when changed
|
|
189
|
+
* (same freshness check the global skill mirror uses).
|
|
190
|
+
*/
|
|
191
|
+
export async function ensureClaudeProjectPlugin(bridge: ProjectBridge): Promise<string | null> {
|
|
192
|
+
if (bridge.skills.length === 0) return null;
|
|
193
|
+
try {
|
|
194
|
+
const key = createHash('sha1').update(bridge.root).digest('hex').slice(0, 16);
|
|
195
|
+
const pluginDir = join(getClopenDir(), 'project-bridge', 'claude', key);
|
|
196
|
+
const manifestDir = join(pluginDir, '.claude-plugin');
|
|
197
|
+
const skillsDir = join(pluginDir, 'skills');
|
|
198
|
+
await mkdir(manifestDir, { recursive: true });
|
|
199
|
+
await mkdir(skillsDir, { recursive: true });
|
|
200
|
+
|
|
201
|
+
const manifest = `${JSON.stringify({ name: CLAUDE_PLUGIN_NAME, description: `Skills from ${bridge.root}`, version: '1.0.0' }, null, 2)}\n`;
|
|
202
|
+
const manifestPath = join(manifestDir, 'plugin.json');
|
|
203
|
+
if ((await readFile(manifestPath, 'utf8').catch(() => '')) !== manifest) await writeFile(manifestPath, manifest, 'utf8');
|
|
204
|
+
|
|
205
|
+
const wanted = new Set(bridge.skills.map(s => s.slug));
|
|
206
|
+
for (const entry of await readdir(skillsDir)) {
|
|
207
|
+
if (!wanted.has(entry)) await rm(join(skillsDir, entry), { recursive: true, force: true });
|
|
208
|
+
}
|
|
209
|
+
for (const skill of bridge.skills) {
|
|
210
|
+
// Resolve a symlinked skill folder first so the copy holds real files.
|
|
211
|
+
await mirrorFolder(await realpath(skill.dir), skillsDir, skill.slug);
|
|
212
|
+
}
|
|
213
|
+
return pluginDir;
|
|
214
|
+
} catch (error) {
|
|
215
|
+
debug.warn('artifacts', '⚠️ Could not build the Claude project-skills plugin (continuing without):', error);
|
|
216
|
+
return null;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Edit in place — the only code that writes project artifacts into a repository.
|
|
3
|
+
*
|
|
4
|
+
* Every write lands in a location from {@link PROJECT_WRITE_PATHS}:
|
|
5
|
+
* - `.agents/skills/<slug>/SKILL.md`
|
|
6
|
+
* - `.agents/agents/<slug>.md`
|
|
7
|
+
* - `.agents/mcp.json`
|
|
8
|
+
* - root `AGENTS.md`, written exactly as edited
|
|
9
|
+
*
|
|
10
|
+
* Paths are built from the repo root plus a validated slug, never from a
|
|
11
|
+
* caller-supplied path. The one caller-supplied path — the source of a "copy to
|
|
12
|
+
* .agents" or a read — is confined to the repo root before use.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { join, resolve, sep, basename, isAbsolute } from 'path';
|
|
16
|
+
import { mkdir, readFile, writeFile, rm, rename, cp, stat, realpath, lstat } from 'node:fs/promises';
|
|
17
|
+
import { parseSkillMd, serializeSkillMd, type ParsedSkill } from '$backend/skills/spec';
|
|
18
|
+
import { debug } from '$shared/utils/logger';
|
|
19
|
+
import { parseDoc, serializeDoc } from '../frontmatter';
|
|
20
|
+
import { slugify, isValidSlug } from '../slug';
|
|
21
|
+
import { PROJECT_WRITE_PATHS } from './sources';
|
|
22
|
+
import { parseProjectMcpJson, hashContent, readSmallFile, subagentSlugFromFile } from './scan';
|
|
23
|
+
|
|
24
|
+
async function exists(path: string): Promise<boolean> {
|
|
25
|
+
try { await lstat(path); return true; } catch { return false; }
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Resolve a repo-relative path, refusing `..` segments and absolute paths.
|
|
30
|
+
*
|
|
31
|
+
* The path itself must sit in the repo; what it points AT may not — a skill
|
|
32
|
+
* folder symlinked to a shared checkout is a normal setup, and the scan already
|
|
33
|
+
* follows those links. Callers limit which files they open (see
|
|
34
|
+
* {@link readProjectFile}).
|
|
35
|
+
*/
|
|
36
|
+
export async function resolveInsideRoot(root: string, relPath: string): Promise<string> {
|
|
37
|
+
if (!relPath || isAbsolute(relPath) || relPath.split(/[\\/]/).includes('..')) {
|
|
38
|
+
throw new Error(`Path must stay inside the project: ${relPath}`);
|
|
39
|
+
}
|
|
40
|
+
const abs = resolve(root, relPath);
|
|
41
|
+
if (!abs.startsWith(resolve(root) + sep)) throw new Error(`Path must stay inside the project: ${relPath}`);
|
|
42
|
+
if (!(await exists(abs))) throw new Error(`Not found: ${relPath}`);
|
|
43
|
+
return abs;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Read an artifact document the scan reported (skill `SKILL.md`, subagent,
|
|
48
|
+
* instruction file, MCP config). Only Markdown/JSON/rule text is served, so a
|
|
49
|
+
* committed symlink can't turn this into a general file reader.
|
|
50
|
+
*/
|
|
51
|
+
export async function readProjectFile(root: string, relPath: string): Promise<string> {
|
|
52
|
+
let abs = await resolveInsideRoot(root, relPath);
|
|
53
|
+
if ((await stat(abs)).isDirectory()) abs = join(abs, 'SKILL.md');
|
|
54
|
+
if (!/\.(md|mdc|json|txt)$/i.test(abs) && basename(abs) !== '.clinerules') {
|
|
55
|
+
throw new Error(`Not an artifact document: ${relPath}`);
|
|
56
|
+
}
|
|
57
|
+
const raw = await readSmallFile(abs);
|
|
58
|
+
if (raw == null) throw new Error(`Cannot read ${relPath} (missing or larger than 512 KB)`);
|
|
59
|
+
return raw;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function requireSlug(input: string): string {
|
|
63
|
+
const slug = slugify(input);
|
|
64
|
+
if (!isValidSlug(slug)) throw new Error(`"${input}" does not make a valid name (lowercase letters, digits, hyphens)`);
|
|
65
|
+
return slug;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
69
|
+
// Skills — `.agents/skills/<slug>/SKILL.md`
|
|
70
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
71
|
+
|
|
72
|
+
export interface ProjectSkillInput {
|
|
73
|
+
/** Present when editing; a different `name` renames the folder. */
|
|
74
|
+
originalSlug?: string;
|
|
75
|
+
name: string;
|
|
76
|
+
description: string;
|
|
77
|
+
body: string;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export async function saveProjectSkill(root: string, input: ProjectSkillInput): Promise<{ slug: string; path: string }> {
|
|
81
|
+
const slug = requireSlug(input.name);
|
|
82
|
+
if (!input.description.trim()) throw new Error('A description is required — it is how the agent decides when to use the skill');
|
|
83
|
+
const base = join(root, PROJECT_WRITE_PATHS.skills);
|
|
84
|
+
const dir = join(base, slug);
|
|
85
|
+
|
|
86
|
+
let existing: ParsedSkill | null = null;
|
|
87
|
+
if (input.originalSlug) {
|
|
88
|
+
if (!isValidSlug(input.originalSlug)) throw new Error('Invalid skill');
|
|
89
|
+
const originalDir = join(base, input.originalSlug);
|
|
90
|
+
const raw = await readSmallFile(join(originalDir, 'SKILL.md'));
|
|
91
|
+
if (raw != null) { try { existing = parseSkillMd(raw); } catch { existing = null; } }
|
|
92
|
+
if (input.originalSlug !== slug) {
|
|
93
|
+
if (await exists(dir)) throw new Error(`A skill named "${slug}" already exists in ${PROJECT_WRITE_PATHS.skills}`);
|
|
94
|
+
if (await exists(originalDir)) await rename(originalDir, dir);
|
|
95
|
+
}
|
|
96
|
+
} else if (await exists(dir)) {
|
|
97
|
+
throw new Error(`A skill named "${slug}" already exists in ${PROJECT_WRITE_PATHS.skills}`);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// Keep every frontmatter field we don't edit here (license, allowed-tools,
|
|
101
|
+
// metadata, …) so saving from Settings never strips what another tool wrote.
|
|
102
|
+
const doc: ParsedSkill = {
|
|
103
|
+
frontmatter: { ...(existing?.frontmatter ?? { extra: {} }), name: slug, description: input.description.trim() },
|
|
104
|
+
body: input.body
|
|
105
|
+
};
|
|
106
|
+
await mkdir(dir, { recursive: true });
|
|
107
|
+
await writeFile(join(dir, 'SKILL.md'), serializeSkillMd(doc), 'utf8');
|
|
108
|
+
debug.log('artifacts', `📝 Project skill saved: ${join(PROJECT_WRITE_PATHS.skills, slug)}`);
|
|
109
|
+
return { slug, path: `${PROJECT_WRITE_PATHS.skills}/${slug}` };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export async function deleteProjectSkill(root: string, slug: string): Promise<void> {
|
|
113
|
+
if (!isValidSlug(slug)) throw new Error('Invalid skill');
|
|
114
|
+
// `rm` on a symlinked folder removes the link, never the shared target.
|
|
115
|
+
await rm(join(root, PROJECT_WRITE_PATHS.skills, slug), { recursive: true, force: true });
|
|
116
|
+
debug.log('artifacts', `🗑️ Project skill deleted: ${slug}`);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
120
|
+
// Subagents — `.agents/agents/<slug>.md`
|
|
121
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
122
|
+
|
|
123
|
+
export interface ProjectSubagentInput {
|
|
124
|
+
originalSlug?: string;
|
|
125
|
+
name: string;
|
|
126
|
+
description: string;
|
|
127
|
+
tools?: string;
|
|
128
|
+
model?: string;
|
|
129
|
+
body: string;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export async function saveProjectSubagent(root: string, input: ProjectSubagentInput): Promise<{ slug: string; path: string }> {
|
|
133
|
+
const slug = requireSlug(input.name);
|
|
134
|
+
if (!input.description.trim()) throw new Error('A description is required — it is how the agent decides when to delegate');
|
|
135
|
+
const base = join(root, PROJECT_WRITE_PATHS.subagents);
|
|
136
|
+
const file = join(base, `${slug}.md`);
|
|
137
|
+
|
|
138
|
+
let frontmatter: Record<string, string> = {};
|
|
139
|
+
if (input.originalSlug) {
|
|
140
|
+
if (!isValidSlug(input.originalSlug)) throw new Error('Invalid subagent');
|
|
141
|
+
const originalFile = join(base, `${input.originalSlug}.md`);
|
|
142
|
+
const raw = await readSmallFile(originalFile);
|
|
143
|
+
if (raw != null) frontmatter = parseDoc(raw).frontmatter;
|
|
144
|
+
if (input.originalSlug !== slug) {
|
|
145
|
+
if (await exists(file)) throw new Error(`A subagent named "${slug}" already exists in ${PROJECT_WRITE_PATHS.subagents}`);
|
|
146
|
+
await rm(originalFile, { force: true });
|
|
147
|
+
}
|
|
148
|
+
} else if (await exists(file)) {
|
|
149
|
+
throw new Error(`A subagent named "${slug}" already exists in ${PROJECT_WRITE_PATHS.subagents}`);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const fm: Record<string, string> = { ...frontmatter, name: slug, description: input.description.trim() };
|
|
153
|
+
const tools = input.tools?.split(/[\s,]+/).map(t => t.trim()).filter(Boolean).join(', ') ?? '';
|
|
154
|
+
if (tools) fm.tools = tools; else delete fm.tools;
|
|
155
|
+
if (input.model?.trim()) fm.model = input.model.trim(); else delete fm.model;
|
|
156
|
+
|
|
157
|
+
await mkdir(base, { recursive: true });
|
|
158
|
+
await writeFile(file, serializeDoc({ frontmatter: fm, body: input.body }, ['name', 'description', 'tools', 'model']), 'utf8');
|
|
159
|
+
debug.log('artifacts', `📝 Project subagent saved: ${PROJECT_WRITE_PATHS.subagents}/${slug}.md`);
|
|
160
|
+
return { slug, path: `${PROJECT_WRITE_PATHS.subagents}/${slug}.md` };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
export async function deleteProjectSubagent(root: string, slug: string): Promise<void> {
|
|
164
|
+
if (!isValidSlug(slug)) throw new Error('Invalid subagent');
|
|
165
|
+
await rm(join(root, PROJECT_WRITE_PATHS.subagents, `${slug}.md`), { force: true });
|
|
166
|
+
debug.log('artifacts', `🗑️ Project subagent deleted: ${slug}`);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
170
|
+
// Copy an artifact from another tool's folder into `.agents/`
|
|
171
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Copy (never move) a detected skill or subagent into `.agents/`, so the one
|
|
175
|
+
* location every engine can use carries it. The original stays where it is —
|
|
176
|
+
* another tool may still depend on it.
|
|
177
|
+
*/
|
|
178
|
+
export async function copyToAgents(root: string, kind: 'skill' | 'subagent', relPath: string): Promise<{ slug: string; path: string }> {
|
|
179
|
+
const source = await resolveInsideRoot(root, relPath);
|
|
180
|
+
if (kind === 'skill') {
|
|
181
|
+
const slug = basename(source);
|
|
182
|
+
if (!isValidSlug(slug)) throw new Error(`"${slug}" is not a valid skill folder name`);
|
|
183
|
+
const dest = join(root, PROJECT_WRITE_PATHS.skills, slug);
|
|
184
|
+
if (await exists(dest)) throw new Error(`${PROJECT_WRITE_PATHS.skills}/${slug} already exists`);
|
|
185
|
+
await mkdir(join(root, PROJECT_WRITE_PATHS.skills), { recursive: true });
|
|
186
|
+
await cp(await realpath(source), dest, { recursive: true });
|
|
187
|
+
debug.log('artifacts', `📋 Copied ${relPath} → ${PROJECT_WRITE_PATHS.skills}/${slug}`);
|
|
188
|
+
return { slug, path: `${PROJECT_WRITE_PATHS.skills}/${slug}` };
|
|
189
|
+
}
|
|
190
|
+
const slug = subagentSlugFromFile(basename(source));
|
|
191
|
+
if (!slug || !isValidSlug(slug)) throw new Error(`"${basename(source)}" is not a valid subagent file name`);
|
|
192
|
+
const dest = join(root, PROJECT_WRITE_PATHS.subagents, `${slug}.md`);
|
|
193
|
+
if (await exists(dest)) throw new Error(`${PROJECT_WRITE_PATHS.subagents}/${slug}.md already exists`);
|
|
194
|
+
await mkdir(join(root, PROJECT_WRITE_PATHS.subagents), { recursive: true });
|
|
195
|
+
await writeFile(dest, await readFile(source, 'utf8'), 'utf8');
|
|
196
|
+
debug.log('artifacts', `📋 Copied ${relPath} → ${PROJECT_WRITE_PATHS.subagents}/${slug}.md`);
|
|
197
|
+
return { slug, path: `${PROJECT_WRITE_PATHS.subagents}/${slug}.md` };
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
201
|
+
// Instructions — root `AGENTS.md`, verbatim
|
|
202
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
203
|
+
|
|
204
|
+
export interface AgentsMdState {
|
|
205
|
+
exists: boolean;
|
|
206
|
+
/** The file exactly as it is on disk. */
|
|
207
|
+
content: string;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
export async function readAgentsMd(root: string): Promise<AgentsMdState> {
|
|
211
|
+
const raw = await readSmallFile(join(root, PROJECT_WRITE_PATHS.instructions));
|
|
212
|
+
if (raw == null) return { exists: false, content: '' };
|
|
213
|
+
return { exists: true, content: raw };
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** Write the file exactly as given — nothing added before or after. Empty content never creates the file. */
|
|
217
|
+
export async function saveAgentsMd(root: string, content: string): Promise<AgentsMdState> {
|
|
218
|
+
const file = join(root, PROJECT_WRITE_PATHS.instructions);
|
|
219
|
+
const current = await readAgentsMd(root);
|
|
220
|
+
if (!current.exists && !content.trim()) return current;
|
|
221
|
+
await writeFile(file, content, 'utf8');
|
|
222
|
+
debug.log('artifacts', '📝 AGENTS.md saved');
|
|
223
|
+
return readAgentsMd(root);
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
227
|
+
// MCP — `.agents/mcp.json`
|
|
228
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
229
|
+
|
|
230
|
+
/** Validate and write `.agents/mcp.json`; returns the new content hash. */
|
|
231
|
+
export async function saveProjectMcp(root: string, raw: string): Promise<string> {
|
|
232
|
+
const text = raw.trim() ? `${raw.trim()}\n` : '';
|
|
233
|
+
const file = join(root, PROJECT_WRITE_PATHS.mcp);
|
|
234
|
+
if (!text) {
|
|
235
|
+
await rm(file, { force: true });
|
|
236
|
+
return '';
|
|
237
|
+
}
|
|
238
|
+
parseProjectMcpJson(text); // throws a readable error for invalid config
|
|
239
|
+
await mkdir(join(root, '.agents'), { recursive: true });
|
|
240
|
+
await writeFile(file, text, 'utf8');
|
|
241
|
+
debug.log('artifacts', '📝 .agents/mcp.json saved');
|
|
242
|
+
return hashContent(text);
|
|
243
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Project artifacts — a repository's own skills, subagents, instructions and
|
|
3
|
+
* MCP servers (`.agents/`, `.claude/`, `AGENTS.md`, …), surfaced in Settings,
|
|
4
|
+
* delivered to the engines that don't read them natively, and edited in place.
|
|
5
|
+
*
|
|
6
|
+
* - `sources.ts` — which repo locations exist and which engines read each one
|
|
7
|
+
* - `scan.ts` — what a repo carries + per-engine coverage
|
|
8
|
+
* - `bridge.ts` — per-stream delivery of the `bridged` part
|
|
9
|
+
* - `edit.ts` — the only writer into the repository
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
export { PROJECT_SOURCES, PROJECT_WRITE_PATHS, sourcesOf, sourceById } from './sources';
|
|
13
|
+
export type { ProjectSource, ProjectArtifactKind, ProjectSourceLayout } from './sources';
|
|
14
|
+
export { scanProject, parseProjectMcpJson, hashContent } from './scan';
|
|
15
|
+
export type {
|
|
16
|
+
ProjectScan,
|
|
17
|
+
ProjectItem,
|
|
18
|
+
ProjectInstructionFile,
|
|
19
|
+
ProjectMcpFile,
|
|
20
|
+
ProjectMcpServer,
|
|
21
|
+
ProjectPermissionsFile,
|
|
22
|
+
EngineCoverage,
|
|
23
|
+
CoverageMap
|
|
24
|
+
} from './scan';
|
|
25
|
+
export { resolveProjectBridge, buildProjectPromptContext, ensureClaudeProjectPlugin, emptyBridge } from './bridge';
|
|
26
|
+
export type { ProjectBridge, BridgedSkill, BridgedSubagent, PromptContextParts } from './bridge';
|
|
27
|
+
export {
|
|
28
|
+
readProjectFile,
|
|
29
|
+
saveProjectSkill,
|
|
30
|
+
deleteProjectSkill,
|
|
31
|
+
saveProjectSubagent,
|
|
32
|
+
deleteProjectSubagent,
|
|
33
|
+
copyToAgents,
|
|
34
|
+
readAgentsMd,
|
|
35
|
+
saveAgentsMd,
|
|
36
|
+
saveProjectMcp
|
|
37
|
+
} from './edit';
|
|
38
|
+
export type { ProjectSkillInput, ProjectSubagentInput, AgentsMdState } from './edit';
|