@myrialabs/clopen 0.4.7 → 0.4.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) 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/db-client/drivers/mysql.ts +21 -0
  40. package/backend/db-client/drivers/postgres.ts +20 -0
  41. package/backend/db-client/drivers/sqlite.ts +21 -0
  42. package/backend/db-client/drivers/types.ts +19 -0
  43. package/backend/db-client/query-executor.ts +89 -1
  44. package/backend/engine/adapters/claude/stream.ts +27 -3
  45. package/backend/engine/adapters/codex/stream.ts +46 -14
  46. package/backend/engine/adapters/copilot/stream.ts +58 -4
  47. package/backend/engine/adapters/opencode/message-converter.ts +22 -2
  48. package/backend/engine/adapters/opencode/server.ts +166 -210
  49. package/backend/engine/adapters/opencode/stream.ts +150 -24
  50. package/backend/engine/adapters/qwen/stream.ts +23 -3
  51. package/backend/engine/artifact-sync.ts +51 -0
  52. package/backend/engine/types.ts +6 -0
  53. package/backend/instructions/index.ts +8 -0
  54. package/backend/instructions/service.ts +63 -0
  55. package/backend/instructions/sync.ts +56 -0
  56. package/backend/mcp/external/config.ts +42 -20
  57. package/backend/mcp/external/proxy.ts +89 -5
  58. package/backend/mcp/external/tools.ts +88 -0
  59. package/backend/mcp/index.ts +38 -15
  60. package/backend/mcp/internal/config.ts +48 -11
  61. package/backend/mcp/internal/remote-server.ts +9 -1
  62. package/backend/permissions/index.ts +27 -0
  63. package/backend/permissions/materialize.ts +96 -0
  64. package/backend/permissions/resolve.test.ts +162 -0
  65. package/backend/permissions/resolve.ts +106 -0
  66. package/backend/permissions/service.ts +167 -0
  67. package/backend/profiles/index.ts +10 -0
  68. package/backend/profiles/service.ts +169 -0
  69. package/backend/skills/index.ts +1 -1
  70. package/backend/skills/sync.ts +88 -128
  71. package/backend/subagents/detect.ts +23 -0
  72. package/backend/subagents/index.ts +10 -0
  73. package/backend/subagents/service.ts +166 -0
  74. package/backend/subagents/store.ts +44 -0
  75. package/backend/subagents/sync.ts +144 -0
  76. package/backend/ws/artifacts/generate.ts +51 -0
  77. package/backend/ws/artifacts/index.ts +8 -0
  78. package/backend/ws/chat/stream.ts +33 -2
  79. package/backend/ws/commands/crud.ts +157 -0
  80. package/backend/ws/commands/index.ts +8 -0
  81. package/backend/ws/db-client/query-history-retention.test.ts +217 -0
  82. package/backend/ws/db-client/query.ts +77 -2
  83. package/backend/ws/git/branch.ts +4 -2
  84. package/backend/ws/git/ignored.ts +65 -0
  85. package/backend/ws/git/index.ts +3 -1
  86. package/backend/ws/git/remote.ts +21 -11
  87. package/backend/ws/index.ts +17 -1
  88. package/backend/ws/instructions/crud.ts +53 -0
  89. package/backend/ws/instructions/index.ts +8 -0
  90. package/backend/ws/mcp/crud.ts +7 -1
  91. package/backend/ws/mcp/index.ts +4 -1
  92. package/backend/ws/mcp/tools.ts +112 -0
  93. package/backend/ws/permissions/crud.ts +72 -0
  94. package/backend/ws/permissions/index.ts +8 -0
  95. package/backend/ws/profiles/crud.ts +149 -0
  96. package/backend/ws/profiles/index.ts +9 -0
  97. package/backend/ws/subagents/crud.ts +136 -0
  98. package/backend/ws/subagents/index.ts +8 -0
  99. package/dist/assets/__vite-browser-external-BIHI7g3E.js +1 -0
  100. package/dist/assets/index-BdRui-1z.js +1 -0
  101. package/dist/assets/{index-xrB3zcfA.js → index-BjaIjmd4.js} +1 -1
  102. package/dist/assets/{main-LBI3a0n5.js → main-Cf8SUfQ1.js} +387 -302
  103. package/dist/assets/main-D4pdkiQK.css +1 -0
  104. package/dist/assets/zipkit-engine-CaR0t_Uy.wasm +0 -0
  105. package/dist/index.html +2 -2
  106. package/package.json +1 -1
  107. package/shared/constants/engine-tools.ts +56 -0
  108. package/shared/types/database/schema.ts +2 -0
  109. package/shared/types/db-client/query.ts +33 -0
  110. package/shared/types/stores/settings.ts +15 -0
  111. package/shared/types/unified/stream.ts +7 -0
  112. package/shared/utils/db-client/split-sql.test.ts +88 -0
  113. package/shared/utils/db-client/split-sql.ts +132 -0
  114. package/shared/utils/logger.ts +6 -0
  115. package/dist/assets/main-BXS8bjJ6.css +0 -1
