@myrialabs/clopen 0.4.36 → 0.4.38

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/README.md +2 -2
  2. package/backend/auth/permissions.ts +14 -0
  3. package/backend/bootstrap.ts +16 -0
  4. package/backend/database/crypto/envelope.test.ts +93 -0
  5. package/backend/database/crypto/envelope.ts +127 -0
  6. package/backend/database/crypto/index.ts +22 -0
  7. package/backend/database/crypto/master-key.ts +129 -0
  8. package/backend/database/crypto/secret-columns.ts +147 -0
  9. package/backend/database/migrations/071_create_notes_tables.ts +90 -0
  10. package/backend/database/migrations/072_encrypt_stored_secrets.ts +107 -0
  11. package/backend/database/migrations/073_create_integration_tables.ts +119 -0
  12. package/backend/database/migrations/074_create_work_tables.ts +94 -0
  13. package/backend/database/migrations/index.ts +28 -0
  14. package/backend/database/queries/db-client-connection-queries.ts +23 -12
  15. package/backend/database/queries/engine-queries.ts +23 -10
  16. package/backend/database/queries/index.ts +6 -1
  17. package/backend/database/queries/integration-queries.ts +297 -0
  18. package/backend/database/queries/mcp-server-queries.ts +38 -11
  19. package/backend/database/queries/note-queries.test.ts +190 -0
  20. package/backend/database/queries/note-queries.ts +269 -0
  21. package/backend/database/queries/profile-queries.ts +1 -1
  22. package/backend/database/queries/ssh-connection-queries.ts +19 -8
  23. package/backend/database/queries/work-queries.ts +210 -0
  24. package/backend/engine/docs/artifacts.md +22 -9
  25. package/backend/files/os-clipboard.test.ts +209 -0
  26. package/backend/files/os-clipboard.ts +567 -0
  27. package/backend/git/conflict-state.test.ts +396 -0
  28. package/backend/git/git-executor.ts +6 -0
  29. package/backend/git/git-parser.ts +144 -48
  30. package/backend/git/git-service.ts +727 -57
  31. package/backend/git/push-target.test.ts +264 -0
  32. package/backend/http/integration-hooks.ts +42 -0
  33. package/backend/http/notes-images.test.ts +228 -0
  34. package/backend/http/notes-images.ts +196 -0
  35. package/backend/index.ts +9 -0
  36. package/backend/integrations/accounts.ts +229 -0
  37. package/backend/integrations/health.ts +146 -0
  38. package/backend/integrations/index.ts +36 -0
  39. package/backend/integrations/projections/index.ts +120 -0
  40. package/backend/integrations/projections/mcp-projector.test.ts +204 -0
  41. package/backend/integrations/projections/mcp-projector.ts +159 -0
  42. package/backend/integrations/projections/types.ts +51 -0
  43. package/backend/integrations/registry/define.ts +38 -0
  44. package/backend/integrations/registry/index.ts +56 -0
  45. package/backend/integrations/registry/providers/context7.ts +44 -0
  46. package/backend/integrations/registry/providers/firecrawl.ts +41 -0
  47. package/backend/integrations/registry/providers/github.ts +78 -0
  48. package/backend/integrations/registry/types.ts +96 -0
  49. package/backend/integrations/webhooks/gateway.ts +160 -0
  50. package/backend/integrations/webhooks/verify.ts +65 -0
  51. package/backend/mcp/README.md +25 -3
  52. package/backend/mcp/external/config.ts +35 -1
  53. package/backend/mcp/index.ts +1 -1
  54. package/backend/mcp/internal/config.ts +1 -1
  55. package/backend/notes/access.test.ts +82 -0
  56. package/backend/notes/access.ts +27 -0
  57. package/backend/notes/storage.test.ts +77 -0
  58. package/backend/notes/storage.ts +114 -0
  59. package/backend/permissions/service.ts +2 -2
  60. package/backend/profiles/service.ts +1 -1
  61. package/backend/project/status-manager.ts +20 -0
  62. package/backend/projects/project-cleanup.ts +6 -0
  63. package/backend/work/bindings.ts +124 -0
  64. package/backend/work/index.ts +42 -0
  65. package/backend/work/prompts.ts +150 -0
  66. package/backend/work/providers/github/actions-logs.ts +180 -0
  67. package/backend/work/providers/github/adapter.test.ts +88 -0
  68. package/backend/work/providers/github/adapter.ts +1255 -0
  69. package/backend/work/providers/github/client.ts +280 -0
  70. package/backend/work/providers/github/list-range.test.ts +158 -0
  71. package/backend/work/providers/github/token-kind.test.ts +42 -0
  72. package/backend/work/pull-requests.ts +242 -0
  73. package/backend/work/registry.ts +27 -0
  74. package/backend/work/service.ts +436 -0
  75. package/backend/work/start-work.test.ts +71 -0
  76. package/backend/work/start-work.ts +232 -0
  77. package/backend/work/types.ts +180 -0
  78. package/backend/ws/files/clipboard.ts +78 -0
  79. package/backend/ws/files/index.ts +5 -0
  80. package/backend/ws/git/branch-name.ts +6 -5
  81. package/backend/ws/git/branch.ts +43 -1
  82. package/backend/ws/git/commit-message.ts +13 -10
  83. package/backend/ws/git/conflict.ts +106 -3
  84. package/backend/ws/git/diff-budget.test.ts +125 -0
  85. package/backend/ws/git/diff-budget.ts +279 -0
  86. package/backend/ws/git/log.ts +25 -0
  87. package/backend/ws/git/remote.ts +75 -1
  88. package/backend/ws/index.ts +11 -1
  89. package/backend/ws/integrations/crud.ts +219 -0
  90. package/backend/ws/integrations/index.ts +22 -0
  91. package/backend/ws/mcp/crud.ts +25 -1
  92. package/backend/ws/notes/index.ts +278 -0
  93. package/backend/ws/profiles/crud.ts +1 -1
  94. package/backend/ws/work/actions.ts +206 -0
  95. package/backend/ws/work/context.ts +51 -0
  96. package/backend/ws/work/crud.ts +347 -0
  97. package/backend/ws/work/index.ts +17 -0
  98. package/backend/ws/work/pull-requests.ts +177 -0
  99. package/backend/ws/work/schemas.ts +226 -0
  100. package/dist/assets/{index-Bg-SUCFg.js → index-CyH7fSbR.js} +1 -1
  101. package/dist/assets/{index-Cz4YpHVi.js → index-DSHIANSy.js} +1 -1
  102. package/dist/assets/main-D2IOjftb.css +1 -0
  103. package/dist/assets/main-DM-tHKbW.js +1152 -0
  104. package/dist/index.html +2 -2
  105. package/package.json +1 -1
  106. package/shared/constants/engine-tools.ts +1 -1
  107. package/shared/constants/tool-icons.ts +33 -0
  108. package/shared/types/database/schema.ts +41 -0
  109. package/shared/types/git.ts +123 -0
  110. package/shared/types/integrations.ts +140 -0
  111. package/shared/types/stores/settings.ts +8 -0
  112. package/shared/types/work.ts +426 -0
  113. package/shared/utils/logger.ts +3 -0
  114. package/dist/assets/main-9G7IpQpK.css +0 -1
  115. package/dist/assets/main-BofFsH8E.js +0 -1085
