@myrialabs/clopen 0.4.40 → 0.4.42

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 (141) hide show
  1. package/.env.example +1 -1
  2. package/backend/artifacts/detect.ts +15 -3
  3. package/backend/artifacts/generate.ts +2 -2
  4. package/backend/artifacts/index.ts +12 -4
  5. package/backend/artifacts/markers.ts +24 -1
  6. package/backend/artifacts/matrix.ts +47 -3
  7. package/backend/artifacts/sync.test.ts +3 -3
  8. package/backend/artifacts/sync.ts +8 -20
  9. package/backend/artifacts/types.ts +9 -3
  10. package/backend/auth/permissions.ts +6 -11
  11. package/backend/auth/session-cleanup.ts +10 -1
  12. package/backend/auth/tokens.ts +9 -1
  13. package/backend/chat/stream-manager.ts +50 -0
  14. package/backend/database/crypto/secret-columns.ts +5 -1
  15. package/backend/database/index.ts +18 -0
  16. package/backend/database/migrations/079_merge_commands_into_skills.ts +222 -0
  17. package/backend/database/migrations/080_create_file_shares.ts +111 -0
  18. package/backend/database/migrations/081_create_push_subscriptions.ts +32 -0
  19. package/backend/database/migrations/082_create_git_identities.test.ts +186 -0
  20. package/backend/database/migrations/082_create_git_identities.ts +122 -0
  21. package/backend/database/migrations/index.ts +28 -0
  22. package/backend/database/queries/file-share-queries.ts +163 -0
  23. package/backend/database/queries/git-identity-queries.ts +290 -0
  24. package/backend/database/queries/index.ts +8 -4
  25. package/backend/database/queries/profile-queries.ts +5 -3
  26. package/backend/database/queries/push-subscription-queries.test.ts +90 -0
  27. package/backend/database/queries/push-subscription-queries.ts +99 -0
  28. package/backend/database/queries/skill-queries.ts +96 -18
  29. package/backend/engine/adapters/claude/environment.ts +11 -1
  30. package/backend/engine/adapters/claude/stream.ts +3 -2
  31. package/backend/engine/adapters/cline/stream.ts +3 -3
  32. package/backend/engine/adapters/codex/stream.ts +38 -6
  33. package/backend/engine/adapters/copilot/stream.ts +3 -3
  34. package/backend/engine/adapters/cursor/stream.ts +25 -3
  35. package/backend/engine/adapters/opencode/server.ts +26 -2
  36. package/backend/engine/adapters/opencode/stream.ts +8 -7
  37. package/backend/engine/adapters/pi/stream.ts +2 -2
  38. package/backend/engine/adapters/qwen/stream.ts +5 -3
  39. package/backend/engine/artifact-sync.ts +26 -20
  40. package/backend/engine/docs/artifacts.md +81 -22
  41. package/backend/engine/docs/quick-reference.md +2 -1
  42. package/backend/engine/resolve-model.test.ts +108 -0
  43. package/backend/engine/resolve-model.ts +53 -10
  44. package/backend/engine/structured-helpers.ts +22 -0
  45. package/backend/engine/types.ts +10 -0
  46. package/backend/files/file-shares.ts +369 -0
  47. package/backend/files/path-browsing.ts +27 -21
  48. package/backend/git/git-executor.ts +28 -2
  49. package/backend/git/git-service.ts +59 -40
  50. package/backend/git/identity/cli.test.ts +58 -0
  51. package/backend/git/identity/cli.ts +201 -0
  52. package/backend/git/identity/credential-helper.test.ts +242 -0
  53. package/backend/git/identity/env.test.ts +214 -0
  54. package/backend/git/identity/env.ts +193 -0
  55. package/backend/git/identity/import-local.test.ts +199 -0
  56. package/backend/git/identity/import-local.ts +141 -0
  57. package/backend/git/identity/index.ts +78 -0
  58. package/backend/git/identity/keys.ts +183 -0
  59. package/backend/git/identity/resolve.ts +140 -0
  60. package/backend/git/identity/scope-config.test.ts +145 -0
  61. package/backend/git/identity/scope-config.ts +175 -0
  62. package/backend/git/identity/service.ts +297 -0
  63. package/backend/http/files-shared.test.ts +505 -0
  64. package/backend/http/files-shared.ts +351 -0
  65. package/backend/http/push.ts +150 -0
  66. package/backend/index.ts +24 -0
  67. package/backend/instructions/index.ts +1 -1
  68. package/backend/instructions/sync.ts +30 -6
  69. package/backend/memory/compose.ts +2 -2
  70. package/backend/memory/consolidate.ts +2 -2
  71. package/backend/memory/extract/episodic.ts +2 -2
  72. package/backend/memory/judge.ts +2 -2
  73. package/backend/preview/browser/browser-console-manager.ts +214 -34
  74. package/backend/preview/browser/browser-pool.ts +526 -123
  75. package/backend/preview/browser/browser-preview-service.ts +192 -8
  76. package/backend/preview/browser/browser-tab-lifecycle.test.ts +240 -0
  77. package/backend/preview/browser/browser-tab-lifecycle.ts +495 -0
  78. package/backend/preview/browser/browser-tab-manager.ts +291 -65
  79. package/backend/preview/browser/capture-profile.ts +15 -1
  80. package/backend/preview/browser/types.ts +26 -1
  81. package/backend/profiles/service.ts +7 -6
  82. package/backend/push/sender.ts +172 -0
  83. package/backend/push/tags.ts +25 -0
  84. package/backend/push/vapid-keys.ts +77 -0
  85. package/backend/push/webpush-crypto.test.ts +200 -0
  86. package/backend/push/webpush-crypto.ts +231 -0
  87. package/backend/skills/detect.ts +28 -0
  88. package/backend/skills/index.ts +22 -4
  89. package/backend/skills/invoke.test.ts +114 -0
  90. package/backend/skills/invoke.ts +222 -0
  91. package/backend/skills/service.ts +194 -44
  92. package/backend/skills/spec.ts +35 -0
  93. package/backend/skills/sync.ts +85 -55
  94. package/backend/subagents/detect.ts +2 -3
  95. package/backend/subagents/sync.ts +15 -8
  96. package/backend/terminal/ptykit.ts +24 -0
  97. package/backend/work/pull-requests.ts +2 -2
  98. package/backend/ws/chat/stream.ts +100 -8
  99. package/backend/ws/files/index.ts +4 -0
  100. package/backend/ws/files/share.ts +95 -0
  101. package/backend/ws/git/branch-name.ts +2 -2
  102. package/backend/ws/git/branch.ts +17 -6
  103. package/backend/ws/git/commit-message.ts +2 -2
  104. package/backend/ws/git/commit.ts +6 -5
  105. package/backend/ws/git/conflict.ts +3 -2
  106. package/backend/ws/git/identity-context.ts +91 -0
  107. package/backend/ws/git/identity.ts +200 -0
  108. package/backend/ws/git/index.ts +3 -1
  109. package/backend/ws/git/remote.ts +57 -11
  110. package/backend/ws/index.ts +3 -4
  111. package/backend/ws/preview/browser/data.ts +60 -0
  112. package/backend/ws/preview/browser/interact.ts +6 -0
  113. package/backend/ws/preview/browser/tab-info.ts +9 -1
  114. package/backend/ws/preview/browser/tab.ts +64 -8
  115. package/backend/ws/preview/index.ts +21 -0
  116. package/backend/ws/profiles/crud.ts +2 -3
  117. package/backend/ws/skills/catalog.ts +5 -1
  118. package/backend/ws/skills/crud.ts +128 -22
  119. package/backend/ws/skills/index.ts +4 -1
  120. package/backend/ws/user/crud.ts +12 -3
  121. package/bin/clopen.ts +9 -0
  122. package/dist/assets/{index-D4igjF6e.js → index-BynqyvF4.js} +1 -1
  123. package/dist/assets/{index-DONNwiXm.js → index-DLoJsmNQ.js} +1 -1
  124. package/dist/assets/{main-BrfXH1bL.js → main-CUyZAmqt.js} +601 -592
  125. package/dist/assets/main-DVCW3cfr.css +1 -0
  126. package/dist/index.html +7 -2
  127. package/dist/sw.js +112 -0
  128. package/package.json +2 -2
  129. package/shared/constants/engine-tools.ts +31 -6
  130. package/shared/constants/notification-messages.ts +142 -0
  131. package/shared/types/git-identity.ts +112 -0
  132. package/shared/types/unified/stream.ts +7 -0
  133. package/backend/commands/detect.ts +0 -25
  134. package/backend/commands/index.ts +0 -9
  135. package/backend/commands/service.ts +0 -178
  136. package/backend/commands/store.ts +0 -45
  137. package/backend/commands/sync.ts +0 -94
  138. package/backend/database/queries/command-queries.ts +0 -82
  139. package/backend/ws/commands/crud.ts +0 -157
  140. package/backend/ws/commands/index.ts +0 -8
  141. package/dist/assets/main-CT1PygsW.css +0 -1