@@ -3,14 +3,20 @@
3
3
  */
4
4
 
5
5
  import { t } from 'elysia';
6
+ import type { DbClientQueryResult } from '$shared/types/db-client';
6
7
  import { createRouter } from '$shared/utils/ws-server';
7
8
  import { connectionManager } from '../../db-client/connection-manager';
8
- import { runSafely } from '../../db-client/query-executor';
9
+ import { executeBatch, runSafely } from '../../db-client/query-executor';
10
+ import { splitSqlStatements } from '$shared/utils/db-client/split-sql';
9
11
  import { dbClientQueryHistoryQueries } from '../../database/queries';
10
12
  import { getDbClientPrincipal, requireDbClientConnectionAccess } from './access';
11
13
  import { debug } from '$shared/utils/logger';
12
14
 
13
15
  const HISTORY_KEEP_PER_CONNECTION = 200;
16
+ const PRUNE_EVERY_N_QUERIES = 10;
17
+
18
+ // Track insert count per connection for deterministic pruning
19
+ const insertCounters = new Map<string, number>();
14
20
 
15
21
  function recordHistory(input: {
16
22
  connectionId: string;
@@ -31,8 +37,14 @@ function recordHistory(input: {
31
37
  status: input.status,
32
38
  error: input.error
33
39
  });
34
- if (Math.random() < 0.05) {
40
+
41
+ // Deterministic pruning: prune after every N inserts
42
+ const count = (insertCounters.get(input.connectionId) ?? 0) + 1;
43
+ insertCounters.set(input.connectionId, count);
44
+
45
+ if (count >= PRUNE_EVERY_N_QUERIES) {
35
46
  dbClientQueryHistoryQueries.prune(input.connectionId, HISTORY_KEEP_PER_CONNECTION);
47
+ insertCounters.set(input.connectionId, 0);
36
48
  }
37
49
  } catch (err) {
38
50
  // history must never break query execution
@@ -133,6 +145,69 @@ export const queryHandler = createRouter()
133
145
  }
134
146
  })
135
147
 
