@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
@@ -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);
@@ -0,0 +1,217 @@
1
+ /**
2
+ * Test query history retention policy enforcement.
3
+ *
4
+ * Verifies that deterministic pruning keeps exactly HISTORY_KEEP_PER_CONNECTION
5
+ * entries after every PRUNE_EVERY_N_QUERIES inserts, replacing the old
6
+ * probabilistic approach that could allow unbounded growth.
7
+ */
8
+
9
+ import { describe, test, expect, beforeEach } from 'bun:test';
10
+ import { initializeDatabase, closeDatabase } from '../../database';
11
+ import { dbClientQueryHistoryQueries } from '../../database/queries';
12
+ import { dbClientConnectionQueries } from '../../database/queries';
13
+
14
+ const HISTORY_KEEP_PER_CONNECTION = 200;
15
+ const PRUNE_EVERY_N_QUERIES = 10;
16
+
17
+ describe('Query History Retention', () => {
18
+ beforeEach(async () => {
19
+ await initializeDatabase();
20
+ // Clean up any existing test data
21
+ const db = await import('../../database').then(m => m.getDatabase());
22
+ db.prepare('DELETE FROM db_client_query_history').run();
23
+ db.prepare('DELETE FROM db_client_connections').run();
24
+ });
25
+
26
+ test('prunes history after PRUNE_EVERY_N_QUERIES inserts', () => {
27
+ // Create a test connection
28
+ const connection = dbClientConnectionQueries.createForUser({
29
+ name: 'test-connection',
30
+ driver: 'postgres',
31
+ host: 'localhost',
32
+ port: 5432,
33
+ username: 'test',
34
+ password: 'test',
35
+ database: 'testdb',
36
+ sslMode: 'disable',
37
+ ssh: {
38
+ enabled: false,
39
+ host: '',
40
+ port: 22,
41
+ username: '',
42
+ authMethod: 'password',
43
+ password: '',
44
+ privateKey: '',
45
+ passphrase: ''
46
+ },
47
+ options: {}
48
+ }, 'test-user-id');
49
+
50
+ // Insert HISTORY_KEEP_PER_CONNECTION + 50 queries (250 total)
51
+ const totalQueries = HISTORY_KEEP_PER_CONNECTION + 50;
52
+ for (let i = 0; i < totalQueries; i++) {
53
+ dbClientQueryHistoryQueries.insert({
54
+ connectionId: connection.id,
55
+ userId: 'test-user-id',
56
+ query: `SELECT ${i};`,
57
+ durationMs: Math.random() * 100,
58
+ rowCount: 1,
59
+ status: 'success',
60
+ error: null
61
+ });
62
+
63
+ // Manually trigger prune every PRUNE_EVERY_N_QUERIES
64
+ if ((i + 1) % PRUNE_EVERY_N_QUERIES === 0) {
65
+ dbClientQueryHistoryQueries.prune(connection.id, HISTORY_KEEP_PER_CONNECTION);
66
+ }
67
+ }
68
+
69
+ // Verify exactly HISTORY_KEEP_PER_CONNECTION entries remain
70
+ const { total } = dbClientQueryHistoryQueries.list({
71
+ connectionId: connection.id,
72
+ limit: 1000
73
+ });
74
+
75
+ expect(total).toBe(HISTORY_KEEP_PER_CONNECTION);
76
+ });
77
+
78
+ test('keeps most recent queries after pruning', () => {
79
+ const connection = dbClientConnectionQueries.createForUser({
80
+ name: 'test-connection-2',
81
+ driver: 'postgres',
82
+ host: 'localhost',
83
+ port: 5432,
84
+ username: 'test',
85
+ password: 'test',
86
+ database: 'testdb',
87
+ sslMode: 'disable',
88
+ ssh: {
89
+ enabled: false,
90
+ host: '',
91
+ port: 22,
92
+ username: '',
93
+ authMethod: 'password',
94
+ password: '',
95
+ privateKey: '',
96
+ passphrase: ''
97
+ },
98
+ options: {}
99
+ }, 'test-user-id');
100
+
101
+ // Insert 250 queries — more than HISTORY_KEEP_PER_CONNECTION
102
+ for (let i = 0; i < 250; i++) {
103
+ dbClientQueryHistoryQueries.insert({
104
+ connectionId: connection.id,
105
+ userId: 'test-user-id',
106
+ query: `SELECT ${i};`,
107
+ durationMs: 10,
108
+ rowCount: 1,
109
+ status: 'success',
110
+ error: null
111
+ });
112
+
113
+ if ((i + 1) % PRUNE_EVERY_N_QUERIES === 0) {
114
+ dbClientQueryHistoryQueries.prune(connection.id, HISTORY_KEEP_PER_CONNECTION);
115
+ }
116
+ }
117
+
118
+ const { items, total } = dbClientQueryHistoryQueries.list({
119
+ connectionId: connection.id,
120
+ limit: 1000
121
+ });
122
+
123
+ expect(total).toBe(HISTORY_KEEP_PER_CONNECTION);
124
+ expect(items.length).toBe(HISTORY_KEEP_PER_CONNECTION);
125
+ });
126
+
127
+ test('prune does not affect other connections', () => {
128
+ // Create two connections
129
+ const conn1 = dbClientConnectionQueries.createForUser({
130
+ name: 'connection-1',
131
+ driver: 'postgres',
132
+ host: 'localhost',
133
+ port: 5432,
134
+ username: 'test',
135
+ password: 'test',
136
+ database: 'testdb',
137
+ sslMode: 'disable',
138
+ ssh: {
139
+ enabled: false,
140
+ host: '',
141
+ port: 22,
142
+ username: '',
143
+ authMethod: 'password',
144
+ password: '',
145
+ privateKey: '',
146
+ passphrase: ''
147
+ },
148
+ options: {}
149
+ }, 'user-1');
150
+
151
+ const conn2 = dbClientConnectionQueries.createForUser({
152
+ name: 'connection-2',
153
+ driver: 'mysql',
154
+ host: 'localhost',
155
+ port: 3306,
156
+ username: 'test',
157
+ password: 'test',
158
+ database: 'testdb',
159
+ sslMode: 'disable',
160
+ ssh: {
161
+ enabled: false,
162
+ host: '',
163
+ port: 22,
164
+ username: '',
165
+ authMethod: 'password',
166
+ password: '',
167
+ privateKey: '',
168
+ passphrase: ''
169
+ },
170
+ options: {}
171
+ }, 'user-2');
172
+
173
+ // Insert 250 queries for conn1
174
+ for (let i = 0; i < 250; i++) {
175
+ dbClientQueryHistoryQueries.insert({
176
+ connectionId: conn1.id,
177
+ userId: 'user-1',
178
+ query: `SELECT ${i};`,
179
+ durationMs: 10,
180
+ rowCount: 1,
181
+ status: 'success',
182
+ error: null
183
+ });
184
+ if ((i + 1) % PRUNE_EVERY_N_QUERIES === 0) {
185
+ dbClientQueryHistoryQueries.prune(conn1.id, HISTORY_KEEP_PER_CONNECTION);
186
+ }
187
+ }
188
+
189
+ // Insert only 50 queries for conn2
190
+ for (let i = 0; i < 50; i++) {
191
+ dbClientQueryHistoryQueries.insert({
192
+ connectionId: conn2.id,
193
+ userId: 'user-2',
194
+ query: `SELECT ${i};`,
195
+ durationMs: 10,
196
+ rowCount: 1,
197
+ status: 'success',
198
+ error: null
199
+ });
200
+ }
201
+
202
+ // Verify conn1 has exactly 200
203
+ const { total: total1 } = dbClientQueryHistoryQueries.list({
204
+ connectionId: conn1.id,
205
+ limit: 1000
206
+ });
207
+ expect(total1).toBe(HISTORY_KEEP_PER_CONNECTION);
208
+
209
+ // Verify conn2 still has all 50 (not affected by conn1 pruning)
210
+ const { total: total2 } = dbClientQueryHistoryQueries.list({
211
+ connectionId: conn2.id,
212
+ limit: 1000
213
+ });
214
+ expect(total2).toBe(50);
215
+ });
216
+ });
217
+