@myrialabs/clopen 0.4.5 → 0.4.7
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/auth/permissions.ts +14 -1
- package/backend/auth/session-invalidation.test.ts +17 -21
- package/backend/auth/session-invalidation.ts +10 -11
- package/backend/database/migrations/044_create_skills_table.ts +29 -0
- package/backend/database/migrations/index.ts +7 -0
- package/backend/database/queries/index.ts +3 -1
- package/backend/database/queries/skill-queries.ts +105 -0
- package/backend/engine/adapters/claude/models.ts +46 -3
- package/backend/engine/adapters/claude/stream.ts +5 -0
- package/backend/engine/adapters/codex/credential.ts +114 -13
- package/backend/engine/adapters/codex/stream.ts +34 -8
- package/backend/engine/adapters/copilot/stream.ts +4 -0
- package/backend/engine/adapters/opencode/stream.ts +4 -0
- package/backend/engine/adapters/qwen/stream.ts +3 -0
- package/backend/engine/docs/lessons-learned.md +54 -50
- package/backend/files/file-archive.test.ts +86 -26
- package/backend/files/file-archive.ts +214 -134
- package/backend/index.ts +10 -1
- package/backend/mcp/README.md +77 -24
- package/backend/mcp/external/config.ts +82 -101
- package/backend/mcp/external/proxy.ts +202 -0
- package/backend/mcp/index.ts +4 -3
- package/backend/mcp/internal/remote-server.ts +103 -55
- package/backend/skills/index.ts +21 -0
- package/backend/skills/marketplace.ts +172 -0
- package/backend/skills/service.ts +245 -0
- package/backend/skills/spec.ts +214 -0
- package/backend/skills/store.ts +99 -0
- package/backend/skills/sync.ts +187 -0
- package/backend/terminal/index.ts +2 -5
- package/backend/terminal/ptykit.ts +64 -0
- package/backend/tunnel/tunnel-config.ts +1 -1
- package/backend/utils/ws.ts +14 -0
- package/backend/ws/files/write.ts +23 -7
- package/backend/ws/index.ts +5 -1
- package/backend/ws/projects/crud.ts +4 -4
- package/backend/ws/skills/catalog.ts +79 -0
- package/backend/ws/skills/crud.ts +123 -0
- package/backend/ws/skills/index.ts +15 -0
- package/backend/ws/system/operations.ts +23 -0
- package/backend/ws/terminal/index.ts +6 -33
- package/backend/ws/terminal/tunnel.ts +76 -0
- package/dist/assets/index-xrB3zcfA.js +1 -0
- package/dist/assets/main-BXS8bjJ6.css +1 -0
- package/dist/assets/{main-zXKH_C5O.js → main-LBI3a0n5.js} +304 -261
- package/dist/index.html +2 -2
- package/package.json +7 -11
- package/shared/constants/engines.ts +4 -4
- package/shared/utils/logger.ts +1 -0
- package/backend/terminal/helpers.ts +0 -14
- package/backend/terminal/pty-manager.ts +0 -4
- package/backend/terminal/pty-session-manager.ts +0 -349
- package/backend/terminal/stream-manager.ts +0 -300
- package/backend/ws/terminal/access.ts +0 -56
- package/backend/ws/terminal/persistence.ts +0 -145
- package/backend/ws/terminal/session.ts +0 -470
- package/backend/ws/terminal/stream.ts +0 -82
- package/dist/assets/main-gNUEJAC5.css +0 -1
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SKILL.md format — parse, serialize, validate.
|
|
3
|
+
*
|
|
4
|
+
* Implements the open Agent Skills spec (https://agentskills.io/specification):
|
|
5
|
+
* a skill is a folder whose `SKILL.md` carries YAML frontmatter (`name`,
|
|
6
|
+
* `description`, optional `license`/`compatibility`/`metadata`/`allowed-tools`)
|
|
7
|
+
* followed by a Markdown instruction body.
|
|
8
|
+
*
|
|
9
|
+
* We deliberately hand-roll a tiny frontmatter parser rather than pull in a YAML
|
|
10
|
+
* dependency: the spec's frontmatter surface is small and flat (one nested
|
|
11
|
+
* `metadata` map), and skills we author in-app are written back in this exact
|
|
12
|
+
* shape. Unknown keys are preserved verbatim so a round-trip of an imported
|
|
13
|
+
* skill never drops fields the spec tells runtimes to ignore.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
export interface SkillFrontmatter {
|
|
17
|
+
name: string;
|
|
18
|
+
description: string;
|
|
19
|
+
license?: string;
|
|
20
|
+
compatibility?: string;
|
|
21
|
+
allowedTools?: string;
|
|
22
|
+
metadata?: Record<string, string>;
|
|
23
|
+
/** Frontmatter keys we don't model, kept verbatim for lossless round-trips. */
|
|
24
|
+
extra: Record<string, string>;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface ParsedSkill {
|
|
28
|
+
frontmatter: SkillFrontmatter;
|
|
29
|
+
/** The Markdown instruction body after the frontmatter fence. */
|
|
30
|
+
body: string;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const NAME_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
34
|
+
|
|
35
|
+
/** Strip matching single/double quotes from a scalar value. */
|
|
36
|
+
function unquote(value: string): string {
|
|
37
|
+
const v = value.trim();
|
|
38
|
+
if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) {
|
|
39
|
+
return v.slice(1, -1);
|
|
40
|
+
}
|
|
41
|
+
return v;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Quote a scalar for YAML output only when it could otherwise be misparsed. */
|
|
45
|
+
function quoteIfNeeded(value: string): string {
|
|
46
|
+
if (value === '') return '""';
|
|
47
|
+
// Quote when the value contains characters that change YAML meaning, or has
|
|
48
|
+
// leading/trailing whitespace that would be trimmed on re-parse.
|
|
49
|
+
if (/[:#"'\n]|^[\s]|[\s]$|^[[{>|&*!%@`]/.test(value)) {
|
|
50
|
+
return `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
|
|
51
|
+
}
|
|
52
|
+
return value;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Split a SKILL.md into its frontmatter block and body. Returns null when the
|
|
57
|
+
* leading `---` fence is missing or unterminated.
|
|
58
|
+
*/
|
|
59
|
+
function splitFrontmatter(raw: string): { fm: string; body: string } | null {
|
|
60
|
+
const text = raw.replace(/^\uFEFF/, "");
|
|
61
|
+
const match = /^---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n([\s\S]*))?$/.exec(text);
|
|
62
|
+
if (!match) return null;
|
|
63
|
+
return { fm: match[1], body: (match[2] ?? '').replace(/^\r?\n/, '') };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Parse a SKILL.md document. Throws with a readable message on malformed input. */
|
|
67
|
+
export function parseSkillMd(raw: string): ParsedSkill {
|
|
68
|
+
const split = splitFrontmatter(raw);
|
|
69
|
+
if (!split) {
|
|
70
|
+
throw new Error('SKILL.md must start with a YAML frontmatter block fenced by --- lines.');
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const fm: SkillFrontmatter = { name: '', description: '', extra: {}, metadata: undefined };
|
|
74
|
+
const metadata: Record<string, string> = {};
|
|
75
|
+
|
|
76
|
+
const lines = split.fm.split(/\r?\n/);
|
|
77
|
+
let i = 0;
|
|
78
|
+
while (i < lines.length) {
|
|
79
|
+
const line = lines[i];
|
|
80
|
+
if (line.trim() === '' || line.trim().startsWith('#')) { i++; continue; }
|
|
81
|
+
|
|
82
|
+
// Nested `metadata:` block — indented `key: value` entries.
|
|
83
|
+
if (/^metadata:\s*$/.test(line)) {
|
|
84
|
+
i++;
|
|
85
|
+
while (i < lines.length && /^\s+\S/.test(lines[i])) {
|
|
86
|
+
const m = /^\s+([A-Za-z0-9_-]+):\s*(.*)$/.exec(lines[i]);
|
|
87
|
+
if (m) metadata[m[1]] = unquote(m[2]);
|
|
88
|
+
i++;
|
|
89
|
+
}
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const m = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(line);
|
|
94
|
+
if (!m) { i++; continue; }
|
|
95
|
+
const key = m[1];
|
|
96
|
+
let value: string;
|
|
97
|
+
|
|
98
|
+
// Block scalar (`|` literal / `>` folded, with optional chomping). The value
|
|
99
|
+
// lives on the following more-indented lines; both styles are folded to a
|
|
100
|
+
// single line so the value stays one canonical, serialize-safe string.
|
|
101
|
+
if (/^[|>][+-]?\s*$/.test(m[2].trim())) {
|
|
102
|
+
i++;
|
|
103
|
+
let baseIndent: number | null = null;
|
|
104
|
+
const collected: string[] = [];
|
|
105
|
+
while (i < lines.length) {
|
|
106
|
+
const l = lines[i];
|
|
107
|
+
if (l.trim() === '') { collected.push(''); i++; continue; }
|
|
108
|
+
const indent = l.length - l.replace(/^\s+/, '').length;
|
|
109
|
+
if (indent === 0) break; // dedented back to a top-level key
|
|
110
|
+
if (baseIndent === null) baseIndent = indent;
|
|
111
|
+
collected.push(l.slice(baseIndent));
|
|
112
|
+
i++;
|
|
113
|
+
}
|
|
114
|
+
value = collected.join(' ').replace(/\s+/g, ' ').trim();
|
|
115
|
+
} else {
|
|
116
|
+
value = unquote(m[2]);
|
|
117
|
+
i++;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
switch (key) {
|
|
121
|
+
case 'name': fm.name = value; break;
|
|
122
|
+
case 'description': fm.description = value; break;
|
|
123
|
+
case 'license': fm.license = value; break;
|
|
124
|
+
case 'compatibility': fm.compatibility = value; break;
|
|
125
|
+
case 'allowed-tools': fm.allowedTools = value; break;
|
|
126
|
+
default: fm.extra[key] = value;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
if (Object.keys(metadata).length > 0) fm.metadata = metadata;
|
|
131
|
+
return { frontmatter: fm, body: split.body };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Serialize a parsed skill back into a canonical SKILL.md document. */
|
|
135
|
+
export function serializeSkillMd(skill: ParsedSkill): string {
|
|
136
|
+
const { frontmatter: fm, body } = skill;
|
|
137
|
+
const lines: string[] = ['---'];
|
|
138
|
+
lines.push(`name: ${quoteIfNeeded(fm.name)}`);
|
|
139
|
+
lines.push(`description: ${quoteIfNeeded(fm.description)}`);
|
|
140
|
+
if (fm.license) lines.push(`license: ${quoteIfNeeded(fm.license)}`);
|
|
141
|
+
if (fm.compatibility) lines.push(`compatibility: ${quoteIfNeeded(fm.compatibility)}`);
|
|
142
|
+
if (fm.allowedTools) lines.push(`allowed-tools: ${quoteIfNeeded(fm.allowedTools)}`);
|
|
143
|
+
for (const [k, v] of Object.entries(fm.extra)) lines.push(`${k}: ${quoteIfNeeded(v)}`);
|
|
144
|
+
if (fm.metadata && Object.keys(fm.metadata).length > 0) {
|
|
145
|
+
lines.push('metadata:');
|
|
146
|
+
for (const [k, v] of Object.entries(fm.metadata)) lines.push(` ${k}: ${quoteIfNeeded(v)}`);
|
|
147
|
+
}
|
|
148
|
+
lines.push('---');
|
|
149
|
+
const trimmedBody = body.replace(/^\s+/, '').replace(/\s+$/, '');
|
|
150
|
+
return `${lines.join('\n')}\n\n${trimmedBody}\n`;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export interface SkillValidationResult {
|
|
154
|
+
valid: boolean;
|
|
155
|
+
errors: string[];
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Validate frontmatter against the spec. `expectedName` (when given) enforces
|
|
160
|
+
* the spec rule that `name` must match the parent folder — we pass the slug.
|
|
161
|
+
*/
|
|
162
|
+
export function validateFrontmatter(fm: SkillFrontmatter, expectedName?: string): SkillValidationResult {
|
|
163
|
+
const errors: string[] = [];
|
|
164
|
+
|
|
165
|
+
if (!fm.name) {
|
|
166
|
+
errors.push('`name` is required.');
|
|
167
|
+
} else {
|
|
168
|
+
if (fm.name.length > 64) errors.push('`name` must be at most 64 characters.');
|
|
169
|
+
if (!NAME_RE.test(fm.name)) {
|
|
170
|
+
errors.push('`name` may only contain lowercase letters, numbers, and single hyphens (no leading, trailing, or consecutive hyphens).');
|
|
171
|
+
}
|
|
172
|
+
if (expectedName && fm.name !== expectedName) {
|
|
173
|
+
errors.push(`\`name\` (${fm.name}) must match the skill folder name (${expectedName}).`);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
if (!fm.description || !fm.description.trim()) {
|
|
178
|
+
errors.push('`description` is required and must describe what the skill does and when to use it.');
|
|
179
|
+
} else if (fm.description.length > 1024) {
|
|
180
|
+
errors.push('`description` must be at most 1024 characters.');
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
if (fm.compatibility && fm.compatibility.length > 500) {
|
|
184
|
+
errors.push('`compatibility` must be at most 500 characters.');
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// Angle brackets in frontmatter can inject unintended system-prompt content.
|
|
188
|
+
for (const [label, value] of [
|
|
189
|
+
['name', fm.name],
|
|
190
|
+
['description', fm.description],
|
|
191
|
+
['license', fm.license],
|
|
192
|
+
['compatibility', fm.compatibility]
|
|
193
|
+
] as const) {
|
|
194
|
+
if (value && /[<>]/.test(value)) errors.push(`\`${label}\` must not contain angle brackets (< or >).`);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
return { valid: errors.length === 0, errors };
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Normalise an arbitrary string into a spec-valid skill slug: lowercase, ASCII
|
|
202
|
+
* alphanumerics and single hyphens, no leading/trailing hyphen, capped at 64.
|
|
203
|
+
*/
|
|
204
|
+
export function slugifySkillName(input: string): string {
|
|
205
|
+
const slug = input
|
|
206
|
+
.toLowerCase()
|
|
207
|
+
.normalize('NFKD')
|
|
208
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
209
|
+
.replace(/^-+|-+$/g, '')
|
|
210
|
+
.replace(/-{2,}/g, '-')
|
|
211
|
+
.slice(0, 64)
|
|
212
|
+
.replace(/-+$/g, '');
|
|
213
|
+
return slug || 'skill';
|
|
214
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Canonical skill store — the single source of truth on disk.
|
|
3
|
+
*
|
|
4
|
+
* Every managed skill lives in its own folder under `{clopenDir}/skills/<slug>/`
|
|
5
|
+
* with a `SKILL.md` (and optionally bundled `scripts/`, `references/`,
|
|
6
|
+
* `assets/`). This is engine-agnostic: the `syncSkills` layer mirrors enabled
|
|
7
|
+
* skills from here into each engine's native location (or injects a synthetic
|
|
8
|
+
* preamble) at stream start. The DB (`skills` table) only tracks metadata and
|
|
9
|
+
* the enable/disable toggle.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { join } from 'path';
|
|
13
|
+
import { mkdir, readdir, rm, stat, writeFile, readFile, cp } from 'node:fs/promises';
|
|
14
|
+
import { getClopenDir } from '$backend/utils/paths';
|
|
15
|
+
import { debug } from '$shared/utils/logger';
|
|
16
|
+
|
|
17
|
+
/** Root of the canonical store: `{clopenDir}/skills`. */
|
|
18
|
+
export function getSkillsRootDir(): string {
|
|
19
|
+
return join(getClopenDir(), 'skills');
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Absolute path to a single skill's folder. */
|
|
23
|
+
export function getSkillDir(slug: string): string {
|
|
24
|
+
return join(getSkillsRootDir(), slug);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Absolute path to a skill's SKILL.md. */
|
|
28
|
+
export function getSkillMdPath(slug: string): string {
|
|
29
|
+
return join(getSkillDir(slug), 'SKILL.md');
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async function pathExists(path: string): Promise<boolean> {
|
|
33
|
+
try {
|
|
34
|
+
await stat(path);
|
|
35
|
+
return true;
|
|
36
|
+
} catch {
|
|
37
|
+
return false;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Whether a skill folder exists on disk. */
|
|
42
|
+
export function skillDirExists(slug: string): Promise<boolean> {
|
|
43
|
+
return pathExists(getSkillDir(slug));
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Read a skill's SKILL.md content, or null when the file is absent. */
|
|
47
|
+
export async function readSkillMd(slug: string): Promise<string | null> {
|
|
48
|
+
const path = getSkillMdPath(slug);
|
|
49
|
+
if (!(await pathExists(path))) return null;
|
|
50
|
+
return readFile(path, 'utf8');
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Create or overwrite a skill's SKILL.md (creating the folder as needed). */
|
|
54
|
+
export async function writeSkillMd(slug: string, content: string): Promise<void> {
|
|
55
|
+
const dir = getSkillDir(slug);
|
|
56
|
+
await mkdir(dir, { recursive: true });
|
|
57
|
+
await writeFile(getSkillMdPath(slug), content, 'utf8');
|
|
58
|
+
debug.log('skills', `💾 Wrote SKILL.md for ${slug}`);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Write an additional bundled file (e.g. `scripts/run.py`) relative to the
|
|
63
|
+
* skill folder. The relative path is sanitised to stay inside the folder.
|
|
64
|
+
*/
|
|
65
|
+
export async function writeSkillResource(slug: string, relativePath: string, content: string | Uint8Array): Promise<void> {
|
|
66
|
+
const safeRel = relativePath.replace(/\\/g, '/').replace(/(^|\/)\.\.(\/|$)/g, '/').replace(/^\/+/, '');
|
|
67
|
+
if (!safeRel || safeRel === 'SKILL.md') return;
|
|
68
|
+
const dest = join(getSkillDir(slug), safeRel);
|
|
69
|
+
await mkdir(join(dest, '..'), { recursive: true });
|
|
70
|
+
await writeFile(dest, content);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Permanently delete a skill folder and everything in it. */
|
|
74
|
+
export async function deleteSkillDir(slug: string): Promise<void> {
|
|
75
|
+
await rm(getSkillDir(slug), { recursive: true, force: true });
|
|
76
|
+
debug.log('skills', `🗑️ Removed skill folder ${slug}`);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** List skill folder names that physically exist in the canonical store. */
|
|
80
|
+
export async function listSkillSlugsOnDisk(): Promise<string[]> {
|
|
81
|
+
const root = getSkillsRootDir();
|
|
82
|
+
if (!(await pathExists(root))) return [];
|
|
83
|
+
const entries = await readdir(root, { withFileTypes: true });
|
|
84
|
+
return entries.filter(e => e.isDirectory() && !e.name.startsWith('.')).map(e => e.name);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Copy a skill folder from the canonical store into a destination skills
|
|
89
|
+
* directory (used by the native-engine sync). Removes any stale copy first so
|
|
90
|
+
* renames/edits never leave orphaned files behind.
|
|
91
|
+
*/
|
|
92
|
+
export async function copySkillInto(slug: string, destSkillsDir: string): Promise<void> {
|
|
93
|
+
const src = getSkillDir(slug);
|
|
94
|
+
if (!(await pathExists(src))) return;
|
|
95
|
+
const dest = join(destSkillsDir, slug);
|
|
96
|
+
await rm(dest, { recursive: true, force: true });
|
|
97
|
+
await mkdir(destSkillsDir, { recursive: true });
|
|
98
|
+
await cp(src, dest, { recursive: true });
|
|
99
|
+
}
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Engine sync — materialize enabled skills into the shape each engine consumes.
|
|
3
|
+
*
|
|
4
|
+
* Skills are an open standard, but engines surface them differently:
|
|
5
|
+
* - NATIVE (Claude, Qwen, Copilot): read a real skills directory and do their
|
|
6
|
+
* own progressive disclosure. We mirror each enabled skill folder there.
|
|
7
|
+
* Claude's dir is inside its isolated CLAUDE_CONFIG_DIR; Qwen and Copilot
|
|
8
|
+
* resolve theirs from $HOME (`~/.qwen/skills`, `~/.copilot/skills`) with no
|
|
9
|
+
* relocation env, so for those we manage the user's real global skills dir —
|
|
10
|
+
* touching only the slugs we own, never the user's own skills.
|
|
11
|
+
* - SYNTHETIC (Codex, OpenCode): no native skills concept, so we emit a
|
|
12
|
+
* "skills preamble" — name + description + the absolute path to each skill's
|
|
13
|
+
* SKILL.md — into a managed, marker-delimited block of the engine's global
|
|
14
|
+
* instructions file (inside its isolated home). The engine reads the body on
|
|
15
|
+
* demand with its own file tool, emulating progressive disclosure.
|
|
16
|
+
*
|
|
17
|
+
* Sync is wrapped so a failure degrades gracefully — a stream never breaks
|
|
18
|
+
* because skills couldn't sync.
|
|
19
|
+
*
|
|
20
|
+
* NOTE: the synthetic target paths (Codex/OpenCode) follow each engine's
|
|
21
|
+
* documented global-memory convention but are best-effort; if an engine ignores
|
|
22
|
+
* the path, its skills simply don't surface (no error, no data loss) until the
|
|
23
|
+
* mapping is verified against that engine.
|
|
24
|
+
*/
|
|
25
|
+
|
|
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
|
+
import { skillQueries } from '$backend/database/queries';
|
|
31
|
+
import { debug } from '$shared/utils/logger';
|
|
32
|
+
import { getSkillMdPath, copySkillInto } from './store';
|
|
33
|
+
|
|
34
|
+
export type SkillEngine = 'claude' | 'codex' | 'copilot' | 'qwen' | 'opencode';
|
|
35
|
+
|
|
36
|
+
const MARKER_START = '<!-- CLOPEN:SKILLS:START — managed block, do not edit -->';
|
|
37
|
+
const MARKER_END = '<!-- CLOPEN:SKILLS:END -->';
|
|
38
|
+
|
|
39
|
+
interface EnabledSkill {
|
|
40
|
+
slug: string;
|
|
41
|
+
name: string;
|
|
42
|
+
description: string;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function getEnabledSkills(): EnabledSkill[] {
|
|
46
|
+
return skillQueries.getEnabled().map(r => ({ slug: r.slug, name: r.name, description: r.description }));
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Native engines read a real skills directory; this is where we mirror to.
|
|
51
|
+
*
|
|
52
|
+
* Claude's skills dir lives under its isolated `CLAUDE_CONFIG_DIR`, so it stays
|
|
53
|
+
* fully inside Clopen's sandbox. Qwen and Copilot DO support skills natively but
|
|
54
|
+
* resolve the user-level dir from `$HOME` (`~/.qwen/skills`, `~/.copilot/skills`)
|
|
55
|
+
* — neither `QWEN_RUNTIME_DIR` nor `COPILOT_HOME` relocates it, and there is no
|
|
56
|
+
* config-dir override. So for those two we manage the user's real global skills
|
|
57
|
+
* dir, touching ONLY the slugs we own (see syncNative's prune guard) and never
|
|
58
|
+
* the user's own skills.
|
|
59
|
+
*/
|
|
60
|
+
function nativeSkillsDir(engine: SkillEngine): string | null {
|
|
61
|
+
switch (engine) {
|
|
62
|
+
case 'claude': return join(getEngineUserConfigDir('claude'), 'skills');
|
|
63
|
+
case 'qwen': return join(homedir(), '.qwen', 'skills');
|
|
64
|
+
case 'copilot': return join(homedir(), '.copilot', 'skills');
|
|
65
|
+
default: return null;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Synthetic engines have no native skills concept — we inject the preamble into
|
|
71
|
+
* the global instructions file each one auto-loads from its (isolated) home.
|
|
72
|
+
*/
|
|
73
|
+
function syntheticMemoryFile(engine: SkillEngine): string | null {
|
|
74
|
+
switch (engine) {
|
|
75
|
+
// Codex loads global guidance from `$CODEX_HOME/AGENTS.md`.
|
|
76
|
+
case 'codex': return join(getEngineUserConfigDir('codex'), 'AGENTS.md');
|
|
77
|
+
// OpenCode reads `AGENTS.md` from its XDG config dir (`$XDG_CONFIG_HOME/opencode`).
|
|
78
|
+
case 'opencode': return join(getEngineUserConfigDir('opencode'), 'opencode', 'AGENTS.md');
|
|
79
|
+
default: return null;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async function pathExists(path: string): Promise<boolean> {
|
|
84
|
+
try { await stat(path); return true; } catch { return false; }
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Mirror enabled skill folders into a native engine's skills dir; prune the rest. */
|
|
88
|
+
async function syncNative(destDir: string, enabled: EnabledSkill[]): Promise<void> {
|
|
89
|
+
await mkdir(destDir, { recursive: true });
|
|
90
|
+
const enabledSlugs = new Set(enabled.map(s => s.slug));
|
|
91
|
+
const managedSlugs = new Set(skillQueries.getAll().map(s => s.slug));
|
|
92
|
+
|
|
93
|
+
// Remove copies of managed skills that are no longer enabled. Folders we
|
|
94
|
+
// don't manage (e.g. user-placed skills) are left untouched.
|
|
95
|
+
for (const entry of await readdir(destDir, { withFileTypes: true })) {
|
|
96
|
+
if (!entry.isDirectory()) continue;
|
|
97
|
+
if (managedSlugs.has(entry.name) && !enabledSlugs.has(entry.name)) {
|
|
98
|
+
await rm(join(destDir, entry.name), { recursive: true, force: true });
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
for (const skill of enabled) {
|
|
103
|
+
await copySkillInto(skill.slug, destDir);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Build the synthetic preamble block listing each enabled skill. */
|
|
108
|
+
function buildPreamble(enabled: EnabledSkill[]): string {
|
|
109
|
+
if (enabled.length === 0) return '';
|
|
110
|
+
const lines: string[] = [
|
|
111
|
+
MARKER_START,
|
|
112
|
+
'# Available Skills',
|
|
113
|
+
'',
|
|
114
|
+
'You have access to the following skills. Each is a set of instructions for a',
|
|
115
|
+
'specific kind of task. When the user\'s request matches a skill\'s purpose, READ',
|
|
116
|
+
'its SKILL.md file with your file-reading tool to load the full instructions',
|
|
117
|
+
'before proceeding. Only load a skill when it is relevant.',
|
|
118
|
+
''
|
|
119
|
+
];
|
|
120
|
+
for (const skill of enabled) {
|
|
121
|
+
lines.push(`- **${skill.name}** — ${skill.description}`);
|
|
122
|
+
lines.push(` Instructions: ${getSkillMdPath(skill.slug)}`);
|
|
123
|
+
}
|
|
124
|
+
lines.push(MARKER_END);
|
|
125
|
+
return lines.join('\n');
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Replace (or remove) the managed skills block inside an engine memory file. */
|
|
129
|
+
async function syncSynthetic(filePath: string, enabled: EnabledSkill[]): Promise<void> {
|
|
130
|
+
let existing = '';
|
|
131
|
+
if (await pathExists(filePath)) existing = await readFile(filePath, 'utf8');
|
|
132
|
+
|
|
133
|
+
// Strip any prior managed block so updates are idempotent and never duplicate.
|
|
134
|
+
const blockRe = new RegExp(`\\n*${escapeRe(MARKER_START)}[\\s\\S]*?${escapeRe(MARKER_END)}\\n*`, 'g');
|
|
135
|
+
const base = existing.replace(blockRe, '\n').replace(/\n{3,}/g, '\n\n').trim();
|
|
136
|
+
|
|
137
|
+
const block = buildPreamble(enabled);
|
|
138
|
+
const next = block ? (base ? `${base}\n\n${block}\n` : `${block}\n`) : (base ? `${base}\n` : '');
|
|
139
|
+
|
|
140
|
+
if (next === existing) return;
|
|
141
|
+
if (next === '') {
|
|
142
|
+
// Nothing managed and nothing else in the file — leave any empty file as-is.
|
|
143
|
+
await writeFile(filePath, '', 'utf8');
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
await mkdir(join(filePath, '..'), { recursive: true });
|
|
147
|
+
await writeFile(filePath, next, 'utf8');
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function escapeRe(s: string): string {
|
|
151
|
+
return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
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.
|
|
157
|
+
* Never throws: failures are logged and swallowed so streaming is unaffected.
|
|
158
|
+
*/
|
|
159
|
+
export async function syncSkills(engine: SkillEngine): Promise<void> {
|
|
160
|
+
try {
|
|
161
|
+
const enabled = getEnabledSkills();
|
|
162
|
+
const native = nativeSkillsDir(engine);
|
|
163
|
+
if (native) {
|
|
164
|
+
await syncNative(native, enabled);
|
|
165
|
+
debug.log('skills', `🧩 Synced ${enabled.length} skill(s) → ${engine} (native)`);
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
const memoryFile = syntheticMemoryFile(engine);
|
|
169
|
+
if (memoryFile) {
|
|
170
|
+
await syncSynthetic(memoryFile, enabled);
|
|
171
|
+
debug.log('skills', `🧩 Synced ${enabled.length} skill(s) → ${engine} (synthetic)`);
|
|
172
|
+
}
|
|
173
|
+
} catch (error) {
|
|
174
|
+
debug.warn('skills', `⚠️ Skill sync for ${engine} failed (continuing without):`, error);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** Re-sync every engine — used after a mutation so changes propagate eagerly. */
|
|
179
|
+
export async function syncSkillsAllEngines(): Promise<void> {
|
|
180
|
+
const engines: SkillEngine[] = ['claude', 'codex', 'copilot', 'qwen', 'opencode'];
|
|
181
|
+
await Promise.all(engines.map(syncSkills));
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** Validate that a skill's SKILL.md exists on disk (used by the WS status surface). */
|
|
185
|
+
export async function skillFileReady(slug: string): Promise<boolean> {
|
|
186
|
+
return pathExists(getSkillMdPath(slug));
|
|
187
|
+
}
|
|
@@ -1,8 +1,5 @@
|
|
|
1
1
|
// Export shell utilities
|
|
2
2
|
export * from './shell-utils.js';
|
|
3
3
|
|
|
4
|
-
// Export
|
|
5
|
-
export * from './
|
|
6
|
-
|
|
7
|
-
// Export terminal stream manager
|
|
8
|
-
export * from './stream-manager.js';
|
|
4
|
+
// Export the PtyKit backend bridge (session engine + embedded server)
|
|
5
|
+
export * from './ptykit.js';
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PtyKit backend bridge.
|
|
3
|
+
*
|
|
4
|
+
* Clopen adopts @myrialabs/ptykit wholesale for terminal PTY sessions: the core
|
|
5
|
+
* `PtyKitManager` owns spawn + scrollback + serialized reattach + backend
|
|
6
|
+
* auto-detect, and an embedded `PtyKitServer` speaks the PtyKit wire protocol.
|
|
7
|
+
* There is no second WebSocket — the server is driven over Clopen's existing
|
|
8
|
+
* app-wide socket via `handleFrame` (see `backend/ws/terminal/tunnel.ts`).
|
|
9
|
+
*
|
|
10
|
+
* - `namespace` = Clopen `projectId` (collaborative room + anti-hijack scope).
|
|
11
|
+
* - `authorize` bridges to Clopen's project-access check.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { PtyKitManager } from '@myrialabs/ptykit/core';
|
|
15
|
+
import { createPtyKitServer } from '@myrialabs/ptykit/server';
|
|
16
|
+
import { projectQueries } from '$backend/database/queries';
|
|
17
|
+
|
|
18
|
+
/** Terminal-friendly env, matching the previous `createCleanPtyEnv` overrides. */
|
|
19
|
+
const TERMINAL_ENV = {
|
|
20
|
+
FORCE_COLOR: '1',
|
|
21
|
+
COLORTERM: 'truecolor',
|
|
22
|
+
TERM: 'xterm-256color',
|
|
23
|
+
TERM_PROGRAM: 'xterm.js',
|
|
24
|
+
CLICOLOR: '1',
|
|
25
|
+
LC_ALL: 'en_US.UTF-8',
|
|
26
|
+
LANG: 'en_US.UTF-8'
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
/** Singleton session engine — replaces pty-session-manager + stream-manager. */
|
|
30
|
+
export const ptyKitManager = new PtyKitManager({
|
|
31
|
+
scrollback: 5000,
|
|
32
|
+
// Sessions live until the tab is killed; keep exited sessions briefly so a
|
|
33
|
+
// refresh/reconnect can still replay their final screen (matches old 5-min window).
|
|
34
|
+
idleTtl: null,
|
|
35
|
+
retainExitedMs: 5 * 60_000,
|
|
36
|
+
env: { sanitize: true, inject: TERMINAL_ENV }
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Embedded WebSocket server over the manager. No HTTP/Bun mounting — Clopen's
|
|
41
|
+
* tunnel feeds it frames and supplies per-connection `send`. `authorize` enforces
|
|
42
|
+
* project access; the room is the project so output is collaborative.
|
|
43
|
+
*/
|
|
44
|
+
export const ptyKitServer = createPtyKitServer(ptyKitManager, {
|
|
45
|
+
room: (ctx) => ctx.namespace,
|
|
46
|
+
authorize: (ctx) => {
|
|
47
|
+
const userId = ctx.conn.data.userId;
|
|
48
|
+
if (typeof userId !== 'string' || !userId) return false;
|
|
49
|
+
return projectQueries.userHasProject(userId, ctx.namespace);
|
|
50
|
+
}
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Kill every PTY session belonging to a project (namespace). Used on project
|
|
55
|
+
* delete/remove to reap orphaned shells. Returns the number killed.
|
|
56
|
+
*/
|
|
57
|
+
export function cleanupProjectSessions(projectId: string): number {
|
|
58
|
+
let killed = 0;
|
|
59
|
+
for (const session of ptyKitManager.list(projectId)) {
|
|
60
|
+
ptyKitManager.killSession(session.sessionId, 'SIGKILL');
|
|
61
|
+
killed++;
|
|
62
|
+
}
|
|
63
|
+
return killed;
|
|
64
|
+
}
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
8
|
import { join } from 'path';
|
|
9
|
-
import { TunnelKit, TunnelStore, type ActiveTunnel, type IngressInfo, type TunnelType } from 'tunnelkit';
|
|
9
|
+
import { TunnelKit, TunnelStore, type ActiveTunnel, type IngressInfo, type TunnelType } from '@myrialabs/tunnelkit';
|
|
10
10
|
import { getClopenDir } from '../utils/paths';
|
|
11
11
|
import { debug } from '$shared/utils/logger';
|
|
12
12
|
|
package/backend/utils/ws.ts
CHANGED
|
@@ -1026,6 +1026,20 @@ class WSServer {
|
|
|
1026
1026
|
}
|
|
1027
1027
|
};
|
|
1028
1028
|
|
|
1029
|
+
/**
|
|
1030
|
+
* Send a pre-serialized message to a single connection by its stable id.
|
|
1031
|
+
* Resolves the CURRENT wrapper (Elysia recreates wrappers per handler call),
|
|
1032
|
+
* so it is safe to hold a connection id in a long-lived closure and send later
|
|
1033
|
+
* — e.g. an embedded PtyKit transport tunneling frames to one viewer. Applies
|
|
1034
|
+
* the same backpressure guard as room emits. Returns false if the connection is
|
|
1035
|
+
* gone or backpressured.
|
|
1036
|
+
*/
|
|
1037
|
+
sendToConnectionId(connId: string, message: string | ArrayBuffer): boolean {
|
|
1038
|
+
const conn = this.connections.get(connId);
|
|
1039
|
+
if (!conn) return false;
|
|
1040
|
+
return this.sendToConnection(conn, message);
|
|
1041
|
+
}
|
|
1042
|
+
|
|
1029
1043
|
/**
|
|
1030
1044
|
* Get all connections (optionally filtered by project)
|
|
1031
1045
|
*/
|
|
@@ -22,7 +22,7 @@ import {
|
|
|
22
22
|
duplicateOperation,
|
|
23
23
|
deleteOperation
|
|
24
24
|
} from '../../files/file-operations';
|
|
25
|
-
import {
|
|
25
|
+
import { createArchiveOperation, extractArchiveOperation } from '../../files/file-archive';
|
|
26
26
|
import { stat as fsStat, readdir as fsReaddir, rename as fsRename } from 'node:fs/promises';
|
|
27
27
|
import { requireFilePathAccess, requireSharedFilePathAccess } from './path-access';
|
|
28
28
|
|
|
@@ -127,11 +127,21 @@ export const writeHandler = createRouter()
|
|
|
127
127
|
// kept getting dropped by the Vite dev proxy with `write EPIPE` on
|
|
128
128
|
// sustained binary transfers (any chunk size). See backend/http/files-upload.ts.
|
|
129
129
|
|
|
130
|
-
//
|
|
130
|
+
// Compress operation — pack files/directories into an archive (zip/tar/7z)
|
|
131
131
|
.http('files:zip', {
|
|
132
132
|
data: t.Object({
|
|
133
133
|
sourcePaths: t.Array(t.String()),
|
|
134
|
-
targetPath: t.String()
|
|
134
|
+
targetPath: t.String(),
|
|
135
|
+
format: t.Optional(t.Union([
|
|
136
|
+
t.Literal('zip'),
|
|
137
|
+
t.Literal('tar'),
|
|
138
|
+
t.Literal('tar.gz'),
|
|
139
|
+
t.Literal('tar.zst'),
|
|
140
|
+
t.Literal('7z')
|
|
141
|
+
])),
|
|
142
|
+
method: t.Optional(t.Union([t.Literal('store'), t.Literal('deflate'), t.Literal('zstd')])),
|
|
143
|
+
level: t.Optional(t.Number()),
|
|
144
|
+
password: t.Optional(t.String())
|
|
135
145
|
}),
|
|
136
146
|
response: t.Object({
|
|
137
147
|
message: t.String(),
|
|
@@ -148,14 +158,20 @@ export const writeHandler = createRouter()
|
|
|
148
158
|
resolvedSources.push(await requireFilePathAccess(conn, p));
|
|
149
159
|
}
|
|
150
160
|
const resolvedTarget = await requireFilePathAccess(conn, data.targetPath);
|
|
151
|
-
return await
|
|
161
|
+
return await createArchiveOperation(resolvedSources, resolvedTarget, {
|
|
162
|
+
format: data.format,
|
|
163
|
+
method: data.method,
|
|
164
|
+
level: data.level,
|
|
165
|
+
password: data.password
|
|
166
|
+
});
|
|
152
167
|
})
|
|
153
168
|
|
|
154
|
-
// Extract operation — extract
|
|
169
|
+
// Extract operation — extract any supported archive into a target directory
|
|
155
170
|
.http('files:extract', {
|
|
156
171
|
data: t.Object({
|
|
157
172
|
archivePath: t.String(),
|
|
158
|
-
targetDir: t.String()
|
|
173
|
+
targetDir: t.String(),
|
|
174
|
+
password: t.Optional(t.String())
|
|
159
175
|
}),
|
|
160
176
|
response: t.Object({
|
|
161
177
|
message: t.String(),
|
|
@@ -166,7 +182,7 @@ export const writeHandler = createRouter()
|
|
|
166
182
|
}, async ({ data, conn }) => {
|
|
167
183
|
const archivePath = await requireFilePathAccess(conn, data.archivePath);
|
|
168
184
|
const targetDir = await requireFilePathAccess(conn, data.targetDir);
|
|
169
|
-
return await
|
|
185
|
+
return await extractArchiveOperation(archivePath, targetDir, data.password);
|
|
170
186
|
})
|
|
171
187
|
|
|
172
188
|
// Delete operation
|