@myrialabs/clopen 0.4.38 → 0.4.39

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 (114) hide show
  1. package/backend/auth/permissions.ts +25 -0
  2. package/backend/chat/stream-manager.ts +1 -1
  3. package/backend/database/crypto/secret-columns.ts +5 -1
  4. package/backend/database/migrations/075_create_deploy_bindings.ts +54 -0
  5. package/backend/database/migrations/076_remove_memory_code_graph.ts +229 -0
  6. package/backend/database/migrations/077_create_integration_db_links.ts +150 -0
  7. package/backend/database/migrations/index.ts +21 -0
  8. package/backend/database/queries/db-client-connection-queries.ts +19 -0
  9. package/backend/database/queries/deploy-queries.ts +124 -0
  10. package/backend/database/queries/graph-queries.ts +291 -247
  11. package/backend/database/queries/index.ts +4 -0
  12. package/backend/database/queries/integration-db-link-queries.ts +168 -0
  13. package/backend/database/queries/integration-queries.ts +34 -6
  14. package/backend/db-client/integrations/index.ts +37 -0
  15. package/backend/db-client/integrations/links.ts +533 -0
  16. package/backend/db-client/integrations/projector.test.ts +280 -0
  17. package/backend/db-client/integrations/projector.ts +256 -0
  18. package/backend/db-client/integrations/supabase-service.ts +266 -0
  19. package/backend/db-client/providers/registry.ts +27 -0
  20. package/backend/db-client/providers/supabase/adapter.ts +500 -0
  21. package/backend/db-client/providers/supabase/api-types.ts +92 -0
  22. package/backend/db-client/providers/supabase/apply-migration.ts +104 -0
  23. package/backend/db-client/providers/supabase/client.ts +259 -0
  24. package/backend/db-client/providers/supabase/features.ts +502 -0
  25. package/backend/db-client/providers/supabase/local.test.ts +78 -0
  26. package/backend/db-client/providers/supabase/local.ts +137 -0
  27. package/backend/db-client/providers/types.ts +137 -0
  28. package/backend/deployments/bindings.test.ts +43 -0
  29. package/backend/deployments/bindings.ts +216 -0
  30. package/backend/deployments/index.ts +53 -0
  31. package/backend/deployments/log-streams.ts +214 -0
  32. package/backend/deployments/prompts.ts +70 -0
  33. package/backend/deployments/providers/vercel/adapter.ts +757 -0
  34. package/backend/deployments/providers/vercel/build-logs.test.ts +80 -0
  35. package/backend/deployments/providers/vercel/build-logs.ts +211 -0
  36. package/backend/deployments/providers/vercel/client.ts +203 -0
  37. package/backend/deployments/providers/vercel/list.test.ts +624 -0
  38. package/backend/deployments/providers/vercel/normalise.test.ts +115 -0
  39. package/backend/deployments/providers/vercel/normalise.ts +113 -0
  40. package/backend/deployments/providers/vercel/types.ts +104 -0
  41. package/backend/deployments/registry.ts +27 -0
  42. package/backend/deployments/service.ts +458 -0
  43. package/backend/deployments/types.ts +278 -0
  44. package/backend/index.ts +4 -0
  45. package/backend/integrations/projections/index.ts +0 -0
  46. package/backend/integrations/projections/mcp-projector.ts +7 -3
  47. package/backend/integrations/projections/types.ts +21 -9
  48. package/backend/integrations/registry/index.ts +5 -1
  49. package/backend/integrations/registry/providers/supabase.ts +61 -0
  50. package/backend/integrations/registry/providers/vercel.ts +46 -0
  51. package/backend/mcp/internal/servers/memory-graph/description.ts +3 -3
  52. package/backend/mcp/internal/servers/memory-graph/runner.ts +4 -9
  53. package/backend/mcp/internal/servers/memory-graph/schema.ts +0 -4
  54. package/backend/memory/README.md +57 -34
  55. package/backend/memory/compose.test.ts +3 -3
  56. package/backend/memory/compose.ts +6 -9
  57. package/backend/memory/config.ts +0 -5
  58. package/backend/memory/consolidate.ts +1 -2
  59. package/backend/memory/context.test.ts +8 -54
  60. package/backend/memory/context.ts +19 -25
  61. package/backend/memory/extract/episodic.ts +10 -12
  62. package/backend/memory/extract/index.ts +23 -52
  63. package/backend/memory/extract/scheduler.ts +3 -6
  64. package/backend/memory/index.ts +6 -5
  65. package/backend/memory/invalidate.ts +36 -48
  66. package/backend/memory/layout.ts +319 -130
  67. package/backend/memory/retention.ts +12 -42
  68. package/backend/memory/retrieval.eval.test.ts +2 -2
  69. package/backend/memory/retrieval.test.ts +228 -183
  70. package/backend/memory/retrieval.ts +22 -21
  71. package/backend/memory/revise.test.ts +62 -116
  72. package/backend/memory/revise.ts +0 -1
  73. package/backend/memory/view.ts +8 -5
  74. package/backend/snapshot/helpers.ts +35 -41
  75. package/backend/snapshot/snapshot-service.ts +90 -0
  76. package/backend/snapshot/turn-changes.test.ts +163 -0
  77. package/backend/snapshot/turn-changes.ts +131 -0
  78. package/backend/ws/db-client/accounts.ts +225 -0
  79. package/backend/ws/db-client/connections.ts +34 -3
  80. package/backend/ws/db-client/context.ts +37 -0
  81. package/backend/ws/db-client/index.ts +20 -1
  82. package/backend/ws/db-client/supabase.ts +188 -0
  83. package/backend/ws/deployments/actions.ts +360 -0
  84. package/backend/ws/deployments/context.ts +43 -0
  85. package/backend/ws/deployments/crud.ts +152 -0
  86. package/backend/ws/deployments/index.ts +15 -0
  87. package/backend/ws/deployments/schemas.ts +183 -0
  88. package/backend/ws/index.ts +6 -2
  89. package/backend/ws/memory/crud.ts +4 -16
  90. package/backend/ws/snapshot/changes.ts +279 -0
  91. package/backend/ws/snapshot/index.ts +4 -3
  92. package/dist/assets/{index-CyH7fSbR.js → index-BrF6nqld.js} +1 -1
  93. package/dist/assets/{index-DSHIANSy.js → index-C8Gi-b6U.js} +1 -1
  94. package/dist/assets/main-Bd3gb79F.css +1 -0
  95. package/dist/assets/main-Bo1hD7mt.js +1191 -0
  96. package/dist/index.html +2 -2
  97. package/package.json +1 -1
  98. package/shared/constants/tool-icons.ts +9 -0
  99. package/shared/types/db-client/connection.ts +6 -0
  100. package/shared/types/db-client/index.ts +2 -0
  101. package/shared/types/db-client/integrations.ts +174 -0
  102. package/shared/types/db-client/supabase.ts +131 -0
  103. package/shared/types/deployments.ts +382 -0
  104. package/shared/types/memory.ts +34 -51
  105. package/shared/types/ui/components.ts +1 -1
  106. package/shared/utils/diff-calculator.test.ts +89 -0
  107. package/shared/utils/diff-calculator.ts +30 -65
  108. package/shared/utils/logger.ts +1 -0
  109. package/backend/memory/extract/languages.ts +0 -176
  110. package/backend/memory/extract/structural.test.ts +0 -215
  111. package/backend/memory/extract/structural.ts +0 -364
  112. package/backend/ws/snapshot/content.ts +0 -85
  113. package/dist/assets/main-D2IOjftb.css +0 -1
  114. package/dist/assets/main-DM-tHKbW.js +0 -1152
