@myrialabs/clopen 0.4.8 → 0.4.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/backend/artifacts/detect.ts +129 -0
  2. package/backend/artifacts/engine-map.ts +53 -0
  3. package/backend/artifacts/frontmatter.ts +68 -0
  4. package/backend/artifacts/generate.ts +105 -0
  5. package/backend/artifacts/index.ts +34 -0
  6. package/backend/artifacts/markers.ts +76 -0
  7. package/backend/artifacts/matrix.ts +247 -0
  8. package/backend/artifacts/slug.ts +35 -0
  9. package/backend/artifacts/sync.ts +130 -0
  10. package/backend/artifacts/types.ts +152 -0
  11. package/backend/auth/permissions.ts +51 -1
  12. package/backend/chat/stream-manager.ts +14 -1
  13. package/backend/commands/detect.ts +25 -0
  14. package/backend/commands/index.ts +9 -0
  15. package/backend/commands/service.ts +178 -0
  16. package/backend/commands/store.ts +45 -0
  17. package/backend/commands/sync.ts +94 -0
  18. package/backend/database/migrations/045_create_commands_table.ts +28 -0
  19. package/backend/database/migrations/046_create_subagents_table.ts +29 -0
  20. package/backend/database/migrations/047_create_instructions_table.ts +29 -0
  21. package/backend/database/migrations/048_add_mcp_tool_overrides.ts +23 -0
  22. package/backend/database/migrations/049_create_permission_sets_table.ts +50 -0
  23. package/backend/database/migrations/050_create_profiles_tables.ts +57 -0
  24. package/backend/database/migrations/051_add_profile_to_sessions.ts +20 -0
  25. package/backend/database/migrations/052_add_default_profile_to_projects.ts +20 -0
  26. package/backend/database/migrations/053_add_profile_to_permission_sets.ts +37 -0
  27. package/backend/database/migrations/054_drop_subagent_agent_type.ts +20 -0
  28. package/backend/database/migrations/055_artifact_model_tools_per_engine.ts +43 -0
  29. package/backend/database/migrations/index.ts +77 -0
  30. package/backend/database/queries/command-queries.ts +82 -0
  31. package/backend/database/queries/index.ts +12 -2
  32. package/backend/database/queries/instruction-queries.ts +62 -0
  33. package/backend/database/queries/mcp-server-queries.ts +25 -0
  34. package/backend/database/queries/permission-set-queries.ts +155 -0
  35. package/backend/database/queries/profile-queries.ts +118 -0
  36. package/backend/database/queries/project-queries.ts +14 -0
  37. package/backend/database/queries/session-queries.ts +10 -0
  38. package/backend/database/queries/subagent-queries.ts +92 -0
  39. package/backend/engine/adapters/claude/stream.ts +27 -3
  40. package/backend/engine/adapters/codex/stream.ts +46 -14
  41. package/backend/engine/adapters/copilot/stream.ts +58 -4
  42. package/backend/engine/adapters/opencode/message-converter.ts +22 -2
  43. package/backend/engine/adapters/opencode/server.ts +166 -210
  44. package/backend/engine/adapters/opencode/stream.ts +150 -24
  45. package/backend/engine/adapters/qwen/stream.ts +23 -3
  46. package/backend/engine/artifact-sync.ts +51 -0
  47. package/backend/engine/types.ts +6 -0
  48. package/backend/instructions/index.ts +8 -0
  49. package/backend/instructions/service.ts +63 -0
  50. package/backend/instructions/sync.ts +56 -0
  51. package/backend/mcp/external/config.ts +42 -20
  52. package/backend/mcp/external/proxy.ts +89 -5
  53. package/backend/mcp/external/tools.ts +88 -0
  54. package/backend/mcp/index.ts +38 -15
  55. package/backend/mcp/internal/config.ts +48 -11
  56. package/backend/mcp/internal/remote-server.ts +9 -1
  57. package/backend/permissions/index.ts +27 -0
  58. package/backend/permissions/materialize.ts +96 -0
  59. package/backend/permissions/resolve.test.ts +162 -0
  60. package/backend/permissions/resolve.ts +106 -0
  61. package/backend/permissions/service.ts +167 -0
  62. package/backend/profiles/index.ts +10 -0
  63. package/backend/profiles/service.ts +169 -0
  64. package/backend/skills/index.ts +1 -1
  65. package/backend/skills/sync.ts +88 -128
  66. package/backend/subagents/detect.ts +23 -0
  67. package/backend/subagents/index.ts +10 -0
  68. package/backend/subagents/service.ts +166 -0
  69. package/backend/subagents/store.ts +44 -0
  70. package/backend/subagents/sync.ts +144 -0
  71. package/backend/ws/artifacts/generate.ts +51 -0
  72. package/backend/ws/artifacts/index.ts +8 -0
  73. package/backend/ws/chat/stream.ts +33 -2
  74. package/backend/ws/commands/crud.ts +157 -0
  75. package/backend/ws/commands/index.ts +8 -0
  76. package/backend/ws/git/branch.ts +4 -2
  77. package/backend/ws/git/remote.ts +21 -11
  78. package/backend/ws/index.ts +17 -1
  79. package/backend/ws/instructions/crud.ts +53 -0
  80. package/backend/ws/instructions/index.ts +8 -0
  81. package/backend/ws/mcp/crud.ts +7 -1
  82. package/backend/ws/mcp/index.ts +4 -1
  83. package/backend/ws/mcp/tools.ts +112 -0
  84. package/backend/ws/permissions/crud.ts +72 -0
  85. package/backend/ws/permissions/index.ts +8 -0
  86. package/backend/ws/profiles/crud.ts +149 -0
  87. package/backend/ws/profiles/index.ts +9 -0
  88. package/backend/ws/subagents/crud.ts +136 -0
  89. package/backend/ws/subagents/index.ts +8 -0
  90. package/dist/assets/{index-jGo0X72U.js → index-BdRui-1z.js} +1 -1
  91. package/dist/assets/{index-B_F_OgoC.js → index-BjaIjmd4.js} +1 -1
  92. package/dist/assets/{main-BkCc3WEB.js → main-Cf8SUfQ1.js} +367 -315
  93. package/dist/assets/main-D4pdkiQK.css +1 -0
  94. package/dist/index.html +2 -2
  95. package/package.json +1 -1
  96. package/shared/constants/engine-tools.ts +56 -0
  97. package/shared/types/database/schema.ts +2 -0
  98. package/shared/types/stores/settings.ts +15 -0
  99. package/shared/types/unified/stream.ts +7 -0
  100. package/shared/utils/logger.ts +6 -0
  101. package/dist/assets/main-CWDwET4x.css +0 -1