@@ -120,6 +120,11 @@ export const remoteHandler = createRouter()
120
120
  remote: t.Optional(t.String()),
121
121
  branch: t.Optional(t.String()),
122
122
  force: t.Optional(t.Boolean()),
123
+ /**
124
+ * Follow the branch's own upstream instead of `remote`. Default true —
125
+ * only set false for a deliberate "push this somewhere else" action.
126
+ */
127
+ useUpstream: t.Optional(t.Boolean()),
123
128
  repoPath: t.Optional(t.String())
124
129
  }),
125
130
  response: t.Object({
@@ -129,7 +134,59 @@ export const remoteHandler = createRouter()
129
134
  }, async ({ data, conn }) => {
130
135
  const { root } = requireProjectWorkspace(conn, data.projectId);
131
136
  const cwd = resolveRepoCwd(root, data.repoPath);
132
- return await gitService.push(cwd, data.remote, data.branch, data.force);
137
+ return await gitService.push(cwd, data.remote, data.branch, data.force, {
138
+ useUpstream: data.useUpstream ?? true
139
+ });
140
+ })
141
+
142
+ /** Where a push would actually land — drives the Push button's label. */
143
+ .http('git:push-target', {
144
+ data: t.Object({
145
+ projectId: t.String(),
146
+ branch: t.Optional(t.String()),
147
+ repoPath: t.Optional(t.String())
148
+ }),
149
+ response: t.Object({
150
+ remote: t.String(),
151
+ remoteBranch: t.String(),
152
+ hasUpstream: t.Boolean(),
153
+ isUrl: t.Boolean(),
154
+ branch: t.String()
155
+ })
156
+ }, async ({ data, conn }) => {
157
+ const { root } = requireProjectWorkspace(conn, data.projectId);
158
+ const cwd = resolveRepoCwd(root, data.repoPath);
159
+ return await gitService.getPushTarget(cwd, data.branch);
160
+ })
161
+
162
+ .http('git:set-upstream', {
163
+ data: t.Object({
164
+ projectId: t.String(),
165
+ branch: t.String({ minLength: 1 }),
166
+ remote: t.String({ minLength: 1 }),
167
+ remoteBranch: t.Optional(t.String()),
168
+ repoPath: t.Optional(t.String())
169
+ }),
170
+ response: t.Object({ ok: t.Boolean() })
171
+ }, async ({ data, conn }) => {
172
+ const { root } = requireProjectWorkspace(conn, data.projectId);
173
+ const cwd = resolveRepoCwd(root, data.repoPath);
174
+ await gitService.setUpstream(cwd, data.branch, data.remote, data.remoteBranch);
175
+ return { ok: true };
176
+ })
177
+
178
+ .http('git:unset-upstream', {
179
+ data: t.Object({
180
+ projectId: t.String(),
181
+ branch: t.String({ minLength: 1 }),
182
+ repoPath: t.Optional(t.String())
183
+ }),
184
+ response: t.Object({ ok: t.Boolean() })
185
+ }, async ({ data, conn }) => {
186
+ const { root } = requireProjectWorkspace(conn, data.projectId);
187
+ const cwd = resolveRepoCwd(root, data.repoPath);
188
+ await gitService.unsetUpstream(cwd, data.branch);
189
+ return { ok: true };
133
190
  })