@@ -0,0 +1,259 @@
1
+ /**
2
+ * A small Supabase Management API client — only what DB Client needs.
3
+ *
4
+ * No SDK, for the reason the Vercel and GitHub clients have none: this is a
5
+ * handful of plain JSON calls, and an SDK would add a dependency tree we then
6
+ * have to keep Bun-compatible for no capability we use.
7
+ *
8
+ * Every path in this file was read out of the published OpenAPI document at
9
+ * `https://api.supabase.com/api/v1-json` rather than inferred from a sibling.
10
+ * Two things there are worth knowing before changing anything:
11
+ *
12
+ * - `POST /v1/projects/{ref}/database/query` exists and is marked BETA. It is
13
+ * deliberately unused: everything inside the database is read through the
14
+ * Postgres connection DB Client already holds, which keeps a `supabase start`
15
+ * stack working without an access token and keeps us off a beta endpoint for
16
+ * queries we can make directly.
17
+ * - There is NO endpoint that reads a project's database password back.
18
+ * `/v1/projects/{ref}/database/password` is PATCH-only, by design. That single
19
+ * fact is why a link stores a password of its own.
20
+ */
21
+
22
+ const SUPABASE_API_BASE = 'https://api.supabase.com';
23
+
24
+ /**
25
+ * Two budgets, the same split the Vercel client settled on. A read answers
26
+ * quickly; generating TypeScript types for a large schema does not, and
27
+ * aborting it mid-flight reports a timeout for work the server completed.
28
+ */
29
+ const READ_TIMEOUT_MS = 20_000;
30
+ const SLOW_TIMEOUT_MS = 120_000;
31
+
32
+ export class SupabaseError extends Error {
33
+ constructor(
34
+ message: string,
35
+ readonly status: number,
36
+ readonly kind: 'auth' | 'config' | 'rate-limit' | 'error'
37
+ ) {
38
+ super(message);
39
+ this.name = 'SupabaseError';
40
+ }
41
+ }
42
+
43
+ export interface SupabaseCredentials {
44
+ accessToken: string;
45
+ }
46
+
47
+ /**
48
+ * Classic or scoped, read from the prefix.
49
+ *
50
+ * Supabase prefixes a scoped personal access token `sbp_fc` and a classic
51
+ * full-access one plain `sbp_`. That one character of information is worth a
52
+ * great deal, because a scoped token missing a permission fails with an
53
+ * undecorated "Forbidden" — the same undiagnosable shape GitHub's fine-grained
54
+ * tokens produced in `Task 2`, and answered the same way: read the prefix and
55
+ * name the likely cause rather than repeating the provider's word for it.
56
+ */
57
+ export function tokenKindOf(token: string): 'scoped' | 'classic' {
58
+ return token.startsWith('sbp_fc') ? 'scoped' : 'classic';
59
+ }
60
+
61
+ /** Which permission a 403 on a given path most likely needs. */
62
+ function missingScopeHint(path: string): string | null {
63
+ if (path.startsWith('/v1/organizations/')) return 'Organization Settings (Read)';
64
+ if (path === '/v1/organizations') return 'Organizations (Read)';
65
+ if (path === '/v1/projects') return 'Organization Projects (Read-write) to create, Projects (account-wide) Read to list';
66
+ if (path.includes('/types/typescript')) return 'Database (Read)';
67
+ if (path.includes('/functions')) return 'Edge Functions (Read)';
68
+ if (path.includes('/advisors/')) return 'Project Settings (Read)';
69
+ if (path.includes('/config/database/pooler')) return 'Project Settings (Read)';
70
+ return null;
71
+ }
72
+
73
+ /**
74
+ * Map a failed response onto something the hub and the panel can act on.
75
+ *
76
+ * Supabase's own message is kept: it is the most specific thing anyone will
77
+ * see. The classification is ours, because the hub's status strip understands
78
+ * four states and no more.
79
+ */
80
+ async function toError(
81
+ response: Response,
82
+ context: { path: string; token: string }
83
+ ): Promise<SupabaseError> {
84
+ let message = response.statusText || `HTTP ${response.status}`;
85
+ try {
86
+ const body = await response.json() as { message?: unknown; error?: unknown; msg?: unknown };
87
+ for (const candidate of [body.message, body.error, body.msg]) {
88
+ if (typeof candidate === 'string' && candidate.trim()) {
89
+ message = candidate;
90
+ break;
91
+ }
92
+ }
93
+ } catch {
94
+ // Non-JSON body — the status line is all we have.
95
+ }
96
+
97
+ if (response.status === 401) {
98
+ return new SupabaseError(
99
+ `${message}. The access token is invalid or was revoked — create a new one at supabase.com/dashboard/account/tokens.`,
100
+ 401,
101
+ 'auth'
102
+ );
103
+ }
104
+ if (response.status === 403) {
105
+ // The most common cause by far, and the one the provider never names.
106
+ // A classic token's 403 really is about membership; a scoped token's is
107
+ // almost always a permission that was not ticked when it was created.
108
+ const scope = missingScopeHint(context.path);
109
+ const detail = tokenKindOf(context.token) === 'scoped'
110
+ ? `This is a SCOPED token${scope ? `, and this call needs ${scope}` : ''}. Scoped tokens only carry the permissions picked when they were created — regenerate it with that permission, or use a classic token.`
111
+ : "This token's user does not have access here — a token belongs to one Supabase user, and organisation access follows that user's membership.";
112
+ return new SupabaseError(`${message}. ${detail}`, 403, 'config');
113
+ }
114
+ if (response.status === 404) {
115
+ return new SupabaseError(
116
+ `${message}. The project does not exist, or this token cannot see it.`,
117
+ 404,
118
+ 'config'
119
+ );
120
+ }
121
+ if (response.status === 429) {
122
+ return new SupabaseError('Supabase rate limit reached. Try again shortly.', 429, 'rate-limit');
123
+ }
124
+ return new SupabaseError(message, response.status, 'error');
125
+ }
126
+
127
+ /**
128
+ * What the Management API says about how much budget is left.
129
+ *
130
+ * Supabase does not document these, but every response carries them — verified
131
+ * against a live account: `x-ratelimit-limit: 120`, `x-ratelimit-remaining`,
132
+ * and `x-ratelimit-reset: 60`. The budget is per MINUTE, not per hour.
133
+ *
134
+ * `x-ratelimit-reset` is SECONDS FROM NOW, not an epoch timestamp. GitHub and
135
+ * Vercel both send an epoch there, and reading this one the same way dated
136
+ * every reset to January 1970 — the footer would have said "resets 07:01:00"
137
+ * and nobody would have known why.
138
+ *
139
+ * Absent means "not reported", never "none left", so a missing header shows
140
+ * nothing rather than an alarming zero.
141
+ */
142
+ export interface SupabaseRateLimit {
143
+ remaining: number;
144
+ limit: number;
145
+ resetAt: string | null;
146
+ }
147
+
148
+ /**
149
+ * Last reading PER TOKEN, not per process.
150
+ *
151
+ * The limit is counted per Supabase user, so two connected accounts have two
152
+ * separate budgets and one global figure would attribute one account's usage to
153
+ * the other. The token is used as the map key and nothing more — it never
154
+ * leaves this module, and it is already in memory on the object being passed.
155
+ */
156
+ const rateLimits = new Map<string, SupabaseRateLimit>();
157
+
158
+ /** The most recent rate-limit reading for one account, for the surface's footer. */
159
+ export function getSupabaseRateLimit(credentials: SupabaseCredentials): SupabaseRateLimit | null {
160
+ return rateLimits.get(credentials.accessToken) ?? null;
161
+ }
162
+
163
+ /**
164
+ * Take a reading if this account has never produced one.
165
+ *
166
+ * The footer is rendered from the connection context, and resolving that
167
+ * context touches no Management API at all — the default tab is pure SQL — so
168
+ * on a fresh server the quota had nothing to show and simply never appeared.
169
+ * One cheap request the first time an account is looked at fixes that for the
170
+ * process's lifetime; every later call refreshes the reading for free, because
171
+ * the headers ride on responses we were making anyway.
172
+ *
173
+ * Failure is ignored: this exists to populate a footer, and nothing depends on
174
+ * it succeeding.
175
+ */
176
+ export async function primeSupabaseRateLimit(
177
+ credentials: SupabaseCredentials,
178
+ ref: string
179
+ ): Promise<void> {
180
+ if (rateLimits.has(credentials.accessToken)) return;
181
+ try {
182
+ await supabaseRequest(credentials, `/v1/projects/${encodeURIComponent(ref)}`);
183
+ } catch {
184
+ // A token that cannot read the project still cannot report a budget.
185
+ }
186
+ }
187
+
188
+ function readRateLimit(token: string, headers: Headers): void {
189
+ const remaining = headers.get('x-ratelimit-remaining');
190
+ const limit = headers.get('x-ratelimit-limit');
191
+ if (remaining === null || limit === null) return;
192
+
193
+ const remainingValue = Number(remaining);
194
+ const limitValue = Number(limit);
195
+ if (!Number.isFinite(remainingValue) || !Number.isFinite(limitValue)) return;
196
+
197
+ const reset = headers.get('x-ratelimit-reset');
198
+ const resetValue = reset === null ? NaN : Number(reset);
199
+ rateLimits.set(token, {
200
+ remaining: remainingValue,
201
+ limit: limitValue,
202
+ // A DURATION in seconds, resolved against now. See the note above: reading
203
+ // it as an epoch is the mistake this comment exists to stop.
204
+ resetAt: Number.isFinite(resetValue) ? new Date(Date.now() + resetValue * 1000).toISOString() : null
205
+ });
206
+ }
207
+
208
+ export interface SupabaseRequestOptions {
209
+ method?: 'GET' | 'POST' | 'PATCH' | 'DELETE';
210
+ body?: unknown;
211
+ query?: Record<string, string | number | undefined | null>;
212
+ timeoutMs?: number;
213
+ }
214
+
215
+ function buildUrl(path: string, query?: SupabaseRequestOptions['query']): string {
216
+ const url = new URL(`${SUPABASE_API_BASE}${path}`);
217
+ for (const [key, value] of Object.entries(query ?? {})) {
218
+ if (value === undefined || value === null || value === '') continue;
219
+ url.searchParams.set(key, String(value));
220
+ }
221
+ return url.toString();
222
+ }
223
+
224
+ export async function supabaseRequest<T>(
225
+ credentials: SupabaseCredentials,
226
+ path: string,
227
+ options: SupabaseRequestOptions = {}
228
+ ): Promise<T> {
229
+ const method = options.method ?? 'GET';
230
+ const headers: Record<string, string> = {
231
+ Authorization: `Bearer ${credentials.accessToken}`,
232
+ 'User-Agent': 'clopen'
233
+ };
234
+ if (options.body !== undefined) headers['Content-Type'] = 'application/json';
235
+
236
+ let response: Response;
237
+ try {
238
+ response = await fetch(buildUrl(path, options.query), {
239
+ method,
240
+ headers,
241
+ ...(options.body !== undefined && { body: JSON.stringify(options.body) }),
242
+ signal: AbortSignal.timeout(options.timeoutMs ?? READ_TIMEOUT_MS)
243
+ });
244
+ } catch (error) {
245
+ const detail = error instanceof Error ? error.message : String(error);
246
+ throw new SupabaseError(`Could not reach Supabase: ${detail}`, 0, 'error');
247
+ }
248
+
249
+ // Read before the status check: a 429 is precisely when the remaining count
250
+ // is worth knowing.
251
+ readRateLimit(credentials.accessToken, response.headers);
252
+ if (!response.ok) throw await toError(response, { path, token: credentials.accessToken });
253
+
254
+ const text = await response.text();
255
+ return (text ? JSON.parse(text) : null) as T;
256
+ }
257
+
258
+ /** The budget for calls that do real work upstream, such as type generation. */
259
+ export const SUPABASE_SLOW_TIMEOUT_MS = SLOW_TIMEOUT_MS;