@@ -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
+ }
@@ -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(),
@@ -0,0 +1,157 @@
1
+ /**
2
+ * Command CRUD Handlers (Settings → Commands)
3
+ *
4
+ * - commands:list / get / create / update / parse-import / import / toggle / delete
5
+ * - commands:detect — on-disk commands (managed + adoptable) per engine
6
+ *
7
+ * Mutations are admin-gated. Changes take effect on the next chat stream, when
8
+ * each engine re-syncs its commands.
9
+ */
10
+
11
+ import { t } from 'elysia';
12
+ import { createRouter } from '$shared/utils/ws-server';
13
+ import { debug } from '$shared/utils/logger';
14
+ import { commandService, detectCommands, syncCommandsAllEngines } from '$backend/commands';
15
+ import { resolveActiveProfileId, artifactFilter } from '$backend/profiles';
16
+
17
+ /** EngineType → value map (model id / tool list). {} = inherit / all. */
18
+ const ENGINE_MAP_SCHEMA = t.Record(t.String(), t.String());
19
+
20
+ const COMMAND_SCHEMA = t.Object({
21
+ id: t.Number(),
22
+ slug: t.String(),
23
+ name: t.String(),
24
+ description: t.String(),
25
+ argumentHint: t.Union([t.String(), t.Null()]),
26
+ modelByEngine: ENGINE_MAP_SCHEMA,
27
+ source: t.Union([t.Literal('custom'), t.Literal('imported')]),
28
+ enabled: t.Boolean(),
29
+ present: t.Boolean(),
30
+ createdAt: t.String()
31
+ });
32
+
33
+ const FIELDS_SCHEMA = {
34
+ name: t.String(),
35
+ description: t.String(),
36
+ argumentHint: t.Optional(t.Union([t.String(), t.Null()])),
37
+ modelByEngine: t.Optional(ENGINE_MAP_SCHEMA),
38
+ body: t.String()
39
+ };
40
+
41
+ const DETECTED_SCHEMA = t.Object({
42
+ engine: t.String(),
43
+ detected: t.Array(t.Object({
44
+ slug: t.String(),
45
+ name: t.String(),
46
+ description: t.String(),
47
+ path: t.String(),
48
+ managed: t.Boolean(),
49
+ adoptable: t.Boolean()
50
+ }))
51
+ });
52
+
53
+ export const commandCrudHandler = createRouter()
54
+ .http('commands:list', {
55
+ data: t.Object({}),
56
+ response: t.Object({ commands: t.Array(COMMAND_SCHEMA) })
57
+ }, async () => {
58
+ debug.log('path', 'commands:list');
59
+ return { commands: await commandService.list() };
60
+ })
61
+ .http('commands:get', {
62
+ data: t.Object({ id: t.Number() }),
63
+ response: t.Object({ command: COMMAND_SCHEMA, body: t.String() })
64
+ }, async ({ data }) => {
65
+ debug.log('path', `commands:get ${data.id}`);
66
+ const result = await commandService.get(data.id);
67
+ if (!result) throw new Error('Command not found');
68
+ return result;
69
+ })
70
+ .http('commands:create', {
71
+ data: t.Object(FIELDS_SCHEMA),
72
+ response: t.Object({ command: COMMAND_SCHEMA })
73
+ }, async ({ data }) => {
74
+ debug.log('path', `commands:create ${data.name}`);
75
+ if (!data.name.trim()) throw new Error('A command name is required');
76
+ const command = await commandService.create(data);
77
+ await syncCommandsAllEngines();
78
+ return { command };
79
+ })
80
+ .http('commands:update', {
81
+ data: t.Object({ id: t.Number(), ...FIELDS_SCHEMA }),
82
+ response: t.Object({ command: COMMAND_SCHEMA })
83
+ }, async ({ data }) => {
84
+ debug.log('path', `commands:update ${data.id}`);
85
+ if (!data.name.trim()) throw new Error('A command name is required');
86
+ const command = await commandService.update(data.id, data);
87
+ await syncCommandsAllEngines();
88
+ return { command };
89
+ })
90
+ .http('commands:parse-import', {
91
+ data: t.Object({ text: t.String() }),
92
+ response: t.Object({
93
+ name: t.String(),
94
+ description: t.String(),
95
+ argumentHint: t.Union([t.String(), t.Null()]),
96
+ modelByEngine: ENGINE_MAP_SCHEMA,
97
+ body: t.String()
98
+ })
99
+ }, async ({ data }) => {
100
+ debug.log('path', 'commands:parse-import');
101
+ return commandService.parsePreview(data.text);
102
+ })
103
+ .http('commands:import', {
104
+ data: t.Object({ text: t.String(), name: t.Optional(t.String()) }),
105
+ response: t.Object({ command: COMMAND_SCHEMA })
106
+ }, async ({ data }) => {
107
+ debug.log('path', 'commands:import');
108
+ const command = await commandService.import(data.text, data.name);
109
+ await syncCommandsAllEngines();
110
+ return { command };
111
+ })
112
+ .http('commands:toggle', {
113
+ data: t.Object({ id: t.Number(), enabled: t.Boolean() }),
114
+ response: t.Object({ command: COMMAND_SCHEMA })
115
+ }, async ({ data }) => {
116
+ debug.log('path', `commands:toggle ${data.id} → ${data.enabled}`);
117
+ const command = commandService.toggle(data.id, data.enabled);
118
+ await syncCommandsAllEngines();
119
+ return { command };
120
+ })
121
+ .http('commands:delete', {
122
+ data: t.Object({ id: t.Number() }),
123
+ response: t.Object({ success: t.Boolean() })
124
+ }, async ({ data }) => {
125
+ debug.log('path', `commands:delete ${data.id}`);
126
+ await commandService.remove(data.id);
127
+ await syncCommandsAllEngines();
128
+ return { success: true };
129
+ })
130
+ .http('commands:available', {
131
+ // Non-admin: commands for the chat "/" picker (display fields only),
132
+ // narrowed by the session's active profile (if any) same as stream sync.
133
+ data: t.Object({
134
+ profileId: t.Optional(t.Union([t.Number(), t.Null()])),
135
+ projectId: t.Optional(t.String())
136
+ }),
137
+ response: t.Object({
138
+ commands: t.Array(t.Object({
139
+ slug: t.String(),
140
+ name: t.String(),
141
+ description: t.String(),
142
+ argumentHint: t.Union([t.String(), t.Null()])
143
+ }))
144
+ })
145
+ }, async ({ data }) => {
146
+ debug.log('path', 'commands:available');
147
+ const activeProfileId = resolveActiveProfileId(data.profileId ?? null, data.projectId);
148
+ const filter = artifactFilter(activeProfileId, 'command');
149
+ return { commands: commandService.available(filter) };
150
+ })
151
+ .http('commands:detect', {
152
+ data: t.Object({ projectPath: t.Optional(t.String()) }),
153
+ response: t.Object({ groups: t.Array(DETECTED_SCHEMA) })
154
+ }, async ({ data }) => {
155
+ debug.log('path', 'commands:detect');
156
+ return { groups: await detectCommands(data.projectPath) };
157
+ });
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Commands Router — Settings → Commands CRUD + on-disk detection.
3
+ */
4
+
5
+ import { createRouter } from '$shared/utils/ws-server';
6
+ import { commandCrudHandler } from './crud';
7
+
8
+ export const commandsRouter = createRouter().merge(commandCrudHandler);
@@ -142,12 +142,14 @@ export const branchHandler = createRouter()
142
142
  data: t.Object({
143
143
  projectId: t.String(),
144
144
  oldName: t.String(),
145
- newName: t.String({ minLength: 1 })
145
+ newName: t.String({ minLength: 1 }),
146
+ repoPath: t.Optional(t.String())
146
147
  }),
