@myrialabs/clopen 0.4.8 → 0.4.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -7
- 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 +21 -0
- package/backend/database/queries/subagent-queries.ts +92 -0
- 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/project/status-manager.ts +7 -25
- 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/utils/static-curl.ts +12 -54
- 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/git/branch.ts +4 -2
- 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/sessions/crud.ts +12 -0
- package/backend/ws/subagents/crud.ts +136 -0
- package/backend/ws/subagents/index.ts +8 -0
- package/dist/assets/{index-jGo0X72U.js → index-C3kp8wpM.js} +1 -1
- package/dist/assets/{index-B_F_OgoC.js → index-cVUk7das.js} +1 -1
- package/dist/assets/main-CuCxUeqZ.js +533 -0
- package/dist/assets/main-D4pdkiQK.css +1 -0
- package/dist/index.html +2 -2
- package/package.json +24 -24
- package/shared/constants/engine-tools.ts +56 -0
- package/shared/types/database/schema.ts +2 -0
- package/shared/types/stores/settings.ts +15 -0
- package/shared/types/unified/stream.ts +7 -0
- package/shared/utils/interactive-input.ts +71 -0
- package/shared/utils/logger.ts +6 -0
- package/dist/assets/main-BkCc3WEB.js +0 -481
- package/dist/assets/main-CWDwET4x.css +0 -1
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Subagent service — keeps the `subagents` table and the on-disk canonical store
|
|
3
|
+
* in lockstep for Settings → Subagents. Skills-shaped, plus a per-engine tool
|
|
4
|
+
* allowlist and per-engine model override (JSON maps keyed by EngineType). The
|
|
5
|
+
* canonical `.md` holds only name/description/body; model & tools are injected
|
|
6
|
+
* per engine at sync time.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { subagentQueries, type SubagentRow } from '$backend/database/queries';
|
|
10
|
+
import { parseDoc, serializeDoc, uniqueSlug, parseEngineMap, stringifyEngineMap, normalizeToolList, type EngineMap } from '$backend/artifacts';
|
|
11
|
+
import { debug } from '$shared/utils/logger';
|
|
12
|
+
import {
|
|
13
|
+
writeSubagentMd,
|
|
14
|
+
readSubagentMd,
|
|
15
|
+
deleteSubagentMd,
|
|
16
|
+
subagentFileExists
|
|
17
|
+
} from './store';
|
|
18
|
+
|
|
19
|
+
export interface SubagentDTO {
|
|
20
|
+
id: number;
|
|
21
|
+
slug: string;
|
|
22
|
+
name: string;
|
|
23
|
+
description: string;
|
|
24
|
+
/** Per-engine tool allowlist (EngineType → comma list; absent = all tools). */
|
|
25
|
+
toolsByEngine: EngineMap;
|
|
26
|
+
/** Per-engine model override (EngineType → model id; absent = inherit). */
|
|
27
|
+
modelByEngine: EngineMap;
|
|
28
|
+
source: 'custom' | 'imported';
|
|
29
|
+
enabled: boolean;
|
|
30
|
+
present: boolean;
|
|
31
|
+
createdAt: string;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface SubagentInputFields {
|
|
35
|
+
name: string;
|
|
36
|
+
description: string;
|
|
37
|
+
toolsByEngine?: EngineMap;
|
|
38
|
+
modelByEngine?: EngineMap;
|
|
39
|
+
body: string;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const FRONTMATTER_ORDER = ['name', 'description'];
|
|
43
|
+
|
|
44
|
+
function toDTO(row: SubagentRow, present: boolean): SubagentDTO {
|
|
45
|
+
return {
|
|
46
|
+
id: row.id,
|
|
47
|
+
slug: row.slug,
|
|
48
|
+
name: row.name,
|
|
49
|
+
description: row.description,
|
|
50
|
+
toolsByEngine: parseEngineMap(row.tools_by_engine),
|
|
51
|
+
modelByEngine: parseEngineMap(row.model_by_engine),
|
|
52
|
+
source: row.source,
|
|
53
|
+
enabled: row.is_enabled === 1,
|
|
54
|
+
present,
|
|
55
|
+
createdAt: row.created_at
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Normalise each per-engine tool allowlist string into `a, b, c`. */
|
|
60
|
+
function normalizeToolsMap(map: EngineMap | undefined): EngineMap {
|
|
61
|
+
const out: EngineMap = {};
|
|
62
|
+
for (const [engine, list] of Object.entries(map ?? {})) {
|
|
63
|
+
const normalized = normalizeToolList(list);
|
|
64
|
+
if (normalized) out[engine as keyof EngineMap] = normalized;
|
|
65
|
+
}
|
|
66
|
+
return out;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** An imported Claude-shaped `.md` maps its single frontmatter value → claude slot. */
|
|
70
|
+
function singleToMap(value: string | undefined): EngineMap {
|
|
71
|
+
return value?.trim() ? { 'claude-code': value.trim() } : {};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Canonical doc holds name + description only; model/tools are per-engine (sync-injected). */
|
|
75
|
+
function buildDocument(slug: string, fields: SubagentInputFields): string {
|
|
76
|
+
const frontmatter: Record<string, string> = { name: slug };
|
|
77
|
+
if (fields.description.trim()) frontmatter.description = fields.description.trim();
|
|
78
|
+
return serializeDoc({ frontmatter, body: fields.body }, FRONTMATTER_ORDER);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export const subagentService = {
|
|
82
|
+
async list(): Promise<SubagentDTO[]> {
|
|
83
|
+
const rows = subagentQueries.getAll();
|
|
84
|
+
const presence = await Promise.all(rows.map(r => subagentFileExists(r.slug)));
|
|
85
|
+
return rows.map((row, i) => toDTO(row, presence[i]));
|
|
86
|
+
},
|
|
87
|
+
|
|
88
|
+
async get(id: number): Promise<{ subagent: SubagentDTO; body: string } | null> {
|
|
89
|
+
const row = subagentQueries.getById(id);
|
|
90
|
+
if (!row) return null;
|
|
91
|
+
const raw = await readSubagentMd(row.slug);
|
|
92
|
+
const body = raw ? parseDoc(raw).body : '';
|
|
93
|
+
return { subagent: toDTO(row, raw !== null), body };
|
|
94
|
+
},
|
|
95
|
+
|
|
96
|
+
async create(input: SubagentInputFields): Promise<SubagentDTO> {
|
|
97
|
+
if (!input.name.trim()) throw new Error('A subagent name is required');
|
|
98
|
+
if (!input.description.trim()) throw new Error('A subagent description is required');
|
|
99
|
+
const slug = uniqueSlug(input.name, s => !!subagentQueries.getBySlug(s));
|
|
100
|
+
await writeSubagentMd(slug, buildDocument(slug, input));
|
|
101
|
+
const row = subagentQueries.insert({
|
|
102
|
+
slug,
|
|
103
|
+
name: input.name.trim(),
|
|
104
|
+
description: input.description.trim(),
|
|
105
|
+
toolsByEngine: stringifyEngineMap(normalizeToolsMap(input.toolsByEngine)),
|
|
106
|
+
modelByEngine: stringifyEngineMap(input.modelByEngine),
|
|
107
|
+
source: 'custom'
|
|
108
|
+
});
|
|
109
|
+
debug.log('subagents', `📦 Created subagent: ${slug}`);
|
|
110
|
+
return toDTO(row, true);
|
|
111
|
+
},
|
|
112
|
+
|
|
113
|
+
async update(id: number, input: SubagentInputFields): Promise<SubagentDTO> {
|
|
114
|
+
const row = subagentQueries.getById(id);
|
|
115
|
+
if (!row) throw new Error('Subagent not found');
|
|
116
|
+
if (!input.description.trim()) throw new Error('A subagent description is required');
|
|
117
|
+
await writeSubagentMd(row.slug, buildDocument(row.slug, input));
|
|
118
|
+
subagentQueries.updateMeta(
|
|
119
|
+
id,
|
|
120
|
+
input.name.trim(),
|
|
121
|
+
input.description.trim(),
|
|
122
|
+
stringifyEngineMap(normalizeToolsMap(input.toolsByEngine)),
|
|
123
|
+
stringifyEngineMap(input.modelByEngine)
|
|
124
|
+
);
|
|
125
|
+
debug.log('subagents', `🔧 Updated subagent: ${row.slug}`);
|
|
126
|
+
return toDTO(subagentQueries.getById(id)!, true);
|
|
127
|
+
},
|
|
128
|
+
|
|
129
|
+
parsePreview(raw: string): { name: string; description: string; toolsByEngine: EngineMap; modelByEngine: EngineMap; body: string } {
|
|
130
|
+
const parsed = parseDoc(raw);
|
|
131
|
+
return {
|
|
132
|
+
name: parsed.frontmatter.name || '',
|
|
133
|
+
description: parsed.frontmatter.description || '',
|
|
134
|
+
toolsByEngine: singleToMap(parsed.frontmatter.tools),
|
|
135
|
+
modelByEngine: singleToMap(parsed.frontmatter.model),
|
|
136
|
+
body: parsed.body
|
|
137
|
+
};
|
|
138
|
+
},
|
|
139
|
+
|
|
140
|
+
async import(raw: string, nameHint?: string): Promise<SubagentDTO> {
|
|
141
|
+
const parsed = parseDoc(raw);
|
|
142
|
+
const displayName = (nameHint?.trim() || parsed.frontmatter.name || 'subagent').trim();
|
|
143
|
+
return this.create({
|
|
144
|
+
name: displayName,
|
|
145
|
+
description: parsed.frontmatter.description || '',
|
|
146
|
+
toolsByEngine: singleToMap(parsed.frontmatter.tools),
|
|
147
|
+
modelByEngine: singleToMap(parsed.frontmatter.model),
|
|
148
|
+
body: parsed.body
|
|
149
|
+
});
|
|
150
|
+
},
|
|
151
|
+
|
|
152
|
+
toggle(id: number, enabled: boolean): SubagentDTO {
|
|
153
|
+
const row = subagentQueries.getById(id);
|
|
154
|
+
if (!row) throw new Error('Subagent not found');
|
|
155
|
+
subagentQueries.setEnabled(id, enabled);
|
|
156
|
+
return toDTO(subagentQueries.getById(id)!, true);
|
|
157
|
+
},
|
|
158
|
+
|
|
159
|
+
async remove(id: number): Promise<void> {
|
|
160
|
+
const row = subagentQueries.getById(id);
|
|
161
|
+
if (!row) throw new Error('Subagent not found');
|
|
162
|
+
await deleteSubagentMd(row.slug);
|
|
163
|
+
subagentQueries.remove(id);
|
|
164
|
+
debug.log('subagents', `🗑️ Deleted subagent: ${row.slug}`);
|
|
165
|
+
}
|
|
166
|
+
};
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Canonical subagent store — one Markdown file per subagent under
|
|
3
|
+
* `{clopenDir}/subagents/<slug>.md` (a `single-md` artifact). The DB tracks
|
|
4
|
+
* metadata + the enable toggle; the sync layer mirrors enabled subagents into
|
|
5
|
+
* each engine's agents dir (native) or a synthetic preamble.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { join } from 'path';
|
|
9
|
+
import { mkdir, rm, stat, writeFile, readFile } from 'node:fs/promises';
|
|
10
|
+
import { getClopenDir } from '$backend/utils/paths';
|
|
11
|
+
import { debug } from '$shared/utils/logger';
|
|
12
|
+
|
|
13
|
+
export function getSubagentsRootDir(): string {
|
|
14
|
+
return join(getClopenDir(), 'subagents');
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function getSubagentPath(slug: string): string {
|
|
18
|
+
return join(getSubagentsRootDir(), `${slug}.md`);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async function pathExists(path: string): Promise<boolean> {
|
|
22
|
+
try { await stat(path); return true; } catch { return false; }
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function subagentFileExists(slug: string): Promise<boolean> {
|
|
26
|
+
return pathExists(getSubagentPath(slug));
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export async function readSubagentMd(slug: string): Promise<string | null> {
|
|
30
|
+
const path = getSubagentPath(slug);
|
|
31
|
+
if (!(await pathExists(path))) return null;
|
|
32
|
+
return readFile(path, 'utf8');
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export async function writeSubagentMd(slug: string, content: string): Promise<void> {
|
|
36
|
+
await mkdir(getSubagentsRootDir(), { recursive: true });
|
|
37
|
+
await writeFile(getSubagentPath(slug), content, 'utf8');
|
|
38
|
+
debug.log('subagents', `💾 Wrote subagent ${slug}.md`);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export async function deleteSubagentMd(slug: string): Promise<void> {
|
|
42
|
+
await rm(getSubagentPath(slug), { force: true });
|
|
43
|
+
debug.log('subagents', `🗑️ Removed subagent ${slug}.md`);
|
|
44
|
+
}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Engine sync for Subagents — a thin adapter over the shared artifact framework.
|
|
3
|
+
* Enabled subagents are mirrored as `<slug>.md` into each engine's native agents
|
|
4
|
+
* dir (Claude: `.../agents/`) or listed in a synthetic preamble for engines with
|
|
5
|
+
* no native subagent concept (best-effort/unverified).
|
|
6
|
+
*
|
|
7
|
+
* Never throws — a stream never breaks because subagents couldn't sync.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { subagentQueries } from '$backend/database/queries';
|
|
11
|
+
import { debug } from '$shared/utils/logger';
|
|
12
|
+
import { materializeArtifacts, resolveArtifact, isPromptScopedEngine, parseDoc, serializeDoc, parseEngineMap, artifactEngineToType, type ManagedArtifact, type ArtifactEngine } from '$backend/artifacts';
|
|
13
|
+
import { artifactFilter } from '$backend/profiles';
|
|
14
|
+
import { readSubagentMd } from './store';
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Shape a subagent document for the engine's native format, injecting that
|
|
18
|
+
* engine's own model/tool override (both are per-engine; the canonical `.md`
|
|
19
|
+
* carries neither).
|
|
20
|
+
* - Claude reads a comma-list `tools` and a `model` in frontmatter.
|
|
21
|
+
* - OpenCode agents need `mode: subagent` and express `tools` as a map (not the
|
|
22
|
+
* Claude comma-list); we emit description + mode + model and drop `tools`
|
|
23
|
+
* rather than mistranslate the allowlist. See https://opencode.ai/docs/agents.
|
|
24
|
+
* - Other engines fall back to a synthetic preamble that ignores the document.
|
|
25
|
+
*/
|
|
26
|
+
function documentForEngine(engine: ArtifactEngine, raw: string, model?: string, tools?: string): string {
|
|
27
|
+
const { frontmatter, body } = parseDoc(raw);
|
|
28
|
+
if (engine === 'opencode') {
|
|
29
|
+
const fm: Record<string, string> = { mode: 'subagent' };
|
|
30
|
+
if (frontmatter.description) fm.description = frontmatter.description;
|
|
31
|
+
if (model) fm.model = model;
|
|
32
|
+
return serializeDoc({ frontmatter: fm, body }, ['description', 'mode', 'model']);
|
|
33
|
+
}
|
|
34
|
+
// Claude (and the default): re-serialize with the injected model/tools.
|
|
35
|
+
const fm: Record<string, string> = { name: frontmatter.name };
|
|
36
|
+
if (frontmatter.description) fm.description = frontmatter.description;
|
|
37
|
+
if (tools) fm.tools = tools;
|
|
38
|
+
if (model) fm.model = model;
|
|
39
|
+
return serializeDoc({ frontmatter: fm, body }, ['name', 'description', 'tools', 'model']);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function buildSubagentsPreamble(items: ManagedArtifact[]): string {
|
|
43
|
+
if (items.length === 0) return '';
|
|
44
|
+
const lines = ['# Available Subagents', '', 'Specialized agent definitions you can delegate matching tasks to:', ''];
|
|
45
|
+
for (const s of items) lines.push(`- **${s.name}** (${s.slug}) — ${s.description}`);
|
|
46
|
+
return lines.join('\n');
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The subagents active for a stream, narrowed by the active Profile (metadata only). */
|
|
50
|
+
function resolveEnabledSubagentsMeta(profileId?: number): ManagedArtifact[] {
|
|
51
|
+
const filter = artifactFilter(profileId, 'subagent');
|
|
52
|
+
return (filter ? subagentQueries.getAll() : subagentQueries.getEnabled())
|
|
53
|
+
.filter(r => !filter || filter.has(r.slug))
|
|
54
|
+
.map(r => ({ slug: r.slug, name: r.name, description: r.description }));
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* The profile-scoped subagents preamble for PER-SESSION injection into a
|
|
59
|
+
* prompt-scoped engine's prompt (OpenCode/Codex/Copilot). Returns '' when none
|
|
60
|
+
* apply. Advisory: it steers which subagents the model delegates to, on top of
|
|
61
|
+
* whatever the engine's own (possibly stale/shared) agent registry exposes.
|
|
62
|
+
*/
|
|
63
|
+
export function buildSubagentsPromptContext(profileId?: number): string {
|
|
64
|
+
return buildSubagentsPreamble(resolveEnabledSubagentsMeta(profileId));
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** One inline Open Code agent definition (an `AgentConfig` in its config content). */
|
|
68
|
+
export interface OpenCodeInlineAgent {
|
|
69
|
+
description?: string;
|
|
70
|
+
mode: 'subagent';
|
|
71
|
+
prompt: string;
|
|
72
|
+
model?: string;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* The profile-scoped subagents as INLINE Open Code agent definitions, keyed by
|
|
77
|
+
* slug. Open Code caches its agent registry from a shared dir at server boot, so
|
|
78
|
+
* a per-session dir prune can't scope it; instead each per-Profile server is
|
|
79
|
+
* built with exactly these agents inline (see the server pool). Returns the
|
|
80
|
+
* enabled set narrowed by the active Profile (a referenced subagent counts even
|
|
81
|
+
* if globally disabled — same presence-per-type rule as everywhere else).
|
|
82
|
+
*/
|
|
83
|
+
export async function buildOpenCodeInlineAgents(profileId?: number): Promise<Record<string, OpenCodeInlineAgent>> {
|
|
84
|
+
const filter = artifactFilter(profileId, 'subagent');
|
|
85
|
+
const rows = (filter ? subagentQueries.getAll() : subagentQueries.getEnabled())
|
|
86
|
+
.filter(r => !filter || filter.has(r.slug));
|
|
87
|
+
const out: Record<string, OpenCodeInlineAgent> = {};
|
|
88
|
+
for (const row of rows) {
|
|
89
|
+
const raw = await readSubagentMd(row.slug);
|
|
90
|
+
if (raw == null) continue;
|
|
91
|
+
const { frontmatter, body } = parseDoc(raw);
|
|
92
|
+
const model = parseEngineMap(row.model_by_engine).opencode;
|
|
93
|
+
out[row.slug] = {
|
|
94
|
+
description: frontmatter.description || row.description,
|
|
95
|
+
mode: 'subagent',
|
|
96
|
+
prompt: body,
|
|
97
|
+
...(model ? { model } : {})
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
return out;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export async function syncSubagents(engine: ArtifactEngine, profileId?: number): Promise<void> {
|
|
104
|
+
try {
|
|
105
|
+
// Deliver subagents OUT-OF-BAND (not via the shared engine dir/block) when:
|
|
106
|
+
// - the target is SYNTHETIC on a prompt-scoped engine (Codex/Copilot) →
|
|
107
|
+
// injected into the prompt as a preamble; OR
|
|
108
|
+
// - the engine is OpenCode → each per-Profile server is built with the
|
|
109
|
+
// agents INLINE in its config (Open Code caches its agent registry from
|
|
110
|
+
// the shared dir at boot, so a per-session dir prune can't scope it).
|
|
111
|
+
// In both cases materialize an EMPTY set so any stale dir/block is stripped.
|
|
112
|
+
// Claude keeps its native filtered files; Qwen (per-query) keeps its preamble.
|
|
113
|
+
const synthetic = resolveArtifact('subagent', { engine, scope: 'global' }).format === 'preamble-region';
|
|
114
|
+
const viaPrompt = (synthetic && isPromptScopedEngine(engine)) || engine === 'opencode';
|
|
115
|
+
const filter = artifactFilter(profileId, 'subagent');
|
|
116
|
+
// A profile activates the subagents it references even if globally disabled;
|
|
117
|
+
// with no profile filter, only the enabled set applies (unchanged).
|
|
118
|
+
const rows = viaPrompt ? [] : (filter ? subagentQueries.getAll() : subagentQueries.getEnabled())
|
|
119
|
+
.filter(r => !filter || filter.has(r.slug));
|
|
120
|
+
const engineType = artifactEngineToType(engine);
|
|
121
|
+
const enabled: ManagedArtifact[] = [];
|
|
122
|
+
for (const row of rows) {
|
|
123
|
+
const raw = await readSubagentMd(row.slug);
|
|
124
|
+
if (raw == null) continue;
|
|
125
|
+
const model = parseEngineMap(row.model_by_engine)[engineType];
|
|
126
|
+
const tools = parseEngineMap(row.tools_by_engine)[engineType];
|
|
127
|
+
enabled.push({ slug: row.slug, name: row.name, description: row.description, document: documentForEngine(engine, raw, model, tools) });
|
|
128
|
+
}
|
|
129
|
+
const managedSlugs = subagentQueries.getAll().map(r => r.slug);
|
|
130
|
+
await materializeArtifacts('subagent', { engine, scope: 'global' }, {
|
|
131
|
+
enabled,
|
|
132
|
+
managedSlugs,
|
|
133
|
+
buildPreamble: buildSubagentsPreamble
|
|
134
|
+
});
|
|
135
|
+
debug.log('subagents', `🤖 Synced ${enabled.length} subagent(s) → ${engine}`);
|
|
136
|
+
} catch (error) {
|
|
137
|
+
debug.warn('subagents', `⚠️ Subagent sync for ${engine} failed (continuing without):`, error);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export async function syncSubagentsAllEngines(): Promise<void> {
|
|
142
|
+
const engines: ArtifactEngine[] = ['claude', 'codex', 'copilot', 'qwen', 'opencode'];
|
|
143
|
+
await Promise.all(engines.map(syncSubagents));
|
|
144
|
+
}
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
|
|
19
19
|
import { existsSync, readdirSync, mkdirSync, chmodSync, renameSync } from 'node:fs';
|
|
20
20
|
import { join, dirname } from 'node:path';
|
|
21
|
-
import {
|
|
21
|
+
import { untar, unxz } from '@myrialabs/zipkit';
|
|
22
22
|
import { debug } from '$shared/utils/logger';
|
|
23
23
|
import { getClopenDir } from '$backend/utils/paths';
|
|
24
24
|
import { resolveBinary } from '$backend/utils/cli';
|
|
@@ -104,59 +104,18 @@ function sha256(bytes: Uint8Array): string {
|
|
|
104
104
|
return hasher.digest('hex');
|
|
105
105
|
}
|
|
106
106
|
|
|
107
|
-
function parseTarOctal(bytes: Uint8Array): number {
|
|
108
|
-
let end = bytes.length;
|
|
109
|
-
for (let i = 0; i < bytes.length; i++) {
|
|
110
|
-
if (bytes[i] === 0 || bytes[i] === 0x20) {
|
|
111
|
-
end = i;
|
|
112
|
-
break;
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
const str = new TextDecoder().decode(bytes.subarray(0, end)).trim();
|
|
116
|
-
return str === '' ? 0 : parseInt(str, 8);
|
|
117
|
-
}
|
|
118
|
-
|
|
119
107
|
/**
|
|
120
|
-
*
|
|
121
|
-
*
|
|
122
|
-
*
|
|
108
|
+
* Pull the `curl` binary out of a static-curl `.tar.xz` archive: unxz the
|
|
109
|
+
* outer layer, then walk the tar for the entry named `curl` (it sits at the
|
|
110
|
+
* archive root). The archive is small and already SHA256-verified before we
|
|
111
|
+
* get here, so decoding it whole in memory is fine — no streaming needed.
|
|
123
112
|
*/
|
|
124
|
-
function
|
|
125
|
-
const
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
for (let i = 0; i < 512; i++) {
|
|
131
|
-
if (header[i] !== 0) { allZero = false; break; }
|
|
132
|
-
}
|
|
133
|
-
if (allZero) return null;
|
|
134
|
-
|
|
135
|
-
const nameBytes = header.subarray(0, 100);
|
|
136
|
-
const nameEnd = nameBytes.indexOf(0);
|
|
137
|
-
const name = decoder.decode(nameEnd >= 0 ? nameBytes.subarray(0, nameEnd) : nameBytes);
|
|
138
|
-
const size = parseTarOctal(header.subarray(124, 136));
|
|
139
|
-
const typeflag = header[156];
|
|
140
|
-
const isRegularFile = typeflag === 0 || typeflag === 0x30; // '\0' or '0'
|
|
141
|
-
|
|
142
|
-
offset += 512;
|
|
143
|
-
if (isRegularFile && name === filename) {
|
|
144
|
-
return tarBytes.subarray(offset, offset + size);
|
|
145
|
-
}
|
|
146
|
-
offset += Math.ceil(size / 512) * 512;
|
|
147
|
-
}
|
|
148
|
-
return null;
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
async function decompressXz(xzBytes: Uint8Array): Promise<Uint8Array> {
|
|
152
|
-
const input = new ReadableStream<Uint8Array>({
|
|
153
|
-
start(controller) {
|
|
154
|
-
controller.enqueue(xzBytes);
|
|
155
|
-
controller.close();
|
|
156
|
-
}
|
|
157
|
-
});
|
|
158
|
-
const decompressed = new Response(new XzReadableStream(input));
|
|
159
|
-
return new Uint8Array(await decompressed.arrayBuffer());
|
|
113
|
+
async function extractCurlFromArchive(archiveBytes: Uint8Array): Promise<Uint8Array | null> {
|
|
114
|
+
const entries = untar(await unxz(archiveBytes));
|
|
115
|
+
const curl = entries.find(
|
|
116
|
+
(entry) => entry.type === 'file' && entry.name.split('/').pop() === 'curl'
|
|
117
|
+
);
|
|
118
|
+
return curl?.data ?? null;
|
|
160
119
|
}
|
|
161
120
|
|
|
162
121
|
export type CurlProgressPhase = 'cached' | 'fetching' | 'verifying' | 'extracting' | 'done';
|
|
@@ -209,8 +168,7 @@ export async function ensureCurlAvailable(
|
|
|
209
168
|
}
|
|
210
169
|
|
|
211
170
|
onProgress({ phase: 'extracting', message: `extracting curl to ${binDir}` });
|
|
212
|
-
const
|
|
213
|
-
const curlBytes = findFileInTar(tarBytes, 'curl');
|
|
171
|
+
const curlBytes = await extractCurlFromArchive(archiveBytes);
|
|
214
172
|
if (!curlBytes) {
|
|
215
173
|
throw new Error('curl binary not found in archive');
|
|
216
174
|
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Artifact AI-generation handler (Settings → Skills/Commands/Subagents/Instructions).
|
|
3
|
+
*
|
|
4
|
+
* - artifacts:generate — draft an artifact of a given type from a purpose
|
|
5
|
+
* sentence, using the caller-selected engine/model (the "Artifacts" model in
|
|
6
|
+
* Settings → Models). Returns loosely-typed fields the editor prefills.
|
|
7
|
+
*
|
|
8
|
+
* Admin-gated (authoring is part of the admin artifact editors). The engine/model
|
|
9
|
+
* are chosen client-side, mirroring git:generate-commit-message.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { t } from 'elysia';
|
|
13
|
+
import { createRouter } from '$shared/utils/ws-server';
|
|
14
|
+
import { debug } from '$shared/utils/logger';
|
|
15
|
+
import { generateArtifact, type GeneratableType } from '$backend/artifacts';
|
|
16
|
+
import type { EngineType } from '$shared/types/unified';
|
|
17
|
+
import { requireProjectAccess } from '../access';
|
|
18
|
+
|
|
19
|
+
export const artifactGenerateHandler = createRouter()
|
|
20
|
+
.http('artifacts:generate', {
|
|
21
|
+
data: t.Object({
|
|
22
|
+
artifactType: t.Union([
|
|
23
|
+
t.Literal('skill'),
|
|
24
|
+
t.Literal('command'),
|
|
25
|
+
t.Literal('subagent'),
|
|
26
|
+
t.Literal('instruction')
|
|
27
|
+
]),
|
|
28
|
+
purpose: t.String(),
|
|
29
|
+
engine: t.String(),
|
|
30
|
+
providerSlug: t.String(),
|
|
31
|
+
modelId: t.String(),
|
|
32
|
+
projectId: t.Optional(t.String())
|
|
33
|
+
}),
|
|
34
|
+
// Loose bag of fields — shape depends on artifactType (see backend/artifacts/generate.ts).
|
|
35
|
+
response: t.Object({ fields: t.Record(t.String(), t.Unknown()) })
|
|
36
|
+
}, async ({ data, conn }) => {
|
|
37
|
+
debug.log('path', `artifacts:generate ${data.artifactType}`);
|
|
38
|
+
if (!data.purpose.trim()) throw new Error('Describe what you want first');
|
|
39
|
+
|
|
40
|
+
// Optional project only decides the engine process cwd; generation has no
|
|
41
|
+
// project side effects. Falls back to the Clopen data dir when absent.
|
|
42
|
+
const projectPath = data.projectId ? requireProjectAccess(conn, data.projectId).path : undefined;
|
|
43
|
+
|
|
44
|
+
const fields = await generateArtifact(data.artifactType as GeneratableType, data.purpose, {
|
|
45
|
+
engine: data.engine as EngineType,
|
|
46
|
+
providerSlug: data.providerSlug,
|
|
47
|
+
modelId: data.modelId,
|
|
48
|
+
projectPath
|
|
49
|
+
});
|
|
50
|
+
return { fields };
|
|
51
|
+
});
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Artifacts Router — cross-cutting artifact operations (AI generation).
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { createRouter } from '$shared/utils/ws-server';
|
|
6
|
+
import { artifactGenerateHandler } from './generate';
|
|
7
|
+
|
|
8
|
+
export const artifactsRouter = createRouter().merge(artifactGenerateHandler);
|
|
@@ -215,7 +215,10 @@ export const streamHandler = createRouter()
|
|
|
215
215
|
sender: t.Object({
|
|
216
216
|
id: t.String(),
|
|
217
217
|
name: t.String()
|
|
218
|
-
})
|
|
218
|
+
}),
|
|
219
|
+
// Active Profile for this session (null = explicit none; absent = use
|
|
220
|
+
// the project default). Persisted like engine/model.
|
|
221
|
+
profileId: t.Optional(t.Union([t.Number(), t.Null()]))
|
|
219
222
|
})
|
|
220
223
|
}, async ({ data, conn }) => {
|
|
221
224
|
requireSessionAccess(conn, data.chatSessionId);
|
|
@@ -234,7 +237,8 @@ export const streamHandler = createRouter()
|
|
|
234
237
|
prompt: data.prompt,
|
|
235
238
|
chatSessionId: data.chatSessionId,
|
|
236
239
|
engine: data.engine,
|
|
237
|
-
sender: data.sender
|
|
240
|
+
sender: data.sender,
|
|
241
|
+
profileId: data.profileId
|
|
238
242
|
});
|
|
239
243
|
|
|
240
244
|
debug.log('chat', 'Stream started with ID:', streamId);
|
|
@@ -855,6 +859,28 @@ export const streamHandler = createRouter()
|
|
|
855
859
|
});
|
|
856
860
|
})
|
|
857
861
|
|
|
862
|
+
// Collaborative profile sync — broadcast + persist the per-session active
|
|
863
|
+
// profile, mirroring chat:model-sync. Non-admin: choosing a profile is a run
|
|
864
|
+
// choice like the model, not an admin mutation of the profile itself.
|
|
865
|
+
.on('chat:profile-sync', {
|
|
866
|
+
data: t.Object({
|
|
867
|
+
senderId: t.String(),
|
|
868
|
+
chatSessionId: t.String(),
|
|
869
|
+
profileId: t.Union([t.Number(), t.Null()])
|
|
870
|
+
})
|
|
871
|
+
}, ({ data, conn }) => {
|
|
872
|
+
requireSessionAccess(conn, data.chatSessionId);
|
|
873
|
+
try {
|
|
874
|
+
sessionQueries.updateProfile(data.chatSessionId, data.profileId);
|
|
875
|
+
} catch (err) {
|
|
876
|
+
debug.error('chat', 'Failed to persist profile sync to DB:', err);
|
|
877
|
+
}
|
|
878
|
+
ws.emit.chatSession(data.chatSessionId, 'chat:profile-sync', {
|
|
879
|
+
senderId: data.senderId,
|
|
880
|
+
profileId: data.profileId
|
|
881
|
+
});
|
|
882
|
+
})
|
|
883
|
+
|
|
858
884
|
// Event declarations
|
|
859
885
|
.emit('chat:edit-mode', t.Object({
|
|
860
886
|
senderId: t.String(),
|
|
@@ -890,6 +916,11 @@ export const streamHandler = createRouter()
|
|
|
890
916
|
accountName: t.Union([t.String(), t.Null()])
|
|
891
917
|
}))
|
|
892
918
|
|
|
919
|
+
.emit('chat:profile-sync', t.Object({
|
|
920
|
+
senderId: t.String(),
|
|
921
|
+
profileId: t.Union([t.Number(), t.Null()])
|
|
922
|
+
}))
|
|
923
|
+
|
|
893
924
|
.emit('chat:connection', t.Object({
|
|
894
925
|
processId: t.String(),
|
|
895
926
|
timestamp: t.String(),
|