@@ -1,178 +0,0 @@
1
- /**
2
- * Command service — keeps the `commands` table and the on-disk canonical store
3
- * (`{clopenDir}/commands/<slug>.md`) in lockstep for the Settings → Commands
4
- * CRUD surface. Mirrors the Skills service shape, minus the marketplace.
5
- */
6
-
7
- import { commandQueries, type CommandRow } from '$backend/database/queries';
8
- import { parseDoc, serializeDoc, uniqueSlug, parseEngineMap, stringifyEngineMap, type EngineMap } from '$backend/artifacts';
9
- import { debug } from '$shared/utils/logger';
10
- import {
11
- writeCommandMd,
12
- readCommandMd,
13
- deleteCommandMd,
14
- commandFileExists
15
- } from './store';
16
-
17
- export interface CommandDTO {
18
- id: number;
19
- slug: string;
20
- name: string;
21
- description: string;
22
- argumentHint: string | null;
23
- /** Per-engine model override (EngineType → model id; absent = inherit). */
24
- modelByEngine: EngineMap;
25
- source: 'custom' | 'imported';
26
- enabled: boolean;
27
- /** False when the DB row exists but its `.md` is missing on disk. */
28
- present: boolean;
29
- createdAt: string;
30
- }
31
-
32
- export interface CommandInputFields {
33
- name: string;
34
- description: string;
35
- argumentHint?: string | null;
36
- modelByEngine?: EngineMap;
37
- body: string;
38
- }
39
-
40
- const FRONTMATTER_ORDER = ['description', 'argument-hint'];
41
-
42
- function toDTO(row: CommandRow, present: boolean): CommandDTO {
43
- return {
44
- id: row.id,
45
- slug: row.slug,
46
- name: row.name,
47
- description: row.description,
48
- argumentHint: row.argument_hint,
49
- modelByEngine: parseEngineMap(row.model_by_engine),
50
- source: row.source,
51
- enabled: row.is_enabled === 1,
52
- present,
53
- createdAt: row.created_at
54
- };
55
- }
56
-
57
- /** An imported `.md` carries a single Claude-shaped model → map to the claude slot. */
58
- function singleModelToMap(model: string | undefined): EngineMap {
59
- return model?.trim() ? { 'claude-code': model.trim() } : {};
60
- }
61
-
62
- /**
63
- * Serialize editor fields into the canonical command `.md` document. Model is
64
- * per-engine and injected at sync time, so it is NOT written here.
65
- */
66
- function buildDocument(fields: CommandInputFields): string {
67
- const frontmatter: Record<string, string> = {};
68
- if (fields.description.trim()) frontmatter.description = fields.description.trim();
69
- if (fields.argumentHint?.trim()) frontmatter['argument-hint'] = fields.argumentHint.trim();
70
- return serializeDoc({ frontmatter, body: fields.body }, FRONTMATTER_ORDER);
71
- }
72
-
73
- export const commandService = {
74
- async list(): Promise<CommandDTO[]> {
75
- const rows = commandQueries.getAll();
76
- const presence = await Promise.all(rows.map(r => commandFileExists(r.slug)));
77
- return rows.map((row, i) => toDTO(row, presence[i]));
78
- },
79
-
80
- /**
81
- * Minimal list of commands for the chat "/" picker. Non-admin surface
82
- * (any user can invoke a command), so it exposes only display fields — no
83
- * bodies, no source/disk metadata.
84
- *
85
- * `profileFilter` mirrors {@link syncCommands}'s semantics: when an active
86
- * profile references ≥1 command, the picker shows exactly that set (even if
87
- * a referenced command is globally disabled) instead of the enabled set.
88
- */
89
- available(profileFilter?: Set<string> | null): { slug: string; name: string; description: string; argumentHint: string | null }[] {
90
- const rows = profileFilter
91
- ? commandQueries.getAll().filter(r => profileFilter.has(r.slug))
92
- : commandQueries.getEnabled();
93
- return rows.map(r => ({
94
- slug: r.slug,
95
- name: r.name,
96
- description: r.description,
97
- argumentHint: r.argument_hint
98
- }));
99
- },
100
-
101
- async get(id: number): Promise<{ command: CommandDTO; body: string } | null> {
102
- const row = commandQueries.getById(id);
103
- if (!row) return null;
104
- const raw = await readCommandMd(row.slug);
105
- const body = raw ? parseDoc(raw).body : '';
106
- return { command: toDTO(row, raw !== null), body };
107
- },
108
-
109
- async create(input: CommandInputFields): Promise<CommandDTO> {
110
- if (!input.name.trim()) throw new Error('A command name is required');
111
- const slug = uniqueSlug(input.name, s => !!commandQueries.getBySlug(s));
112
- await writeCommandMd(slug, buildDocument(input));
113
- const row = commandQueries.insert({
114
- slug,
115
- name: input.name.trim(),
116
- description: input.description.trim(),
117
- argumentHint: input.argumentHint?.trim() || null,
118
- modelByEngine: stringifyEngineMap(input.modelByEngine),
119
- source: 'custom'
120
- });
121
- debug.log('commands', `📦 Created command: ${slug}`);
122
- return toDTO(row, true);
123
- },
124
-
125
- async update(id: number, input: CommandInputFields): Promise<CommandDTO> {
126
- const row = commandQueries.getById(id);
127
- if (!row) throw new Error('Command not found');
128
- await writeCommandMd(row.slug, buildDocument(input));
129
- commandQueries.updateMeta(
130
- id,
131
- input.name.trim(),
132
- input.description.trim(),
133
- input.argumentHint?.trim() || null,
134
- stringifyEngineMap(input.modelByEngine)
135
- );
136
- debug.log('commands', `🔧 Updated command: ${row.slug}`);
137
- return toDTO(commandQueries.getById(id)!, true);
138
- },
139
-
140
- /** Preview a pasted command `.md` (its frontmatter + body) before importing. */
141
- parsePreview(raw: string): { name: string; description: string; argumentHint: string | null; modelByEngine: EngineMap; body: string } {
142
- const parsed = parseDoc(raw);
143
- return {
144
- name: parsed.frontmatter.name || '',
145
- description: parsed.frontmatter.description || '',
146
- argumentHint: parsed.frontmatter['argument-hint'] || null,
147
- modelByEngine: singleModelToMap(parsed.frontmatter.model),
148
- body: parsed.body
149
- };
150
- },
151
-
152
- async import(raw: string, nameHint?: string): Promise<CommandDTO> {
153
- const parsed = parseDoc(raw);
154
- const displayName = (nameHint?.trim() || parsed.frontmatter.name || 'command').trim();
155
- return this.create({
156
- name: displayName,
157
- description: parsed.frontmatter.description || '',
158
- argumentHint: parsed.frontmatter['argument-hint'] || null,
159
- modelByEngine: singleModelToMap(parsed.frontmatter.model),
160
- body: parsed.body
161
- });
162
- },
163
-
164
- toggle(id: number, enabled: boolean): CommandDTO {
165
- const row = commandQueries.getById(id);
166
- if (!row) throw new Error('Command not found');
167
- commandQueries.setEnabled(id, enabled);
168
- return toDTO(commandQueries.getById(id)!, true);
169
- },
170
-
171
- async remove(id: number): Promise<void> {
172
- const row = commandQueries.getById(id);
173
- if (!row) throw new Error('Command not found');
174
- await deleteCommandMd(row.slug);
175
- commandQueries.remove(id);
176
- debug.log('commands', `🗑️ Deleted command: ${row.slug}`);
177
- }
178
- };
@@ -1,45 +0,0 @@
1
- /**
2
- * Canonical command store — the single source of truth on disk. Every managed
3
- * command is one Markdown file under `{clopenDir}/commands/<slug>.md` (a
4
- * `single-md` artifact). The DB (`commands` table) tracks only metadata + the
5
- * enable toggle; the sync layer mirrors enabled commands into each engine's
6
- * commands dir (native) or a synthetic preamble.
7
- */
8
-
9
- import { join } from 'path';
10
- import { mkdir, rm, stat, writeFile, readFile } from 'node:fs/promises';
11
- import { getClopenDir } from '$backend/utils/paths';
12
- import { debug } from '$shared/utils/logger';
13
-
14
- export function getCommandsRootDir(): string {
15
- return join(getClopenDir(), 'commands');
16
- }
17
-
18
- export function getCommandPath(slug: string): string {
19
- return join(getCommandsRootDir(), `${slug}.md`);
20
- }
21
-
22
- async function pathExists(path: string): Promise<boolean> {
23
- try { await stat(path); return true; } catch { return false; }
24
- }
25
-
26
- export function commandFileExists(slug: string): Promise<boolean> {
27
- return pathExists(getCommandPath(slug));
28
- }
29
-
30
- export async function readCommandMd(slug: string): Promise<string | null> {
31
- const path = getCommandPath(slug);
32
- if (!(await pathExists(path))) return null;
33
- return readFile(path, 'utf8');
34
- }
35
-
36
- export async function writeCommandMd(slug: string, content: string): Promise<void> {
37
- await mkdir(getCommandsRootDir(), { recursive: true });
38
- await writeFile(getCommandPath(slug), content, 'utf8');
39
- debug.log('commands', `💾 Wrote command ${slug}.md`);
40
- }
41
-
42
- export async function deleteCommandMd(slug: string): Promise<void> {
43
- await rm(getCommandPath(slug), { force: true });
44
- debug.log('commands', `🗑️ Removed command ${slug}.md`);
45
- }
@@ -1,94 +0,0 @@
1
- /**
2
- * Engine sync for Commands — a thin adapter over the shared artifact framework.
3
- * Enabled commands are mirrored as `<slug>.md` into each engine's native
4
- * commands dir (Claude: `.../commands/`) or listed in a synthetic preamble for
5
- * engines with no native command concept (best-effort/unverified).
6
- *
7
- * Never throws — a stream never breaks because commands couldn't sync.
8
- */
9
-
10
- import { commandQueries } 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 { readCommandMd } from './store';
15
-
16
- /**
17
- * Shape a command document for the engine's native format, injecting that
18
- * engine's model override (per-engine; the canonical `.md` carries no model):
19
- * - Codex custom prompts are PLAIN markdown (no frontmatter, no model) — emit the body.
20
- * - Claude / OpenCode read frontmatter — re-serialize with the injected model.
21
- */
22
- function documentForEngine(engine: ArtifactEngine, raw: string, model?: string): string {
23
- const { frontmatter, body } = parseDoc(raw);
24
- if (engine === 'codex') return body;
25
- const fm: Record<string, string> = {};
26
- if (frontmatter.description) fm.description = frontmatter.description;
27
- if (frontmatter['argument-hint']) fm['argument-hint'] = frontmatter['argument-hint'];
28
- if (model) fm.model = model;
29
- return serializeDoc({ frontmatter: fm, body }, ['description', 'argument-hint', 'model']);
30
- }
31
-
32
- function buildCommandsPreamble(items: ManagedArtifact[]): string {
33
- if (items.length === 0) return '';
34
- const lines = ['# Available Commands', '', 'User-defined command prompts you can follow when the user invokes one by name:', ''];
35
- for (const c of items) lines.push(`- **/${c.slug}** — ${c.description || c.name}`);
36
- return lines.join('\n');
37
- }
38
-
39
- /** The commands active for a stream, narrowed by the active Profile (metadata only). */
40
- function resolveEnabledCommandsMeta(profileId?: number): ManagedArtifact[] {
41
- const filter = artifactFilter(profileId, 'command');
42
- return (filter ? commandQueries.getAll() : commandQueries.getEnabled())
43
- .filter(r => !filter || filter.has(r.slug))
44
- .map(r => ({ slug: r.slug, name: r.name, description: r.description }));
45
- }
46
-
47
- /**
48
- * The profile-scoped commands preamble for PER-SESSION injection into a
49
- * prompt-scoped engine's prompt (OpenCode/Codex/Copilot). Returns '' when none
50
- * apply. Advisory: it scopes what the model surfaces/uses, on top of whatever the
51
- * engine's own (possibly stale/shared) command registry exposes.
52
- */
53
- export function buildCommandsPromptContext(profileId?: number): string {
54
- return buildCommandsPreamble(resolveEnabledCommandsMeta(profileId));
55
- }
56
-
57
- export async function syncCommands(engine: ArtifactEngine, profileId?: number): Promise<void> {
58
- try {
59
- // On a prompt-scoped engine, a SYNTHETIC command target (no native command
60
- // dir — Copilot) is delivered per-session via prompt injection instead, so
61
- // materialize an empty set to strip any shared global block that would leak
62
- // across sessions. NATIVE command engines (Claude/OpenCode/Codex) keep the
63
- // filtered files on disk; Qwen (per-query) keeps its synthetic preamble.
64
- const synthetic = resolveArtifact('command', { engine, scope: 'global' }).format === 'preamble-region';
65
- const viaPrompt = synthetic && isPromptScopedEngine(engine);
66
- const filter = artifactFilter(profileId, 'command');
67
- // A profile activates the commands it references even if globally disabled;
68
- // with no profile filter, only the enabled set applies (unchanged).
69
- const rows = viaPrompt ? [] : (filter ? commandQueries.getAll() : commandQueries.getEnabled())
70
- .filter(r => !filter || filter.has(r.slug));
71
- const engineType = artifactEngineToType(engine);
72
- const enabled: ManagedArtifact[] = [];
73
- for (const row of rows) {
74
- const raw = await readCommandMd(row.slug);
75
- if (raw == null) continue; // file missing on disk — skip silently
76
- const model = parseEngineMap(row.model_by_engine)[engineType];
77
- enabled.push({ slug: row.slug, name: row.name, description: row.description, document: documentForEngine(engine, raw, model) });
78
- }
79
- const managedSlugs = commandQueries.getAll().map(r => r.slug);
80
- await materializeArtifacts('command', { engine, scope: 'global' }, {
81
- enabled,
82
- managedSlugs,
83
- buildPreamble: buildCommandsPreamble
84
- });
85
- debug.log('commands', `⌨️ Synced ${enabled.length} command(s) → ${engine}`);
86
- } catch (error) {
87
- debug.warn('commands', `⚠️ Command sync for ${engine} failed (continuing without):`, error);
88
- }
89
- }
90
-
91
- export async function syncCommandsAllEngines(): Promise<void> {
92
- const engines: ArtifactEngine[] = ['claude', 'codex', 'copilot', 'qwen', 'opencode', 'pi'];
93
- await Promise.all(engines.map(syncCommands));
94
- }
@@ -1,82 +0,0 @@
1
- /**
2
- * Command Queries
3
- *
4
- * CRUD for user-managed custom slash Commands (Settings → Commands). Like
5
- * Skills, the `commands` table holds only METADATA + the enable toggle; the
6
- * command's Markdown document lives on disk in the canonical store under
7
- * `{clopenDir}/commands/<slug>.md` (see `backend/commands/store.ts`).
8
- */
9
-
10
- import { getDatabase } from '../index';
11
-
12
- export type CommandSource = 'custom' | 'imported';
13
-
14
- export interface CommandRow {
15
- id: number;
16
- slug: string;
17
- name: string;
18
- description: string;
19
- argument_hint: string | null;
20
- /** JSON map of EngineType → model id ({} = inherit everywhere). */
21
- model_by_engine: string;
22
- source: CommandSource;
23
- is_enabled: number;
24
- created_at: string;
25
- }
26
-
27
- export interface CommandInput {
28
- slug: string;
29
- name: string;
30
- description: string;
31
- argumentHint?: string | null;
32
- /** JSON string: EngineType → model id. */
33
- modelByEngine?: string;
34
- source?: CommandSource;
35
- }
36
-
37
- export const commandQueries = {
38
- getAll(): CommandRow[] {
39
- return getDatabase().prepare(`SELECT * FROM commands ORDER BY created_at ASC`).all() as CommandRow[];
40
- },
41
-
42
- getEnabled(): CommandRow[] {
43
- return getDatabase().prepare(`SELECT * FROM commands WHERE is_enabled = 1 ORDER BY created_at ASC`).all() as CommandRow[];
44
- },
45
-
46
- getById(id: number): CommandRow | null {
47
- return getDatabase().prepare(`SELECT * FROM commands WHERE id = ?`).get(id) as CommandRow | null;
48
- },
49
-
50
- getBySlug(slug: string): CommandRow | null {
51
- return getDatabase().prepare(`SELECT * FROM commands WHERE slug = ?`).get(slug) as CommandRow | null;
52
- },
53
-
54
- insert(input: CommandInput): CommandRow {
55
- const result = getDatabase().prepare(
56
- `INSERT INTO commands (slug, name, description, argument_hint, model_by_engine, source)
57
- VALUES (?, ?, ?, ?, ?, ?)`
58
- ).run(
59
- input.slug,
60
- input.name,
61
- input.description,
62
- input.argumentHint ?? null,
63
- input.modelByEngine ?? '{}',
64
- input.source ?? 'custom'
65
- ) as { lastInsertRowid: number | bigint };
66
- return this.getById(Number(result.lastInsertRowid))!;
67
- },
68
-
69
- updateMeta(id: number, name: string, description: string, argumentHint: string | null, modelByEngine: string): void {
70
- getDatabase().prepare(
71
- `UPDATE commands SET name = ?, description = ?, argument_hint = ?, model_by_engine = ? WHERE id = ?`
72
- ).run(name, description, argumentHint, modelByEngine, id);
73
- },
74
-
75
- setEnabled(id: number, enabled: boolean): void {
76
- getDatabase().prepare(`UPDATE commands SET is_enabled = ? WHERE id = ?`).run(enabled ? 1 : 0, id);
77
- },
78
-
79
- remove(id: number): void {
80
- getDatabase().prepare(`DELETE FROM commands WHERE id = ?`).run(id);
81
- }
82
- };
@@ -1,157 +0,0 @@
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
- });
@@ -1,8 +0,0 @@
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);