147
148
  response: t.Object({ ok: t.Boolean() })
148
149
  }, async ({ data, conn }) => {
149
150
  const project = requireProjectAccess(conn, data.projectId);
150
- await gitService.renameBranch(project.path, data.oldName, data.newName);
151
+ const cwd = resolveRepoCwd(project.path, data.repoPath);
152
+ await gitService.renameBranch(cwd, data.oldName, data.newName);
151
153
  return { ok: true };
152
154
  })
153
155
 
@@ -136,12 +136,14 @@ export const remoteHandler = createRouter()
136
136
  data: t.Object({
137
137
  projectId: t.String(),
138
138
  name: t.String(),
139
- url: t.String()
139
+ url: t.String(),
140
+ repoPath: t.Optional(t.String())
140
141
  }),
141
142
  response: t.Object({ ok: t.Boolean() })
142
143
  }, async ({ data, conn }) => {
143
144
  const project = requireProjectAccess(conn, data.projectId);
144
- await gitService.addRemote(project.path, data.name, data.url);
145
+ const cwd = resolveRepoCwd(project.path, data.repoPath);
146
+ await gitService.addRemote(cwd, data.name, data.url);
145
147
  return { ok: true };
146
148
  })
147
149
 
@@ -149,12 +151,14 @@ export const remoteHandler = createRouter()
149
151
  data: t.Object({
150
152
  projectId: t.String(),
151
153
  name: t.String(),
152
- url: t.String()
154
+ url: t.String(),
155
+ repoPath: t.Optional(t.String())
153
156
  }),