134
191
 
135
192
  .http('git:add-remote', {
@@ -273,6 +330,23 @@ export const remoteHandler = createRouter()
273
330
  return await gitService.stashPop(cwd, data.index);
274
331
  })
275
332
 
333
+ .http('git:stash-apply', {
334
+ data: t.Object({
335
+ projectId: t.String(),
336
+ index: t.Optional(t.Number()),
337
+ repoPath: t.Optional(t.String())
338
+ }),
339
+ response: t.Object({
340
+ success: t.Boolean(),
341
+ hasConflicts: t.Boolean(),
342
+ message: t.String()
343
+ })
344
+ }, async ({ data, conn }) => {
345
+ const { root } = requireProjectWorkspace(conn, data.projectId);
346
+ const cwd = resolveRepoCwd(root, data.repoPath);
347
+ return await gitService.stashApply(cwd, data.index);
348
+ })
349
+
276
350
  .http('git:stash-drop', {
277
351
  data: t.Object({
278
352
  projectId: t.String(),
@@ -35,6 +35,7 @@ import { sshRouter } from './ssh';
35
35
  import { portsRouter } from './ports';
36
36
  import { containersRouter } from './containers';
37
37
  import { mcpRouter } from './mcp';
38
+ import { integrationsRouter } from './integrations';
38
39
  import { skillsRouter } from './skills';
39
40
  import { commandsRouter } from './commands';
40
41
  import { subagentsRouter } from './subagents';
@@ -44,6 +45,8 @@ import { profilesRouter } from './profiles';
44
45
  import { artifactsRouter } from './artifacts';
45
46
  import { memoryRouter } from './memory';
46
47
  import { worktreesRouter } from './worktrees';
48
+ import { notesRouter } from './notes';
49
+ import { workRouter } from './work';
47
50
 
48
51
  // ============================================
49
52
  // Main App Router - Merge All Module Routers
@@ -98,6 +101,7 @@ export const wsRouter = createRouter()
98
101
 
99
102
  // External MCP server management (install from the official registry)
100
103
  .merge(mcpRouter)
104
+ .merge(integrationsRouter)
101
105
 
102
106
  // Agent Skills management (create, import, install from a marketplace)
103
107
  .merge(skillsRouter)
@@ -113,7 +117,13 @@ export const wsRouter = createRouter()
113
117
  .merge(artifactsRouter)
114
118
 
115
119
  // Memory Graph (unified episodic + structural memory, shared by every engine)
116
- .merge(memoryRouter);
120
+ .merge(memoryRouter)
121
+
122
+ // Notes (project-scoped markdown)
123
+ .merge(notesRouter)
124
+
125
+ // Issues & PRs surface — work items, pull requests and CI for the current project
126
+ .merge(workRouter);
117
127
 
118
128
  // Export API type for frontend type-safe access
119
129
  export type WSAPI = typeof wsRouter['$api'];
@@ -0,0 +1,219 @@
1
+ /**
2
+ * Integration account handlers.
3
+ *
4
+ * integrations:providers — the registry, as the catalogue renders it
5
+ * integrations:list — connected accounts (never credential values)
6
+ * integrations:connect — create an account and project its capabilities
7
+ * integrations:update — credentials / capabilities / project / enabled
8
+ * integrations:disconnect — release every projection, then drop the account
9
+ * integrations:health — probe one account
10
+ * integrations:secrets-health — state of secrets at rest, for the hub banner
11
+ *
12
+ * Admin-gated in `backend/auth/permissions.ts`, matching the MCP surface it
13
+ * absorbs: connecting an account changes what every engine and every project
14
+ * can reach.
15
+ */
16
+
17
+ import { t } from 'elysia';
18
+ import { createRouter } from '$shared/utils/ws-server';
19
+ import { debug } from '$shared/utils/logger';
20
+ import {
21
+ checkAccountHealth,
22
+ getSecretsHealth,
23
+ integrationAccounts,
24
+ listProviderInfo
25
+ } from '$backend/integrations';
26
+ import { INTEGRATION_CAPABILITIES, INTEGRATION_CATEGORIES } from '$shared/types/integrations';
27
+ import type { IntegrationCapability } from '$shared/types/integrations';
28
+ import { ws as wsServer } from '$backend/utils/ws';
29
+
30
+ /**
31
+ * Tell every connected client an account changed.
32
+ *
33
+ * Global rather than per-project: an account can be bound to a project, but the
34
+ * connector row it projects is instance-wide, and the hub is an instance-wide
35
+ * screen.
36
+ */
37
+ function announce(accountId?: string): void {
38
+ wsServer.emit.global('integrations:changed', accountId ? { accountId } : {});
39
+ }
40
+
41
+ const CAPABILITY_SCHEMA = t.Union(INTEGRATION_CAPABILITIES.map((capability) => t.Literal(capability)));
42
+ const CATEGORY_SCHEMA = t.Union(INTEGRATION_CATEGORIES.map((category) => t.Literal(category)));
43
+
44
+ const STATUS_SCHEMA = t.Union([
45
+ t.Literal('unknown'),
46
+ t.Literal('ok'),
47
+ t.Literal('needs_auth'),
48
+ t.Literal('needs_config'),
49
+ t.Literal('error')
50
+ ]);
51
+
52
+ const AUTH_METHOD_SCHEMA = t.Union([
53
+ t.Literal('api-key'),
54
+ t.Literal('oauth-device'),
55
+ t.Literal('oauth-code'),
56
+ t.Literal('mcp-oauth'),
57
+ t.Literal('connection-string'),
58
+ t.Literal('none')
59
+ ]);
60
+
61
+ const CREDENTIAL_FIELD_SCHEMA = t.Object({
62
+ name: t.String(),
63
+ label: t.String(),
64
+ placeholder: t.Optional(t.String()),
65
+ help: t.Optional(t.String()),
66
+ isSecret: t.Boolean(),
67
+ isRequired: t.Boolean()
68
+ });
69
+
70
+ const PROVIDER_SCHEMA = t.Object({
71
+ id: t.String(),
72
+ name: t.String(),
73
+ category: CATEGORY_SCHEMA,
74
+ description: t.String(),
75
+ docsUrl: t.Optional(t.String()),
76
+ authMethod: AUTH_METHOD_SCHEMA,
77
+ credentialFields: t.Array(CREDENTIAL_FIELD_SCHEMA),
78
+ capabilities: t.Array(CAPABILITY_SCHEMA),
79
+ defaultCapabilities: t.Array(CAPABILITY_SCHEMA),
80
+ providesAgentTools: t.Boolean(),
81
+ acceptsWebhooks: t.Boolean()
82
+ });
83
+
84
+ const ACCOUNT_SCHEMA = t.Object({
85
+ id: t.String(),
86
+ provider: t.String(),
87
+ label: t.String(),
88
+ projectId: t.Union([t.String(), t.Null()]),
89
+ authMethod: AUTH_METHOD_SCHEMA,
90
+ // Which fields hold a value — NOT the values. A credential that reached the
91
+ // client would be a credential in a log, a screenshot and a bug report.
92
+ configuredFields: t.Array(t.String()),
93
+ capabilities: t.Array(CAPABILITY_SCHEMA),
94
+ status: STATUS_SCHEMA,
95
+ statusDetail: t.Union([t.String(), t.Null()]),
96
+ checkedAt: t.Union([t.String(), t.Null()]),
97
+ isEnabled: t.Boolean(),
98
+ createdAt: t.String(),
99
+ updatedAt: t.String(),
100
+ projections: t.Array(t.Object({
101
+ capability: CAPABILITY_SCHEMA,
102
+ targetKind: t.Union([t.Literal('mcp_server'), t.Literal('db_client_connection')]),
103
+ targetId: t.String(),
104
+ adopted: t.Boolean()
105
+ }))
106
+ });
107
+
108
+ const SECRETS_HEALTH_SCHEMA = t.Object({
109
+ keySource: t.Union([t.Literal('env'), t.Literal('file')]),
110
+ keyFingerprint: t.String(),
111
+ failureCount: t.Number(),
112
+ lastFailureAt: t.Union([t.String(), t.Null()]),
113
+ unknownKeyFingerprints: t.Array(t.String()),
114
+ unsealedColumns: t.Array(t.Object({
115
+ table: t.String(),
116
+ column: t.String(),
117
+ count: t.Number()
118
+ }))
119
+ });
120
+
121
+ export const integrationsCrudHandler = createRouter()
122
+ .http('integrations:providers', {
123
+ data: t.Object({}),
124
+ response: t.Object({ providers: t.Array(PROVIDER_SCHEMA) })
125
+ }, async () => {
126
+ debug.log('path', 'integrations:providers');
127
+ return { providers: listProviderInfo() };
128
+ })
129
+
130
+ .http('integrations:list', {
131
+ data: t.Object({}),
132
+ response: t.Object({ accounts: t.Array(ACCOUNT_SCHEMA) })
133
+ }, async () => {
134
+ debug.log('path', 'integrations:list');
135
+ return { accounts: integrationAccounts.list() };
136
+ })
137
+
138
+ .http('integrations:connect', {
139
+ data: t.Object({
140
+ provider: t.String(),
141
+ label: t.Optional(t.String()),
142
+ projectId: t.Optional(t.Union([t.String(), t.Null()])),
143
+ credentials: t.Record(t.String(), t.String()),
144
+ capabilities: t.Optional(t.Array(CAPABILITY_SCHEMA))
145
+ }),
146
+ response: t.Object({ account: ACCOUNT_SCHEMA })
147
+ }, async ({ data }) => {
148
+ debug.log('path', `integrations:connect ${data.provider}`);
149
+ const account = integrationAccounts.connect({
150
+ provider: data.provider,
151
+ label: data.label,
152
+ projectId: data.projectId ?? null,
153
+ credentials: data.credentials,
154
+ capabilities: data.capabilities as IntegrationCapability[] | undefined
155
+ });
156
+ announce(account.id);
157
+ return { account };
158
+ })
159
+
160
+ /**
161
+ * One update handler rather than four.
162
+ *
163
+ * Every field here re-projects, and splitting them into separate events
164
+ * would just be four ways to reach the same pass. Absent fields are left
165
+ * alone; an empty credential value means "not re-typed", not "clear".
166
+ */
167
+ .http('integrations:update', {
168
+ data: t.Object({
169
+ id: t.String(),
170
+ label: t.Optional(t.String({ minLength: 1, maxLength: 120 })),
171
+ credentials: t.Optional(t.Record(t.String(), t.String())),
172
+ capabilities: t.Optional(t.Array(CAPABILITY_SCHEMA)),
173
+ projectId: t.Optional(t.Union([t.String(), t.Null()])),
174
+ enabled: t.Optional(t.Boolean())
175
+ }),
176
+ response: t.Object({ account: ACCOUNT_SCHEMA })
177
+ }, async ({ data }) => {
178
+ debug.log('path', `integrations:update ${data.id}`);
179
+
180
+ if (data.label !== undefined) integrationAccounts.setLabel(data.id, data.label);
181
+ if (data.credentials) integrationAccounts.updateCredentials(data.id, data.credentials);
182
+ if (data.capabilities) integrationAccounts.setCapabilities(data.id, data.capabilities as IntegrationCapability[]);
183
+ if (data.projectId !== undefined) integrationAccounts.setProject(data.id, data.projectId);
184
+ if (data.enabled !== undefined) integrationAccounts.setEnabled(data.id, data.enabled);
185
+
186
+ const account = integrationAccounts.get(data.id);
187
+ if (!account) throw new Error('Integration account not found');
188
+ announce(account.id);
189
+ return { account };
190
+ })
191
+
192
+ .http('integrations:disconnect', {
193
+ data: t.Object({ id: t.String() }),
194
+ response: t.Object({ success: t.Boolean() })
195
+ }, async ({ data }) => {
196
+ debug.log('path', `integrations:disconnect ${data.id}`);
197
+ integrationAccounts.disconnect(data.id);
198
+ announce(data.id);
199
+ return { success: true };
200
+ })
201
+
202
+ .http('integrations:health', {
203
+ data: t.Object({ id: t.String() }),
204
+ response: t.Object({
205
+ status: STATUS_SCHEMA,
206
+ detail: t.Union([t.String(), t.Null()])
207
+ })
208
+ }, async ({ data }) => {
209
+ debug.log('path', `integrations:health ${data.id}`);
210
+ return checkAccountHealth(data.id);
211
+ })
212
+
213
+ .http('integrations:secrets-health', {
214
+ data: t.Object({}),
215
+ response: t.Object({ health: SECRETS_HEALTH_SCHEMA })
216
+ }, async () => {
217
+ debug.log('path', 'integrations:secrets-health');
218
+ return { health: getSecretsHealth() };
219
+ });
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Integrations Router
3
+ *
4
+ * Connect, reconfigure and disconnect third-party accounts. What an integration
5
+ * DOES is not here — that lives in the surface that owns the work.
6
+ */
7
+
8
+ import { t } from 'elysia';
9
+ import { createRouter } from '$shared/utils/ws-server';
10
+ import { integrationsCrudHandler } from './crud';
11
+
12
+ export const integrationsRouter = createRouter()
13
+ .merge(integrationsCrudHandler)
14
+ /**
15
+ * Broadcast after any account mutation. The hub also shows connectors, whose
16
+ * rows a projection creates and removes, so a client that only watched its
17
+ * own request would miss a connector appearing because someone else
18
+ * connected an account.
19
+ */
20
+ .emit('integrations:changed', t.Object({
21
+ accountId: t.Optional(t.String())
22
+ }));
@@ -25,7 +25,8 @@ import {
25
25
  completeAuthorization,
26
26
  getValidAccessToken,
27
27
  parseMcpConfig,
28
- parseToolOverrides
28
+ parseToolOverrides,
29
+ getEngineConfigsForServer
29
30
  } from '$backend/mcp';
30
31
 
31
32
  const TRANSPORT_SCHEMA = t.Union([t.Literal('stdio'), t.Literal('http'), t.Literal('sse')]);
@@ -325,4 +326,27 @@ export const mcpCrudHandler = createRouter()
325
326
  mcpServerQueries.remove(data.id);
326
327
  debug.log('mcp', `🗑️ Uninstalled external MCP server: ${existing.slug}`);
327
328
  return { success: true };
329
+ })
330
+ /**
331
+ * What each engine is actually handed for this server.
332
+ *
333
+ * Not the same thing as the stored row: every external server reaches an
334
+ * engine as a Streamable-HTTP remote pointing at Clopen's own proxy, so
335
+ * showing the row and labelling it "the engine's config" would mislead.
336
+ * Returned as a JSON string per engine because the shapes differ by SDK and
337
+ * the UI only ever prints them.
338
+ */
339
+ .http('mcp:engine-config', {
340
+ data: t.Object({ id: t.Number() }),
341
+ response: t.Object({ configs: t.Record(t.String(), t.String()) })
342
+ }, async ({ data }) => {
343
+ debug.log('path', `mcp:engine-config ${data.id}`);
344
+ const existing = mcpServerQueries.getById(data.id);
345
+ if (!existing) throw new Error('MCP server not found');
346
+
347
+ const configs = Object.fromEntries(
348
+ Object.entries(getEngineConfigsForServer(existing.slug))
349
+ .map(([engine, config]) => [engine, JSON.stringify(config, null, 2)])
350
+ );
351
+ return { configs };
328
352
  });
@@ -0,0 +1,278 @@
1
+ /**
2
+ * Notes Router
3
+ *
4
+ * Notes live in collections, and a collection carries the scope: `project`
5
+ * (members of that project) or `global` (every signed-in user). Permissions are
6
+ * resolved through the collection on every route — a note id is never treated
7
+ * as a capability on its own.
8
+ *
9
+ * Writes broadcast `notes:changed` to whoever can see the collection, the same
10
+ * way worktrees do: a note another member just created is invisible until the
11
+ * next reload without it. The event carries ids only — a note holds up to
12
+ * 200 KB, so fanning the list out on every autosave would put megabytes on the
13
+ * socket per keystroke of a long note.
14
+ */
15
+
16
+ import { t } from 'elysia';
17
+ import { createRouter } from '$shared/utils/ws-server';
18
+ import type { WSConnection } from '$shared/utils/ws-server';
19
+ import type { NoteCollection } from '$shared/types/database/schema';
20
+ import { ws as wsServer } from '../../utils/ws';
21
+ import { requireProjectAccess } from '../access';
22
+ import {
23
+ noteQueries,
24
+ noteCollectionQueries,
25
+ noteImageQueries
26
+ } from '../../database/queries/note-queries';
27
+ import { canAccessCollection } from '../../notes/access';
28
+ import { removeCollectionFiles, removeNoteFiles, resolveNoteImagePath } from '../../notes/storage';
29
+ import { unlink } from 'node:fs/promises';
30
+
31
+ const scopeSchema = t.Union([t.Literal('project'), t.Literal('global')]);
32
+
33
+ const collectionSchema = t.Object({
34
+ id: t.String(),
35
+ name: t.String(),
36
+ scope: scopeSchema,
37
+ project_id: t.Union([t.String(), t.Null()]),
38
+ created_by: t.Union([t.String(), t.Null()]),
39
+ created_at: t.String(),
40
+ updated_at: t.String()
41
+ });
42
+
43
+ const noteSchema = t.Object({
44
+ id: t.String(),
45
+ collection_id: t.String(),
46
+ title: t.Union([t.String(), t.Null()]),
47
+ content: t.String(),
48
+ created_by: t.Union([t.String(), t.Null()]),
49
+ created_at: t.String(),
50
+ updated_at: t.String(),
51
+ images: t.Array(
52
+ t.Object({
53
+ id: t.String(),
54
+ note_id: t.String(),
55
+ file_name: t.String(),
56
+ mime_type: t.String(),
57
+ size: t.Number(),
58
+ storage_path: t.String(),
59
+ created_at: t.String()
60
+ })
61
+ )
62
+ });
63
+
64
+ /** Resolve a collection and refuse the call unless this connection may see it. */
65
+ function requireCollection(conn: WSConnection, collectionId: string): NoteCollection {
66
+ const collection = noteCollectionQueries.getById(collectionId);
67
+ // Same answer for "does not exist" and "not yours", so the id space cannot be
68
+ // probed for which collections are real.
69
+ if (!collection) throw new Error('Access denied');
70
+ if (!canAccessCollection(wsServer.getUserId(conn), collection)) {
71
+ throw new Error('Access denied');
72
+ }
73
+ return collection;
74
+ }
75
+
76
+ /** Resolve the collection a note belongs to, subject to the same check. */
77
+ function requireNoteCollection(conn: WSConnection, noteId: string): NoteCollection {
78
+ const collection = noteCollectionQueries.getForNote(noteId);
79
+ if (!collection) throw new Error('Access denied');
80
+ if (!canAccessCollection(wsServer.getUserId(conn), collection)) {
81
+ throw new Error('Access denied');
82
+ }
83
+ return collection;
84
+ }
85
+
86
+ /** Check the caller may write into `scope` before anything is created there. */
87
+ function requireScope(conn: WSConnection, scope: 'project' | 'global', projectId: string | null): void {
88
+ if (scope === 'project') {
89
+ if (!projectId) throw new Error('projectId is required for the project scope');
90
+ requireProjectAccess(conn, projectId);
91
+ return;
92
+ }
93
+ // Global is instance-wide; the only requirement is a signed-in connection,
94
+ // which getUserId asserts.
95
+ wsServer.getUserId(conn);
96
+ }
97
+
98
+ /**
99
+ * Tell everyone who can see this collection that its contents moved.
100
+ *
101
+ * A project collection reaches the project room; a global one reaches every
102
+ * connection, because that is exactly the set of people allowed to read it.
103
+ */
104
+ function broadcast(collection: NoteCollection): void {
105
+ const payload = {
106
+ collectionId: collection.id,
107
+ scope: collection.scope,
108
+ projectId: collection.project_id
109
+ };
110
+ if (collection.scope === 'project' && collection.project_id) {
111
+ wsServer.emit.project(collection.project_id, 'notes:changed', payload);
112
+ } else {
113
+ wsServer.emit.global('notes:changed', payload);
114
+ }
115
+ }
116
+
117
+ export const notesRouter = createRouter()
118
+ // ---- Collections ----
119
+
120
+ .http('notes:list', {
121
+ data: t.Object({
122
+ scope: scopeSchema,
123
+ projectId: t.Optional(t.Union([t.String(), t.Null()]))
124
+ }),
125
+ response: t.Object({
126
+ collections: t.Array(collectionSchema),
127
+ notes: t.Array(noteSchema)
128
+ })
129
+ }, async ({ data, conn }) => {
130
+ const projectId = data.projectId ?? null;
131
+ requireScope(conn, data.scope, projectId);
132
+ const collections = noteCollectionQueries.listByScope(data.scope, projectId);
133
+ return {
134
+ collections,
135
+ notes: noteQueries.listByCollections(collections.map((c) => c.id))
136
+ };
137
+ })
138
+
139
+ .http('notes:create-collection', {
140
+ data: t.Object({
141
+ name: t.String({ minLength: 1 }),
142
+ scope: scopeSchema,
143
+ projectId: t.Optional(t.Union([t.String(), t.Null()]))
144
+ }),
145
+ response: t.Object({ collection: collectionSchema })
146
+ }, async ({ data, conn }) => {
147
+ const projectId = data.scope === 'project' ? (data.projectId ?? null) : null;
148
+ requireScope(conn, data.scope, projectId);
149
+ const collection = noteCollectionQueries.create({
150
+ name: data.name,
151
+ scope: data.scope,
152
+ projectId,
153
+ createdBy: wsServer.getUserId(conn)
154
+ });
155
+ broadcast(collection);
156
+ return { collection };
157
+ })
158
+
159
+ .http('notes:rename-collection', {
160
+ data: t.Object({ id: t.String({ minLength: 1 }), name: t.String({ minLength: 1 }) }),
161
+ response: t.Object({ collection: t.Union([collectionSchema, t.Null()]) })
162
+ }, async ({ data, conn }) => {
163
+ const collection = requireCollection(conn, data.id);
164
+ const renamed = noteCollectionQueries.rename(collection.id, data.name);
165
+ if (renamed) broadcast(renamed);
166
+ return { collection: renamed };
167
+ })
168
+
169
+ .http('notes:delete-collection', {
170
+ data: t.Object({ id: t.String({ minLength: 1 }) }),
171
+ response: t.Object({ ok: t.Boolean() })
172
+ }, async ({ data, conn }) => {
173
+ const collection = requireCollection(conn, data.id);
174
+ // Notes and image rows cascade with the collection; the files they point
175
+ // at do not, so the whole collection directory goes with them.
176
+ noteCollectionQueries.delete(collection.id);
177
+ await removeCollectionFiles(collection.id);
178
+ broadcast(collection);
179
+ return { ok: true };
180
+ })
181
+
182
+ // ---- Notes ----
183
+
184
+ .http('notes:get', {
185
+ data: t.Object({ id: t.String({ minLength: 1 }) }),
186
+ response: t.Object({ note: t.Union([noteSchema, t.Null()]) })
187
+ }, async ({ data, conn }) => {
188
+ requireNoteCollection(conn, data.id);
189
+ return { note: noteQueries.getById(data.id) };
190
+ })
191
+
192
+ .http('notes:create', {
193
+ data: t.Object({
194
+ // Either an explicit collection, or a scope whose default collection is
195
+ // created on first use.
196
+ collectionId: t.Optional(t.String()),
197
+ scope: t.Optional(scopeSchema),
198
+ projectId: t.Optional(t.Union([t.String(), t.Null()])),
199
+ title: t.Optional(t.Union([t.String(), t.Null()])),
200
+ content: t.Optional(t.String())
201
+ }),
202
+ response: t.Object({ note: noteSchema })
203
+ }, async ({ data, conn }) => {
204
+ const userId = wsServer.getUserId(conn);
205
+ let collection: NoteCollection;
206
+ if (data.collectionId) {
207
+ collection = requireCollection(conn, data.collectionId);
208
+ } else {
209
+ const scope = data.scope ?? 'project';
210
+ const projectId = scope === 'project' ? (data.projectId ?? null) : null;
211
+ requireScope(conn, scope, projectId);
212
+ collection = noteCollectionQueries.ensureDefault(scope, projectId, userId);
213
+ }
214
+ const note = noteQueries.create({
215
+ collectionId: collection.id,
216
+ title: data.title ?? null,
217
+ content: data.content ?? '',
218
+ createdBy: userId
219
+ });
220
+ broadcast(collection);
221
+ return { note: { ...note, images: [] } };
222
+ })
223
+
224
+ .http('notes:update', {
225
+ data: t.Object({
226
+ id: t.String({ minLength: 1 }),
227
+ title: t.Optional(t.Union([t.String(), t.Null()])),
228
+ content: t.Optional(t.String()),
229
+ collectionId: t.Optional(t.String())
230
+ }),
231
+ response: t.Object({ note: t.Union([noteSchema, t.Null()]) })
232
+ }, async ({ data, conn }) => {
233
+ const from = requireNoteCollection(conn, data.id);
234
+ // Moving a note is only allowed between collections the caller can already
235
+ // see, otherwise a move would be a way to read or plant one they cannot.
236
+ const to = data.collectionId ? requireCollection(conn, data.collectionId) : from;
237
+ const updated = noteQueries.update(data.id, {
238
+ title: data.title,
239
+ content: data.content,
240
+ collectionId: data.collectionId
241
+ });
242
+ if (!updated) return { note: null };
243
+ broadcast(from);
244
+ if (to.id !== from.id) broadcast(to);
245
+ return { note: noteQueries.getById(data.id) };
246
+ })
247
+
248
+ .http('notes:delete', {
249
+ data: t.Object({ id: t.String({ minLength: 1 }) }),
250
+ response: t.Object({ ok: t.Boolean() })
251
+ }, async ({ data, conn }) => {
252
+ const collection = requireNoteCollection(conn, data.id);
253
+ noteQueries.delete(data.id);
254
+ await removeNoteFiles(collection.id, data.id);
255
+ broadcast(collection);
256
+ return { ok: true };
257
+ })
258
+
259
+ .http('notes:delete-image', {
260
+ data: t.Object({ imageId: t.String({ minLength: 1 }) }),
261
+ response: t.Object({ ok: t.Boolean() })
262
+ }, async ({ data, conn }) => {
263
+ const img = noteImageQueries.getById(data.imageId);
264
+ if (!img) return { ok: true };
265
+ const collection = requireNoteCollection(conn, img.note_id);
266
+ const absolute = resolveNoteImagePath(img.storage_path);
267
+ if (absolute) await unlink(absolute).catch(() => {});
268
+ noteImageQueries.delete(data.imageId);
269
+ broadcast(collection);
270
+ return { ok: true };
271
+ })
272
+
273
+ // Collaborative broadcast events (Server → Client)
274
+ .emit('notes:changed', t.Object({
275
+ collectionId: t.String(),
276
+ scope: scopeSchema,
277
+ projectId: t.Union([t.String(), t.Null()])
278
+ }));