148
+ .http('db-client:execute-batch', {
149
+ data: t.Object({
150
+ connectionId: t.String({ minLength: 1 }),
151
+ query: t.String({ minLength: 1 }),
152
+ params: t.Optional(t.Array(t.Any())),
153
+ database: t.Optional(t.String()),
154
+ limit: t.Optional(t.Number())
155
+ }),
156
+ response: t.Any()
157
+ }, async ({ data, conn }) => {
158
+ const { userId } = getDbClientPrincipal(conn);
159
+ const connection = requireDbClientConnectionAccess(conn, data.connectionId);
160
+ const adapter = await connectionManager.get(data.connectionId);
161
+ // Statement splitting is a SQL concern; Mongo/Redis payloads run whole.
162
+ const isSql = connection.driver === 'mysql' || connection.driver === 'postgres' || connection.driver === 'sqlite';
163
+ const split = isSql ? splitSqlStatements(data.query) : [data.query.trim()];
164
+ const statements = split.length > 0 ? split : [data.query.trim()];
165
+ try {
166
+ const batch = await executeBatch({
167
+ driver: connection.driver,
168
+ adapter,
169
+ statements,
170
+ params: data.params,
171
+ database: data.database,
172
+ limit: data.limit
173
+ });
174
+ const rowCount = batch.statements.reduce((acc, s) => acc + (s.result?.rowCount ?? 0), 0);
175
+ const affectedRows = batch.statements.reduce((acc, s) => acc + (s.result?.affectedRows ?? 0), 0);
176
+ const failed = batch.statements.find((s) => s.status === 'error');
177
+ recordHistory({
178
+ connectionId: data.connectionId,
179
+ userId,
180
+ query: data.query,
181
+ status: batch.ok ? 'success' : 'error',
182
+ durationMs: batch.totalDurationMs,
183
+ rowCount,
184
+ error: failed?.error ?? null
185
+ });
186
+ // Mirror the last statement that produced rows at the top level (so
187
+ // existing single-result consumers keep working) with the full
188
+ // per-statement report attached under `batch`.
189
+ const reversed = [...batch.statements].reverse();
190
+ const lastResult = reversed.find((s) => s.result && s.result.rows.length > 0)?.result
191
+ ?? reversed.find((s) => s.result)?.result
192
+ ?? null;
193
+ const top: DbClientQueryResult = lastResult
194
+ ? { ...lastResult, durationMs: batch.totalDurationMs, batch }
195
+ : { columns: [], rows: [], rowCount, affectedRows, durationMs: batch.totalDurationMs, driverMeta: {}, batch };
196
+ return top;
197
+ } catch (error) {
198
+ recordHistory({
199
+ connectionId: data.connectionId,
200
+ userId,
201
+ query: data.query,
202
+ status: 'error',
203
+ durationMs: null,
204
+ rowCount: null,
205
+ error: error instanceof Error ? error.message : String(error)
206
+ });
207
+ throw error;
208
+ }
209
+ })
210
+
136
211
  .http('db-client:explain', {
137
212
  data: t.Object({
138
213
  connectionId: t.String({ minLength: 1 }),
@@ -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
 
@@ -0,0 +1,65 @@
1
+ import { t } from 'elysia';
2
+ import { createRouter } from '$shared/utils/ws-server';
3
+ import { execGit } from '../../git/git-executor';
4
+ import { requireProjectAccess } from '../access';
5
+ import path from 'path';
6
+
7
+ export const ignoredHandler = createRouter()
8
+ .http('git:ignored-paths', {
9
+ data: t.Object({
10
+ projectId: t.String()
11
+ }),
12
+ response: t.Object({
13
+ ignored: t.Array(t.String())
14
+ })
15
+ }, async ({ data, conn }) => {
16
+ const project = requireProjectAccess(conn, data.projectId);
17
+ const ignored: string[] = [];
18
+
19
+ try {
20
+ const isRepo = await execGit(['rev-parse', '--is-inside-work-tree'], project.path, 5_000)
21
+ .then(r => r.exitCode === 0)
22
+ .catch(() => false);
23
+
24
+ if (!isRepo) return { ignored };
25
+
26
+ // Get ignored files (leaf paths)
27
+ const filesResult = await execGit(
28
+ ['ls-files', '--others', '--ignored', '--exclude-standard'],
29
+ project.path,
30
+ 30_000
31
+ );
32
+ if (filesResult.exitCode === 0) {
33
+ const sep = project.path.includes('\\') ? '\\' : '/';
34
+ for (const line of filesResult.stdout.split('\n')) {
35
+ const relPath = line.trim();
36
+ if (!relPath) continue;
37
+ ignored.push(path.join(project.path, relPath.replace(/\//g, sep)));
38
+ }
39
+ }
40
+
41
+ // Get ignored directories (shown with --directory flag)
42
+ const dirsResult = await execGit(
43
+ ['ls-files', '--others', '--ignored', '--exclude-standard', '--directory'],
44
+ project.path,
45
+ 30_000
46
+ );
47
+ if (dirsResult.exitCode === 0) {
48
+ const seen = new Set(ignored);
49
+ const sep = project.path.includes('\\') ? '\\' : '/';
50
+ for (const line of dirsResult.stdout.split('\n')) {
51
+ const relPath = line.trim().replace(/\/$/, '');
52
+ if (!relPath) continue;
53
+ const absPath = path.join(project.path, relPath.replace(/\//g, sep));
54
+ if (!seen.has(absPath)) {
55
+ ignored.push(absPath);
56
+ seen.add(absPath);
57
+ }
58
+ }
59
+ }
60
+ } catch {
61
+ // If git fails, return empty
62
+ }
63
+
64
+ return { ignored };
65
+ });
@@ -14,6 +14,7 @@ import { remoteHandler } from './remote';
14
14
  import { conflictHandler } from './conflict';
15
15
  import { commitMessageHandler } from './commit-message';
16
16
  import { branchNameHandler } from './branch-name';
17
+ import { ignoredHandler } from './ignored';
17
18
 
18
19
  export const gitRouter = createRouter()
19
20
  .merge(statusHandler)
@@ -25,4 +26,5 @@ export const gitRouter = createRouter()
25
26
  .merge(remoteHandler)
26
27
  .merge(conflictHandler)
27
28
  .merge(commitMessageHandler)
28
- .merge(branchNameHandler);
29
+ .merge(branchNameHandler)
30
+ .merge(ignoredHandler);
@@ -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);
@@ -24,7 +24,8 @@ import {
24
24
  startAuthorization,
25
25
  completeAuthorization,
26
26
  getValidAccessToken,
27
- parseMcpConfig
27
+ parseMcpConfig,
28
+ parseToolOverrides
28
29
  } from '$backend/mcp';
29
30
 
30
31
  const TRANSPORT_SCHEMA = t.Union([t.Literal('stdio'), t.Literal('http'), t.Literal('sse')]);
@@ -59,6 +60,9 @@ const INSTALLED_SERVER_SCHEMA = t.Object({
59
60
  url: t.Union([t.String(), t.Null()]),
60
61
  source: t.String(),
61
62
  enabled: t.Boolean(),
63
+ // Number of tools with a stored exposure restriction — drives a "N restricted"
64
+ // badge without a per-server upstream round-trip. The details live in mcp:tools.
65
+ restrictedToolCount: t.Number(),
62
66
  createdAt: t.String()
63
67
  });
64
68
 
@@ -71,6 +75,7 @@ function toDTO(row: McpServerRow) {
71
75
  try { env = JSON.parse(row.env); } catch { /* ignore */ }
72
76
  try { headers = JSON.parse(row.headers); } catch { /* ignore */ }
73
77
  try { configSchema = JSON.parse(row.config_schema); } catch { /* ignore */ }
78
+ const restrictedToolCount = Object.keys(parseToolOverrides(row.tool_overrides)).length;
74
79
  return {
75
80
  id: row.id,
76
81
  slug: row.slug,
@@ -88,6 +93,7 @@ function toDTO(row: McpServerRow) {
88
93
  url: row.url,
89
94
  source: row.source,
90
95
  enabled: row.is_enabled === 1,
96
+ restrictedToolCount,
91
97
  createdAt: row.created_at
92
98
  };
93
99
  }
@@ -4,6 +4,7 @@
4
4
  * Entry point for external (user-installed) MCP server management:
5
5
  * - mcp:catalog — browse the official MCP registry
6
6
  * - mcp:list / install / toggle / uninstall — manage installed servers
7
+ * - mcp:tools / set-tool-overrides / call-tool — per-tool control + inspector
7
8
  *
8
9
  * Internal custom-tool servers (backend/mcp/internal) are NOT managed here —
9
10
  * they are defined in code.
@@ -12,7 +13,9 @@
12
13
  import { createRouter } from '$shared/utils/ws-server';
13
14
  import { mcpCatalogHandler } from './catalog';
14
15
  import { mcpCrudHandler } from './crud';
16
+ import { mcpToolsHandler } from './tools';
15
17
 
16
18
  export const mcpRouter = createRouter()
17
19
  .merge(mcpCatalogHandler)
18
- .merge(mcpCrudHandler);
20
+ .merge(mcpCrudHandler)
21
+ .merge(mcpToolsHandler);
@@ -0,0 +1,112 @@
1
+ /**
2
+ * MCP Tool-level Control + Inspector Handlers
3
+ *
4
+ * Deepens the installed-server surface with per-tool control and a playground:
5
+ * - mcp:tools — list a server's live tools + their exposure state
6
+ * - mcp:set-tool-overrides — persist per-tool + per-engine enable state
7
+ * - mcp:call-tool — inspector: invoke one tool and return its result
8
+ *
9
+ * All three go through the SAME upstream introspection path the bridge uses
10
+ * (`backend/mcp/external/proxy.ts`), so what Settings shows matches what the
11
+ * engines receive. Mutations are admin-gated in `backend/auth/permissions.ts`.
12
+ */
13
+
14
+ import { t } from 'elysia';
15
+ import { createRouter } from '$shared/utils/ws-server';
16
+ import { debug } from '$shared/utils/logger';
17
+ import { mcpServerQueries, type McpToolOverrides } from '$backend/database/queries';
18
+ import {
19
+ listExternalServerTools,
20
+ callExternalServerTool,
21
+ parseToolOverrides,
22
+ resolveToolExposure,
23
+ pruneToolOverrides,
24
+ getValidAccessToken
25
+ } from '$backend/mcp';
26
+
27
+ /** A single per-tool override the client sends back (only restrictions matter). */
28
+ const TOOL_OVERRIDE_SCHEMA = t.Object({
29
+ enabled: t.Optional(t.Boolean()),
30
+ engines: t.Optional(t.Record(t.String(), t.Boolean()))
31
+ });
32
+
33
+ /**
34
+ * Load a non-internal server by id, or throw. External MCP introspection makes
35
+ * no sense for the in-process internal servers (their tools are code-defined).
36
+ */
37
+ function requireExternal(id: number) {
38
+ const row = mcpServerQueries.getById(id);
39
+ if (!row) throw new Error('MCP server not found');
40
+ if (row.source === 'internal') throw new Error('Built-in MCP servers cannot be inspected');
41
+ return row;
42
+ }
43
+
44
+ /** Refresh a near-expiry OAuth token so the live upstream connection authenticates. */
45
+ async function ensureFreshToken(id: number, hasOAuth: boolean): Promise<void> {
46
+ if (hasOAuth) await getValidAccessToken(id);
47
+ }
48
+
49
+ export const mcpToolsHandler = createRouter()
50
+ .http('mcp:tools', {
51
+ data: t.Object({ id: t.Number() }),
52
+ response: t.Object({
53
+ tools: t.Array(t.Object({
54
+ name: t.String(),
55
+ description: t.Optional(t.String()),
56
+ inputSchema: t.Any(),
57
+ // Effective exposure resolved from stored overrides (default: all on).
58
+ enabled: t.Boolean(),
59
+ engines: t.Record(t.String(), t.Boolean())
60
+ }))
61
+ })
62
+ }, async ({ data }) => {
63
+ debug.log('path', `mcp:tools ${data.id}`);
64
+ const row = requireExternal(data.id);
65
+ await ensureFreshToken(row.id, !!row.oauth);
66
+ const live = await listExternalServerTools(row.slug);
67
+ const overrides = parseToolOverrides(row.tool_overrides);
68
+ return {
69
+ tools: live.map(tool => {
70
+ const exposure = resolveToolExposure(overrides[tool.name]);
71
+ return {
72
+ name: tool.name,
73
+ description: tool.description,
74
+ inputSchema: tool.inputSchema,
75
+ enabled: exposure.enabled,
76
+ engines: exposure.engines
77
+ };
78
+ })
79
+ };
80
+ })
81
+ .http('mcp:set-tool-overrides', {
82
+ data: t.Object({
83
+ id: t.Number(),
84
+ overrides: t.Record(t.String(), TOOL_OVERRIDE_SCHEMA)
85
+ }),
86
+ response: t.Object({ success: t.Boolean() })
87
+ }, async ({ data }) => {
88
+ debug.log('path', `mcp:set-tool-overrides ${data.id}`);
89
+ const row = requireExternal(data.id);
90
+ // Prune no-op entries so the column only ever stores real restrictions.
91
+ const overrides = pruneToolOverrides(data.overrides as McpToolOverrides);
92
+ mcpServerQueries.updateToolOverrides(row.id, overrides);
93
+ debug.log('mcp', `🎛️ Updated tool exposure for external MCP server: ${row.slug} (${Object.keys(overrides).length} restricted)`);
94
+ return { success: true };
95
+ })
96
+ .http('mcp:call-tool', {
97
+ // Inspector / playground: invoke one tool with the given arguments and
98
+ // return its raw MCP result (including `isError` results, so the UI can
99
+ // render tool-reported failures). Connection failures throw.
100
+ data: t.Object({
101
+ id: t.Number(),
102
+ tool: t.String(),
103
+ args: t.Optional(t.Any())
104
+ }),
105
+ response: t.Object({ result: t.Any() })
106
+ }, async ({ data }) => {
107
+ debug.log('path', `mcp:call-tool ${data.id} → ${data.tool}`);
108
+ const row = requireExternal(data.id);
109
+ await ensureFreshToken(row.id, !!row.oauth);
110
+ const result = await callExternalServerTool(row.slug, data.tool, data.args ?? {});
111
+ return { result };
112
+ });
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Permissions Handlers (Settings → Permissions)
3
+ *
4
+ * - permissions:list — stored allow/deny sets (global + optional project)
5
+ * - permissions:inventory — tool inventory offered as allow/deny targets
6
+ * - permissions:save — upsert one (scope, project, engine) rule set
7
+ *
8
+ * Rules are enforced at each engine's runtime auto-approve hook (real on
9
+ * Claude/Qwen/Copilot; best-effort/unverified on OpenCode/Codex). Mutations are
10
+ * admin-gated in `backend/auth/permissions.ts`. Changes take effect on the next
11
+ * chat stream.
12
+ */
13
+
14
+ import { t } from 'elysia';
15
+ import { createRouter } from '$shared/utils/ws-server';
16
+ import { debug } from '$shared/utils/logger';
17
+ import { permissionService } from '$backend/permissions';
18
+ import type { PermissionScope } from '$backend/database/queries';
19
+ import type { EngineType } from '$shared/types/unified';
20
+
21
+ const PERMISSION_SET_SCHEMA = t.Object({
22
+ scope: t.Union([t.Literal('global'), t.Literal('project'), t.Literal('profile')]),
23
+ projectId: t.Union([t.String(), t.Null()]),
24
+ profileId: t.Union([t.Number(), t.Null()]),
25
+ engine: t.String(),
26
+ allow: t.Array(t.String()),
27
+ deny: t.Array(t.String())
28
+ });
29
+
30
+ const INVENTORY_SCHEMA = t.Object({
31
+ engines: t.Array(t.Object({
32
+ engine: t.String(),
33
+ builtin: t.Array(t.String()),
34
+ bestEffort: t.Boolean()
35
+ })),
36
+ mcp: t.Array(t.String()),
37
+ subagent: t.Array(t.String())
38
+ });
39
+
40
+ export const permissionsCrudHandler = createRouter()
41
+ .http('permissions:list', {
42
+ data: t.Object({ projectId: t.Optional(t.String()) }),
43
+ response: t.Object({ sets: t.Array(PERMISSION_SET_SCHEMA) })
44
+ }, async ({ data }) => {
45
+ debug.log('path', 'permissions:list');
46
+ return { sets: permissionService.list(data.projectId) };
47
+ })
48
+ .http('permissions:inventory', {
49
+ data: t.Object({}),
50
+ response: INVENTORY_SCHEMA
51
+ }, async () => {
52
+ debug.log('path', 'permissions:inventory');
53
+ return permissionService.inventory();
54
+ })
55
+ .http('permissions:save', {
56
+ data: t.Object({
57
+ scope: t.Union([t.Literal('global'), t.Literal('project')]),
58
+ projectId: t.Optional(t.Union([t.String(), t.Null()])),
59
+ engine: t.String(),
60
+ allow: t.Array(t.String()),
61
+ deny: t.Array(t.String())
62
+ }),
63
+ response: t.Object({ success: t.Boolean() })
64
+ }, async ({ data }) => {
65
+ debug.log('path', `permissions:save ${data.engine}/${data.scope}`);
66
+ const projectId = data.scope === 'project' ? (data.projectId ?? null) : null;
67
+ if (data.scope === 'project' && !projectId) throw new Error('A project is required for project-scoped permissions');
68
+ // This admin endpoint only manages global/project scope. Profile-scoped
69
+ // permission overlays are edited through the profiles editor (profiles:save-permissions).
70
+ permissionService.save(data.scope as PermissionScope, projectId, null, data.engine as EngineType, data.allow, data.deny);
71
+ return { success: true };
72
+ });
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Permissions Router — Settings → Permissions (per-engine tool allow/deny).
3
+ */
4
+
5
+ import { createRouter } from '$shared/utils/ws-server';
6
+ import { permissionsCrudHandler } from './crud';
7
+
8
+ export const permissionsRouter = createRouter().merge(permissionsCrudHandler);