154
157
  response: t.Object({ ok: t.Boolean() })
155
158
  }, async ({ data, conn }) => {
156
159
  const project = requireProjectAccess(conn, data.projectId);
157
- await gitService.setRemoteUrl(project.path, data.name, data.url);
160
+ const cwd = resolveRepoCwd(project.path, data.repoPath);
161
+ await gitService.setRemoteUrl(cwd, data.name, data.url);
158
162
  return { ok: true };
159
163
  })
160
164
 
@@ -162,12 +166,14 @@ export const remoteHandler = createRouter()
162
166
  data: t.Object({
163
167
  projectId: t.String(),
164
168
  oldName: t.String(),
165
- newName: t.String()
169
+ newName: t.String(),
170
+ repoPath: t.Optional(t.String())
166
171
  }),
167
172
  response: t.Object({ ok: t.Boolean() })
168
173
  }, async ({ data, conn }) => {
169
174
  const project = requireProjectAccess(conn, data.projectId);
170
- await gitService.renameRemote(project.path, data.oldName, data.newName);
175
+ const cwd = resolveRepoCwd(project.path, data.repoPath);
176
+ await gitService.renameRemote(cwd, data.oldName, data.newName);
171
177
  return { ok: true };
172
178
  })
173
179
 
@@ -176,27 +182,31 @@ export const remoteHandler = createRouter()
176
182
  projectId: t.String(),
177
183
  oldName: t.String(),
178
184
  newName: t.String(),
179
- newUrl: t.String()
185
+ newUrl: t.String(),
186
+ repoPath: t.Optional(t.String())
180
187
  }),
181
188
  response: t.Object({ ok: t.Boolean() })
182
189
  }, async ({ data, conn }) => {
183
190
  const project = requireProjectAccess(conn, data.projectId);
191
+ const cwd = resolveRepoCwd(project.path, data.repoPath);
184
192
  if (data.oldName !== data.newName) {
185
- await gitService.renameRemote(project.path, data.oldName, data.newName);
193
+ await gitService.renameRemote(cwd, data.oldName, data.newName);
186
194
  }
187
- await gitService.setRemoteUrl(project.path, data.newName, data.newUrl);
195
+ await gitService.setRemoteUrl(cwd, data.newName, data.newUrl);
188
196
  return { ok: true };
189
197
  })
190
198
 
191
199
  .http('git:remove-remote', {
192
200
  data: t.Object({
193
201
  projectId: t.String(),
194
- name: t.String()
202
+ name: t.String(),
203
+ repoPath: t.Optional(t.String())
195
204
  }),
196
205
  response: t.Object({ ok: t.Boolean() })
197
206
  }, async ({ data, conn }) => {
198
207
  const project = requireProjectAccess(conn, data.projectId);
199
- await gitService.removeRemote(project.path, data.name);
208
+ const cwd = resolveRepoCwd(project.path, data.repoPath);
209
+ await gitService.removeRemote(cwd, data.name);
200
210
  return { ok: true };
201
211
  })
202
212
 
@@ -33,6 +33,12 @@ import { systemToolsRouter } from './system-tools';
33
33
  import { dbClientRouter } from './db-client';
34
34
  import { mcpRouter } from './mcp';
35
35
  import { skillsRouter } from './skills';
36
+ import { commandsRouter } from './commands';
37
+ import { subagentsRouter } from './subagents';
38
+ import { instructionsRouter } from './instructions';
39
+ import { permissionsRouter } from './permissions';
40
+ import { profilesRouter } from './profiles';
41
+ import { artifactsRouter } from './artifacts';
36
42
 
37
43
  // ============================================
38
44
  // Main App Router - Merge All Module Routers
@@ -81,7 +87,17 @@ export const wsRouter = createRouter()
81
87
  .merge(mcpRouter)
82
88
 
83
89
  // Agent Skills management (create, import, install from a marketplace)
84
- .merge(skillsRouter);
90
+ .merge(skillsRouter)
91
+
92
+ // Custom Commands, Subagents, and Project Instructions (artifact framework)
93
+ .merge(commandsRouter)
94
+ .merge(subagentsRouter)
95
+ .merge(instructionsRouter)
96
+ .merge(permissionsRouter)
97
+
98
+ // Profiles (reusable artifact bundles activated per-session)
99
+ .merge(profilesRouter)
100
+ .merge(artifactsRouter);
85
101
 
86
102
  // Export API type for frontend type-safe access
87
103
  export type WSAPI = typeof wsRouter['$api'];
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Instruction Handlers (Settings → Instructions)
3
+ *
4
+ * - instructions:get-global / save-global
5
+ * - instructions:get-project / save-project
6
+ *
7
+ * The managed block is injected into each engine's memory file as a
8
+ * marker-region; hand-written content is preserved. Mutations are admin-gated.
9
+ */
10
+
11
+ import { t } from 'elysia';
12
+ import { createRouter } from '$shared/utils/ws-server';
13
+ import { debug } from '$shared/utils/logger';
14
+ import { instructionService } from '$backend/instructions';
15
+
16
+ const INSTRUCTION_SCHEMA = t.Object({
17
+ scope: t.Union([t.Literal('global'), t.Literal('project')]),
18
+ projectId: t.Union([t.String(), t.Null()]),
19
+ content: t.String(),
20
+ enabled: t.Boolean(),
21
+ updatedAt: t.Union([t.String(), t.Null()]),
22
+ engineFiles: t.Array(t.Object({ engine: t.String(), fileName: t.String() }))
23
+ });
24
+
25
+ export const instructionCrudHandler = createRouter()
26
+ .http('instructions:get-global', {
27
+ data: t.Object({}),
28
+ response: t.Object({ instruction: INSTRUCTION_SCHEMA })
29
+ }, async () => {
30
+ debug.log('path', 'instructions:get-global');
31
+ return { instruction: instructionService.getGlobal() };
32
+ })
33
+ .http('instructions:save-global', {
34
+ data: t.Object({ content: t.String(), enabled: t.Boolean() }),
35
+ response: t.Object({ instruction: INSTRUCTION_SCHEMA })
36
+ }, async ({ data }) => {
37
+ debug.log('path', 'instructions:save-global');
38
+ return { instruction: instructionService.saveGlobal(data.content, data.enabled) };
39
+ })
40
+ .http('instructions:get-project', {
41
+ data: t.Object({ projectId: t.String() }),
42
+ response: t.Object({ instruction: INSTRUCTION_SCHEMA })
43
+ }, async ({ data }) => {
44
+ debug.log('path', `instructions:get-project ${data.projectId}`);
45
+ return { instruction: instructionService.getForProject(data.projectId) };
46
+ })
47
+ .http('instructions:save-project', {
48
+ data: t.Object({ projectId: t.String(), content: t.String(), enabled: t.Boolean() }),
49
+ response: t.Object({ instruction: INSTRUCTION_SCHEMA })
50
+ }, async ({ data }) => {
51
+ debug.log('path', `instructions:save-project ${data.projectId}`);
52
+ return { instruction: instructionService.saveForProject(data.projectId, data.content, data.enabled) };
53
+ });
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Instructions Router — Settings → Instructions (global + per-project blocks).
3
+ */
4
+
5
+ import { createRouter } from '$shared/utils/ws-server';
6
+ import { instructionCrudHandler } from './crud';
7
+
8
+ export const instructionsRouter = createRouter().merge(instructionCrudHandler);