@myrialabs/clopen 0.4.37 → 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 (193) hide show
  1. package/README.md +2 -2
  2. package/backend/auth/permissions.ts +39 -0
  3. package/backend/bootstrap.ts +16 -0
  4. package/backend/chat/stream-manager.ts +1 -1
  5. package/backend/database/crypto/envelope.test.ts +93 -0
  6. package/backend/database/crypto/envelope.ts +127 -0
  7. package/backend/database/crypto/index.ts +22 -0
  8. package/backend/database/crypto/master-key.ts +129 -0
  9. package/backend/database/crypto/secret-columns.ts +151 -0
  10. package/backend/database/migrations/071_create_notes_tables.ts +90 -0
  11. package/backend/database/migrations/072_encrypt_stored_secrets.ts +107 -0
  12. package/backend/database/migrations/073_create_integration_tables.ts +119 -0
  13. package/backend/database/migrations/074_create_work_tables.ts +94 -0
  14. package/backend/database/migrations/075_create_deploy_bindings.ts +54 -0
  15. package/backend/database/migrations/076_remove_memory_code_graph.ts +229 -0
  16. package/backend/database/migrations/077_create_integration_db_links.ts +150 -0
  17. package/backend/database/migrations/index.ts +49 -0
  18. package/backend/database/queries/db-client-connection-queries.ts +42 -12
  19. package/backend/database/queries/deploy-queries.ts +124 -0
  20. package/backend/database/queries/engine-queries.ts +23 -10
  21. package/backend/database/queries/graph-queries.ts +291 -247
  22. package/backend/database/queries/index.ts +10 -1
  23. package/backend/database/queries/integration-db-link-queries.ts +168 -0
  24. package/backend/database/queries/integration-queries.ts +325 -0
  25. package/backend/database/queries/mcp-server-queries.ts +38 -11
  26. package/backend/database/queries/note-queries.test.ts +190 -0
  27. package/backend/database/queries/note-queries.ts +269 -0
  28. package/backend/database/queries/profile-queries.ts +1 -1
  29. package/backend/database/queries/ssh-connection-queries.ts +19 -8
  30. package/backend/database/queries/work-queries.ts +210 -0
  31. package/backend/db-client/integrations/index.ts +37 -0
  32. package/backend/db-client/integrations/links.ts +533 -0
  33. package/backend/db-client/integrations/projector.test.ts +280 -0
  34. package/backend/db-client/integrations/projector.ts +256 -0
  35. package/backend/db-client/integrations/supabase-service.ts +266 -0
  36. package/backend/db-client/providers/registry.ts +27 -0
  37. package/backend/db-client/providers/supabase/adapter.ts +500 -0
  38. package/backend/db-client/providers/supabase/api-types.ts +92 -0
  39. package/backend/db-client/providers/supabase/apply-migration.ts +104 -0
  40. package/backend/db-client/providers/supabase/client.ts +259 -0
  41. package/backend/db-client/providers/supabase/features.ts +502 -0
  42. package/backend/db-client/providers/supabase/local.test.ts +78 -0
  43. package/backend/db-client/providers/supabase/local.ts +137 -0
  44. package/backend/db-client/providers/types.ts +137 -0
  45. package/backend/deployments/bindings.test.ts +43 -0
  46. package/backend/deployments/bindings.ts +216 -0
  47. package/backend/deployments/index.ts +53 -0
  48. package/backend/deployments/log-streams.ts +214 -0
  49. package/backend/deployments/prompts.ts +70 -0
  50. package/backend/deployments/providers/vercel/adapter.ts +757 -0
  51. package/backend/deployments/providers/vercel/build-logs.test.ts +80 -0
  52. package/backend/deployments/providers/vercel/build-logs.ts +211 -0
  53. package/backend/deployments/providers/vercel/client.ts +203 -0
  54. package/backend/deployments/providers/vercel/list.test.ts +624 -0
  55. package/backend/deployments/providers/vercel/normalise.test.ts +115 -0
  56. package/backend/deployments/providers/vercel/normalise.ts +113 -0
  57. package/backend/deployments/providers/vercel/types.ts +104 -0
  58. package/backend/deployments/registry.ts +27 -0
  59. package/backend/deployments/service.ts +458 -0
  60. package/backend/deployments/types.ts +278 -0
  61. package/backend/engine/docs/artifacts.md +22 -9
  62. package/backend/files/os-clipboard.test.ts +209 -0
  63. package/backend/files/os-clipboard.ts +567 -0
  64. package/backend/http/integration-hooks.ts +42 -0
  65. package/backend/http/notes-images.test.ts +228 -0
  66. package/backend/http/notes-images.ts +196 -0
  67. package/backend/index.ts +13 -0
  68. package/backend/integrations/accounts.ts +229 -0
  69. package/backend/integrations/health.ts +146 -0
  70. package/backend/integrations/index.ts +36 -0
  71. package/backend/integrations/projections/index.ts +0 -0
  72. package/backend/integrations/projections/mcp-projector.test.ts +204 -0
  73. package/backend/integrations/projections/mcp-projector.ts +163 -0
  74. package/backend/integrations/projections/types.ts +63 -0
  75. package/backend/integrations/registry/define.ts +38 -0
  76. package/backend/integrations/registry/index.ts +60 -0
  77. package/backend/integrations/registry/providers/context7.ts +44 -0
  78. package/backend/integrations/registry/providers/firecrawl.ts +41 -0
  79. package/backend/integrations/registry/providers/github.ts +78 -0
  80. package/backend/integrations/registry/providers/supabase.ts +61 -0
  81. package/backend/integrations/registry/providers/vercel.ts +46 -0
  82. package/backend/integrations/registry/types.ts +96 -0
  83. package/backend/integrations/webhooks/gateway.ts +160 -0
  84. package/backend/integrations/webhooks/verify.ts +65 -0
  85. package/backend/mcp/README.md +25 -3
  86. package/backend/mcp/external/config.ts +35 -1
  87. package/backend/mcp/index.ts +1 -1
  88. package/backend/mcp/internal/config.ts +1 -1
  89. package/backend/mcp/internal/servers/memory-graph/description.ts +3 -3
  90. package/backend/mcp/internal/servers/memory-graph/runner.ts +4 -9
  91. package/backend/mcp/internal/servers/memory-graph/schema.ts +0 -4
  92. package/backend/memory/README.md +57 -34
  93. package/backend/memory/compose.test.ts +3 -3
  94. package/backend/memory/compose.ts +6 -9
  95. package/backend/memory/config.ts +0 -5
  96. package/backend/memory/consolidate.ts +1 -2
  97. package/backend/memory/context.test.ts +8 -54
  98. package/backend/memory/context.ts +19 -25
  99. package/backend/memory/extract/episodic.ts +10 -12
  100. package/backend/memory/extract/index.ts +23 -52
  101. package/backend/memory/extract/scheduler.ts +3 -6
  102. package/backend/memory/index.ts +6 -5
  103. package/backend/memory/invalidate.ts +36 -48
  104. package/backend/memory/layout.ts +319 -130
  105. package/backend/memory/retention.ts +12 -42
  106. package/backend/memory/retrieval.eval.test.ts +2 -2
  107. package/backend/memory/retrieval.test.ts +228 -183
  108. package/backend/memory/retrieval.ts +22 -21
  109. package/backend/memory/revise.test.ts +62 -116
  110. package/backend/memory/revise.ts +0 -1
  111. package/backend/memory/view.ts +8 -5
  112. package/backend/notes/access.test.ts +82 -0
  113. package/backend/notes/access.ts +27 -0
  114. package/backend/notes/storage.test.ts +77 -0
  115. package/backend/notes/storage.ts +114 -0
  116. package/backend/permissions/service.ts +2 -2
  117. package/backend/profiles/service.ts +1 -1
  118. package/backend/projects/project-cleanup.ts +6 -0
  119. package/backend/snapshot/helpers.ts +35 -41
  120. package/backend/snapshot/snapshot-service.ts +90 -0
  121. package/backend/snapshot/turn-changes.test.ts +163 -0
  122. package/backend/snapshot/turn-changes.ts +131 -0
  123. package/backend/work/bindings.ts +124 -0
  124. package/backend/work/index.ts +42 -0
  125. package/backend/work/prompts.ts +150 -0
  126. package/backend/work/providers/github/actions-logs.ts +180 -0
  127. package/backend/work/providers/github/adapter.test.ts +88 -0
  128. package/backend/work/providers/github/adapter.ts +1255 -0
  129. package/backend/work/providers/github/client.ts +280 -0
  130. package/backend/work/providers/github/list-range.test.ts +158 -0
  131. package/backend/work/providers/github/token-kind.test.ts +42 -0
  132. package/backend/work/pull-requests.ts +242 -0
  133. package/backend/work/registry.ts +27 -0
  134. package/backend/work/service.ts +436 -0
  135. package/backend/work/start-work.test.ts +71 -0
  136. package/backend/work/start-work.ts +232 -0
  137. package/backend/work/types.ts +180 -0
  138. package/backend/ws/db-client/accounts.ts +225 -0
  139. package/backend/ws/db-client/connections.ts +34 -3
  140. package/backend/ws/db-client/context.ts +37 -0
  141. package/backend/ws/db-client/index.ts +20 -1
  142. package/backend/ws/db-client/supabase.ts +188 -0
  143. package/backend/ws/deployments/actions.ts +360 -0
  144. package/backend/ws/deployments/context.ts +43 -0
  145. package/backend/ws/deployments/crud.ts +152 -0
  146. package/backend/ws/deployments/index.ts +15 -0
  147. package/backend/ws/deployments/schemas.ts +183 -0
  148. package/backend/ws/files/clipboard.ts +78 -0
  149. package/backend/ws/files/index.ts +5 -0
  150. package/backend/ws/git/diff-budget.ts +70 -11
  151. package/backend/ws/index.ts +16 -2
  152. package/backend/ws/integrations/crud.ts +219 -0
  153. package/backend/ws/integrations/index.ts +22 -0
  154. package/backend/ws/mcp/crud.ts +25 -1
  155. package/backend/ws/memory/crud.ts +4 -16
  156. package/backend/ws/notes/index.ts +278 -0
  157. package/backend/ws/profiles/crud.ts +1 -1
  158. package/backend/ws/snapshot/changes.ts +279 -0
  159. package/backend/ws/snapshot/index.ts +4 -3
  160. package/backend/ws/work/actions.ts +206 -0
  161. package/backend/ws/work/context.ts +51 -0
  162. package/backend/ws/work/crud.ts +347 -0
  163. package/backend/ws/work/index.ts +17 -0
  164. package/backend/ws/work/pull-requests.ts +177 -0
  165. package/backend/ws/work/schemas.ts +226 -0
  166. package/dist/assets/{index-sJmS_CCm.js → index-BrF6nqld.js} +1 -1
  167. package/dist/assets/{index-Bik9TCBi.js → index-C8Gi-b6U.js} +1 -1
  168. package/dist/assets/main-Bd3gb79F.css +1 -0
  169. package/dist/assets/main-Bo1hD7mt.js +1191 -0
  170. package/dist/index.html +2 -2
  171. package/package.json +1 -1
  172. package/shared/constants/engine-tools.ts +1 -1
  173. package/shared/constants/tool-icons.ts +42 -0
  174. package/shared/types/database/schema.ts +41 -0
  175. package/shared/types/db-client/connection.ts +6 -0
  176. package/shared/types/db-client/index.ts +2 -0
  177. package/shared/types/db-client/integrations.ts +174 -0
  178. package/shared/types/db-client/supabase.ts +131 -0
  179. package/shared/types/deployments.ts +382 -0
  180. package/shared/types/integrations.ts +140 -0
  181. package/shared/types/memory.ts +34 -51
  182. package/shared/types/stores/settings.ts +8 -0
  183. package/shared/types/ui/components.ts +1 -1
  184. package/shared/types/work.ts +426 -0
  185. package/shared/utils/diff-calculator.test.ts +89 -0
  186. package/shared/utils/diff-calculator.ts +30 -65
  187. package/shared/utils/logger.ts +4 -0
  188. package/backend/memory/extract/languages.ts +0 -176
  189. package/backend/memory/extract/structural.test.ts +0 -215
  190. package/backend/memory/extract/structural.ts +0 -364
  191. package/backend/ws/snapshot/content.ts +0 -85
  192. package/dist/assets/main-DLqolBI2.css +0 -1
  193. package/dist/assets/main-Df1I3hnw.js +0 -1096
@@ -0,0 +1,757 @@
1
+ /**
2
+ * Vercel — the first provider behind the Deployments surface.
3
+ *
4
+ * Three things here are Vercel facts that the interface deliberately absorbs so
5
+ * no other provider inherits them:
6
+ *
7
+ * TEAMS. One token reaches a personal account and every team the user belongs
8
+ * to, and a request that omits `teamId` simply does not see that team's
9
+ * projects — an empty list, not an error. So the team travels on the BINDING,
10
+ * not on the account: which team a project belongs to is a fact about the
11
+ * project you picked, and putting it on the credential would force a second
12
+ * connect for a second team with the same token.
13
+ *
14
+ * PREVIEW IS NOT A FILTER. `target` is `production` for a production build and
15
+ * NULL for a preview one; there is no `target=preview` to send. Production
16
+ * filters server-side, everything else is filtered here — which means a page
17
+ * can come back nearly empty on a busy project, so the filtered paths fill the
18
+ * page rather than returning whatever survived one request. That is the same
19
+ * mistake the Issues list made with `state=all`, fixed here before it shipped.
20
+ *
21
+ * LIVE IS NOT A STATE. `readyState: READY` and `target: production` together do
22
+ * not mean a build is serving traffic — a superseded or rolled-back-away-from
23
+ * deployment is both. The project's `targets.production.id` is the only honest
24
+ * answer, so it is read once per list and passed down.
25
+ */
26
+
27
+ import { readFile } from 'fs/promises';
28
+ import { join } from 'path';
29
+ import type {
30
+ BuildLogBundle,
31
+ Deployment,
32
+ DeploymentDetail,
33
+ DeploymentDraft,
34
+ DeploymentPage,
35
+ DeployProjectStatus,
36
+ DeployTarget,
37
+ NewProjectDraft
38
+ } from '$shared/types/deployments';
39
+ import type {
40
+ AdapterDeployInfo,
41
+ DeployContext,
42
+ RepositoryAccess,
43
+ DeployProviderAdapter,
44
+ DeploymentQuery,
45
+ LogStreamCallbacks,
46
+ LogStreamHandle,
47
+ ResolvedDeployBinding,
48
+ UnboundDeployContext
49
+ } from '../../types';
50
+ import { vercelRequest, VercelError, type VercelCredentials } from './client';
51
+ import { durationOf, toDeployment, toEnvironment } from './normalise';
52
+ import { fetchBuildLogs, streamBuildLogs } from './build-logs';
53
+ import type {
54
+ VercelDeployment,
55
+ VercelGitNamespace,
56
+ VercelDeploymentList,
57
+ VercelProject,
58
+ VercelProjectList,
59
+ VercelTeamList,
60
+ VercelUser
61
+ } from './types';
62
+ import { debug } from '$shared/utils/logger';
63
+
64
+ /** Rows asked for per provider request. */
65
+ const PAGE_SIZE = 20;
66
+ /**
67
+ * Provider requests one filtered page may spend.
68
+ *
69
+ * Bounded because the preview filter discards rows: on a project that deploys
70
+ * production hourly, filling a page of previews could otherwise walk the whole
71
+ * deployment history. Four pages is enough to fill a screen and small enough to
72
+ * be invisible on the rate limit.
73
+ */
74
+ const MAX_FILL_REQUESTS = 4;
75
+ /** Teams scanned when listing targets, so a large org cannot fan out unbounded. */
76
+ const MAX_TEAMS = 20;
77
+
78
+ function credentialsOf(context: UnboundDeployContext): VercelCredentials {
79
+ return { token: context.credentials.token ?? '' };
80
+ }
81
+
82
+ /** `owner/repo` for a project's connected repository, when it has one. */
83
+ function repoOf(project: VercelProject): string | null {
84
+ const org = project.link?.org;
85
+ const repo = project.link?.repo;
86
+ return org && repo ? `${org}/${repo}` : null;
87
+ }
88
+
89
+ function toTarget(project: VercelProject, team: { id: string; name: string } | null): DeployTarget {
90
+ return {
91
+ id: project.id,
92
+ name: project.name,
93
+ teamId: team?.id ?? null,
94
+ teamName: team?.name ?? null,
95
+ framework: project.framework ?? null,
96
+ gitRepo: repoOf(project)
97
+ };
98
+ }
99
+
100
+ /** The project row, which is also where "what is live" is read from. */
101
+ async function fetchProject(
102
+ credentials: VercelCredentials,
103
+ locator: string,
104
+ teamId: string | null
105
+ ): Promise<VercelProject> {
106
+ const response = await vercelRequest<VercelProject>(
107
+ credentials,
108
+ `/v9/projects/${encodeURIComponent(locator)}`,
109
+ { query: { teamId: teamId ?? undefined } }
110
+ );
111
+ return response.data;
112
+ }
113
+
114
+ function currentProductionIdOf(project: VercelProject): string | null {
115
+ const production = project.targets?.production;
116
+ return production?.id ?? null;
117
+ }
118
+
119
+ export const vercelDeployAdapter: DeployProviderAdapter = {
120
+ provider: 'vercel',
121
+
122
+ capabilities: {
123
+ logs: true,
124
+ streamLogs: true,
125
+ createDeployment: true,
126
+ createProject: true,
127
+ connectRepository: true,
128
+ deleteDeployment: true,
129
+ redeploy: true,
130
+ cancel: true,
131
+ rollback: true,
132
+ promote: true,
133
+ environments: true,
134
+ branchFilter: true
135
+ },
136
+
137
+ /**
138
+ * Read `.vercel/project.json`, which `vercel link` writes.
139
+ *
140
+ * `orgId` is a team id only when it looks like one: a personal account's id
141
+ * is also stored in that field, and sending it as `teamId` turns every
142
+ * subsequent call into a 403 for a team the user does not belong to.
143
+ */
144
+ async detectFromProject(projectRoot: string) {
145
+ try {
146
+ const raw = await readFile(join(projectRoot, '.vercel', 'project.json'), 'utf8');
147
+ const parsed = JSON.parse(raw) as { projectId?: unknown; orgId?: unknown };
148
+ if (typeof parsed.projectId !== 'string' || !parsed.projectId) return null;
149
+
150
+ const orgId = typeof parsed.orgId === 'string' ? parsed.orgId : '';
151
+ return {
152
+ locator: parsed.projectId,
153
+ teamId: orgId.startsWith('team_') ? orgId : null
154
+ };
155
+ } catch {
156
+ // No link file, or one we cannot read. Both mean "nothing to detect".
157
+ return null;
158
+ }
159
+ },
160
+
161
+ /**
162
+ * Every project this credential can reach, each one once.
163
+ *
164
+ * The scoped listing and the default listing OVERLAP. `/v10/projects` with no
165
+ * `teamId` returns the token's default scope, and when that default is one of
166
+ * the user's teams the same project also arrives under that team — so a naive
167
+ * concatenation lists it twice.
168
+ *
169
+ * Which copy survives is the part that matters, and it is not a tie. A
170
+ * project id is globally unique, so the two entries describe one project, but
171
+ * only one of them carries the `teamId` that every later call needs: reading
172
+ * the deployment list, the logs and every action all 404 for a team project
173
+ * addressed without its team. So a team-scoped entry always replaces an
174
+ * unscoped one, never the other way round. Position is kept, because the
175
+ * caller orders these by git-remote match afterwards.
176
+ */
177
+ async listTargets(context) {
178
+ const credentials = credentialsOf(context);
179
+ const byId = new Map<string, DeployTarget>();
180
+
181
+ const add = (target: DeployTarget): void => {
182
+ const existing = byId.get(target.id);
183
+ if (existing && existing.teamId !== null && target.teamId === null) return;
184
+ byId.set(target.id, target);
185
+ };
186
+
187
+ const personal = await vercelRequest<VercelProjectList>(credentials, '/v10/projects', {
188
+ query: { limit: 100 }
189
+ });
190
+ for (const project of personal.data?.projects ?? []) add(toTarget(project, null));
191
+
192
+ let teams: VercelTeamList['teams'] = [];
193
+ try {
194
+ const response = await vercelRequest<VercelTeamList>(credentials, '/v2/teams', {
195
+ query: { limit: MAX_TEAMS }
196
+ });
197
+ teams = response.data?.teams ?? [];
198
+ } catch (error) {
199
+ // A token scoped to one project cannot list teams, and that is not a
200
+ // reason to show the user nothing — the default-scope projects stand.
201
+ debug.log('deployments', 'Could not list Vercel teams:', error);
202
+ }
203
+
204
+ for (const team of teams.slice(0, MAX_TEAMS)) {
205
+ try {
206
+ const response = await vercelRequest<VercelProjectList>(credentials, '/v10/projects', {
207
+ query: { limit: 100, teamId: team.id }
208
+ });
209
+ const label = { id: team.id, name: team.name || team.slug || team.id };
210
+ for (const project of response.data?.projects ?? []) add(toTarget(project, label));
211
+ } catch (error) {
212
+ debug.log('deployments', `Could not list projects for team ${team.id}:`, error);
213
+ }
214
+ }
215
+
216
+ return [...byId.values()];
217
+ },
218
+
219
+ async describeTarget(context, locator, teamId) {
220
+ try {
221
+ const project = await fetchProject(credentialsOf(context), locator, teamId);
222
+ return toTarget(project, teamId ? { id: teamId, name: teamId } : null);
223
+ } catch (error) {
224
+ debug.log('deployments', `Could not describe Vercel project ${locator}:`, error);
225
+ return null;
226
+ }
227
+ },
228
+
229
+ /**
230
+ * Two questions, answered separately.
231
+ *
232
+ * Whether the token works at all, and whether it reaches the bound project.
233
+ * Collapsing them would report a perfectly good token as broken because a
234
+ * project was deleted, and send the user to re-issue a credential that was
235
+ * never the problem.
236
+ */
237
+ async probe(context, binding: ResolvedDeployBinding | null) {
238
+ const credentials = credentialsOf(context);
239
+ if (!credentials.token) {
240
+ return { status: 'needs_auth' as const, detail: 'No access token is stored for this account.' };
241
+ }
242
+
243
+ let viewer: string | null = null;
244
+ try {
245
+ const response = await vercelRequest<VercelUser>(credentials, '/v2/user');
246
+ viewer = response.data?.user?.username ?? response.data?.user?.email ?? null;
247
+ } catch (error) {
248
+ if (error instanceof VercelError) {
249
+ return {
250
+ status: error.kind === 'auth' ? ('needs_auth' as const) : ('error' as const),
251
+ detail: error.message
252
+ };
253
+ }
254
+ return { status: 'error' as const, detail: error instanceof Error ? error.message : String(error) };
255
+ }
256
+
257
+ if (!binding) {
258
+ return {
259
+ status: 'ok' as const,
260
+ detail: viewer ? `Signed in as ${viewer}. No project is bound yet.` : 'No project is bound yet.'
261
+ };
262
+ }
263
+
264
+ try {
265
+ const project = await fetchProject(credentials, binding.locator, binding.teamId);
266
+ return { status: 'ok' as const, detail: `${viewer ? `${viewer} · ` : ''}${project.name}` };
267
+ } catch (error) {
268
+ const detail = error instanceof VercelError ? error.message : String(error);
269
+ return { status: 'needs_config' as const, detail };
270
+ }
271
+ },
272
+
273
+ async list(context: DeployContext, query: DeploymentQuery): Promise<DeploymentPage> {
274
+ const credentials = credentialsOf(context);
275
+ const { locator, teamId } = context.binding;
276
+
277
+ const project = await fetchProject(credentials, locator, teamId);
278
+ const currentProductionId = currentProductionIdOf(project);
279
+
280
+ const limit = query.limit ?? PAGE_SIZE;
281
+ const wantsServerFilter = query.environment === 'production';
282
+
283
+ const items: Deployment[] = [];
284
+ // A row seen twice across fill iterations is a crash, not a cosmetic
285
+ // problem: the list is keyed by id, and a build landing mid-fill can shift
286
+ // the timestamp window so a page repeats one.
287
+ const seen = new Set<string>();
288
+ let cursor = query.cursor ? Number(query.cursor) : undefined;
289
+ let rateLimit = null as DeploymentPage['rateLimit'];
290
+ let hasMore = false;
291
+ let requests = 0;
292
+
293
+ // Fill the page rather than returning whatever one request left behind.
294
+ // The preview and custom filters discard rows after the fact, so a single
295
+ // request against a production-heavy project can answer with almost
296
+ // nothing while more pages clearly exist.
297
+ while (items.length < limit && requests < MAX_FILL_REQUESTS) {
298
+ requests += 1;
299
+
300
+ const response = await vercelRequest<VercelDeploymentList>(credentials, '/v7/deployments', {
301
+ query: {
302
+ projectId: locator,
303
+ teamId: teamId ?? undefined,
304
+ limit,
305
+ until: cursor,
306
+ target: wantsServerFilter ? 'production' : undefined,
307
+ branch: query.branch || undefined
308
+ }
309
+ });
310
+ rateLimit = response.rateLimit ?? rateLimit;
311
+
312
+ const page = response.data?.deployments ?? [];
313
+ for (const raw of page) {
314
+ const deployment = toDeployment(raw, currentProductionId);
315
+ if (query.environment !== 'all' && deployment.environment !== query.environment) continue;
316
+ if (seen.has(deployment.id)) continue;
317
+ if (items.length >= limit) break;
318
+ seen.add(deployment.id);
319
+ items.push(deployment);
320
+ }
321
+
322
+ const next = response.data?.pagination?.next ?? null;
323
+ if (next === null) {
324
+ hasMore = false;
325
+ cursor = undefined;
326
+ break;
327
+ }
328
+ cursor = next;
329
+ hasMore = true;
330
+ }
331
+
332
+ return {
333
+ items,
334
+ hasMore,
335
+ // The cursor is where the FILL stopped, not `page + 1`. Resuming from
336
+ // anywhere else re-reads rows this page already discarded.
337
+ nextCursor: hasMore && cursor !== undefined ? String(cursor) : null,
338
+ rateLimit
339
+ };
340
+ },
341
+
342
+ async get(context: DeployContext, id: string): Promise<DeploymentDetail> {
343
+ const credentials = credentialsOf(context);
344
+ const { locator, teamId } = context.binding;
345
+
346
+ const [detail, project] = await Promise.all([
347
+ vercelRequest<VercelDeployment>(credentials, `/v13/deployments/${encodeURIComponent(id)}`, {
348
+ query: { withGitRepoInfo: 1, teamId: teamId ?? undefined }
349
+ }),
350
+ fetchProject(credentials, locator, teamId)
351
+ ]);
352
+
353
+ const raw = detail.data;
354
+ const base = toDeployment(raw, currentProductionIdOf(project));
355
+
356
+ return {
357
+ ...base,
358
+ // Ordered here, not in the panel. The first alias is the one a reader
359
+ // should be shown, and deciding which that is takes Vercel knowledge:
360
+ // the custom domain is short (`acme.com`) while the generated ones
361
+ // carry the branch and a build hash (`acme-git-fix-x-team.vercel.app`).
362
+ // Shortest-first encodes that without the panel having to know it, and
363
+ // a provider whose aliases do not work that way sorts its own.
364
+ aliases: [...(raw.alias ?? [])].sort((a, b) => a.length - b.length),
365
+ framework: raw.projectSettings?.framework ?? project.framework ?? null,
366
+ durationMs: durationOf(raw)
367
+ };
368
+ },
369
+
370
+ fetchLogs(context: DeployContext, id: string): Promise<BuildLogBundle> {
371
+ return fetchBuildLogs(credentialsOf(context), id, context.binding.teamId);
372
+ },
373
+
374
+ streamLogs(context: DeployContext, id: string, callbacks: LogStreamCallbacks): Promise<LogStreamHandle> {
375
+ return streamBuildLogs(credentialsOf(context), id, context.binding.teamId, callbacks);
376
+ },
377
+
378
+ /**
379
+ * Rebuild an existing deployment.
380
+ *
381
+ * `forceNew=1` because without it Vercel deduplicates against an identical
382
+ * recent deployment and hands back the one that already exists — which for a
383
+ * user who pressed "Redeploy" to retry a flaky build looks exactly like the
384
+ * button doing nothing. The environment is carried over explicitly so
385
+ * redeploying a production build does not quietly produce a preview.
386
+ */
387
+ async redeploy(context: DeployContext, id: string) {
388
+ const credentials = credentialsOf(context);
389
+ const { teamId } = context.binding;
390
+
391
+ const existing = await vercelRequest<VercelDeployment>(
392
+ credentials,
393
+ `/v13/deployments/${encodeURIComponent(id)}`,
394
+ { query: { teamId: teamId ?? undefined } }
395
+ );
396
+ const source = existing.data;
397
+
398
+ const created = await vercelRequest<VercelDeployment>(credentials, '/v13/deployments', {
399
+ method: 'POST',
400
+ query: { forceNew: 1, teamId: teamId ?? undefined },
401
+ body: {
402
+ name: source.name,
403
+ deploymentId: id,
404
+ target: toEnvironment(source) === 'production' ? 'production' : undefined
405
+ }
406
+ });
407
+
408
+ const newId = created.data?.uid ?? created.data?.id ?? null;
409
+ return { deploymentId: newId, message: 'A new build has been queued.' };
410
+ },
411
+
412
+ async cancel(context: DeployContext, id: string) {
413
+ await vercelRequest(credentialsOf(context), `/v12/deployments/${encodeURIComponent(id)}/cancel`, {
414
+ method: 'PATCH',
415
+ query: { teamId: context.binding.teamId ?? undefined }
416
+ });
417
+ return { message: 'The build has been cancelled.' };
418
+ },
419
+
420
+ /**
421
+ * Point production traffic back at an earlier build.
422
+ *
423
+ * Reported as PENDING, not done. Vercel accepts the request and moves the
424
+ * aliases afterwards; the outcome is read from the project's
425
+ * `lastAliasRequest.jobStatus`. Saying "done" here would tell someone their
426
+ * production incident was over while the old build was still serving.
427
+ */
428
+ async rollback(context: DeployContext, id: string) {
429
+ const { locator, teamId } = context.binding;
430
+ await vercelRequest(
431
+ credentialsOf(context),
432
+ `/v1/projects/${encodeURIComponent(locator)}/rollback/${encodeURIComponent(id)}`,
433
+ { method: 'POST', query: { teamId: teamId ?? undefined } }
434
+ );
435
+ return {
436
+ status: 'pending' as const,
437
+ message: 'Rollback requested. Production traffic moves once Vercel reassigns the domains.'
438
+ };
439
+ },
440
+
441
+ async promote(context: DeployContext, id: string) {
442
+ const { locator, teamId } = context.binding;
443
+ await vercelRequest(
444
+ credentialsOf(context),
445
+ `/v10/projects/${encodeURIComponent(locator)}/promote/${encodeURIComponent(id)}`,
446
+ { method: 'POST', query: { teamId: teamId ?? undefined } }
447
+ );
448
+ return {
449
+ status: 'pending' as const,
450
+ message: 'Promotion requested. Production traffic moves once Vercel reassigns the domains.'
451
+ };
452
+ },
453
+
454
+ /**
455
+ * Can a build be started here, and from which branch by default.
456
+ *
457
+ * A Vercel project with no git connection can only be deployed by uploading
458
+ * a file tree, which is what the CLI does and is not something this surface
459
+ * should grow. Saying so plainly beats a Deploy button that fails.
460
+ */
461
+ async deployInfo(context: DeployContext): Promise<AdapterDeployInfo> {
462
+ const { locator, teamId } = context.binding;
463
+ const project = await fetchProject(credentialsOf(context), locator, teamId);
464
+ const repo = repoOf(project);
465
+
466
+ if (!repo || !project.link?.repoId) {
467
+ return {
468
+ gitRepo: repo,
469
+ productionBranch: project.link?.productionBranch ?? null,
470
+ canDeploy: false,
471
+ reason:
472
+ 'This Vercel project is not connected to a git repository, so a build can only be started by uploading files with the Vercel CLI.'
473
+ };
474
+ }
475
+
476
+ return {
477
+ gitRepo: repo,
478
+ // Vercel leaves this null when the repository's default branch is
479
+ // being used, which is `main` far more often than anything else.
480
+ productionBranch: project.link.productionBranch ?? 'main',
481
+ canDeploy: true,
482
+ reason: null
483
+ };
484
+ },
485
+
486
+ /**
487
+ * Start a build from a branch.
488
+ *
489
+ * `project` rather than `name` identifies the target: the docs note that
490
+ * `project` overrides `name`, and a name alone would CREATE a project when
491
+ * it does not match an existing one — silently making a second project
492
+ * beside the one the user is bound to.
493
+ *
494
+ * Omitting `target` yields a preview build, which is what "not production"
495
+ * means here. There is no `target: 'preview'` to send.
496
+ */
497
+ async createDeployment(context: DeployContext, draft: DeploymentDraft) {
498
+ const credentials = credentialsOf(context);
499
+ const { locator, teamId } = context.binding;
500
+
501
+ const project = await fetchProject(credentials, locator, teamId);
502
+ const repoId = project.link?.repoId;
503
+ if (!repoId) {
504
+ throw new VercelError(
505
+ 'This Vercel project is not connected to a git repository, so there is nothing to build from.',
506
+ 400,
507
+ 'config'
508
+ );
509
+ }
510
+
511
+ const created = await vercelRequest<VercelDeployment>(credentials, '/v13/deployments', {
512
+ method: 'POST',
513
+ query: { forceNew: 1, teamId: teamId ?? undefined },
514
+ body: {
515
+ name: project.name,
516
+ project: locator,
517
+ ...(draft.production && { target: 'production' }),
518
+ gitSource: {
519
+ // The git provider is the project's, not a guess: a GitLab-linked
520
+ // project rejects `type: 'github'` outright.
521
+ type: project.link?.type ?? 'github',
522
+ ref: draft.ref,
523
+ repoId
524
+ }
525
+ }
526
+ });
527
+
528
+ const id = created.data?.uid ?? created.data?.id ?? null;
529
+ return {
530
+ deploymentId: id,
531
+ message: draft.production
532
+ ? `Production build queued from ${draft.ref}.`
533
+ : `Preview build queued from ${draft.ref}.`
534
+ };
535
+ },
536
+
537
+ /**
538
+ * Create a Vercel project, connected to a repository when one is given.
539
+ *
540
+ * Connecting the repository at creation is what makes the project useful
541
+ * immediately — an unconnected project cannot be deployed from here at all,
542
+ * per `deployInfo` above. It requires the Vercel account to have access to
543
+ * that repository already, and the error when it does not is Vercel's own,
544
+ * which names the missing installation better than we could.
545
+ */
546
+ async createProject(context: UnboundDeployContext, draft: NewProjectDraft): Promise<DeployTarget> {
547
+ const credentials = credentialsOf(context);
548
+ // Teams are not offered here. A new project lands in the token's default
549
+ // scope, which is the one place we know the credential can write.
550
+ const created = await vercelRequest<VercelProject>(credentials, '/v11/projects', {
551
+ method: 'POST',
552
+ body: {
553
+ name: draft.name,
554
+ ...(draft.framework && { framework: draft.framework }),
555
+ ...(draft.gitRepo && {
556
+ gitRepository: { type: draft.gitProvider || 'github', repo: draft.gitRepo }
557
+ })
558
+ }
559
+ });
560
+
561
+ return toTarget(created.data, null);
562
+ },
563
+
564
+ /**
565
+ * Can this repository be attached, and if not, what would fix it.
566
+ *
567
+ * Vercel needs the ACCOUNT to hold a git login connection before any project
568
+ * can be linked, and it reports the absence as "You need to add a Login
569
+ * Connection to your GitHub account first" — at the moment the user presses
570
+ * Connect, having already been promised it would work. Asking the namespaces
571
+ * endpoint first turns that into a sentence with a link in it.
572
+ *
573
+ * The check also covers the narrower case: a Vercel account CAN have GitHub
574
+ * connected and still not reach one particular owner, because the GitHub App
575
+ * is installed per account or organisation.
576
+ */
577
+ async repositoryAccess(context: UnboundDeployContext, gitRepo: string): Promise<RepositoryAccess> {
578
+ // Two DIFFERENT things, and conflating them is what made the first version
579
+ // wrong. A "Login Connection" is how you sign in to Vercel; the GitHub App
580
+ // installation is what lets Vercel read your repositories. An account can
581
+ // have the first without the second, and this endpoint reports the second.
582
+ const installUrl = 'https://github.com/apps/vercel/installations/new';
583
+ let namespaces: VercelGitNamespace[] = [];
584
+
585
+ try {
586
+ // NO `teamId` HERE. Nearly every other Vercel endpoint requires it, and
587
+ // this one rejects it outright with a 400 — git namespaces belong to the
588
+ // signed-in USER, not to a team.
589
+ const response = await vercelRequest<VercelGitNamespace[] | { gitNamespaces?: VercelGitNamespace[] }>(
590
+ credentialsOf(context),
591
+ '/v1/integrations/git-namespaces',
592
+ { query: { provider: 'github' } }
593
+ );
594
+ const data = response.data;
595
+ // Documented as a bare array, but tolerate a wrapper rather than read a
596
+ // wrapped response as "no namespaces".
597
+ namespaces = Array.isArray(data) ? data : (data?.gitNamespaces ?? []);
598
+ } catch (error) {
599
+ debug.log('deployments', 'Could not list Vercel git namespaces:', error);
600
+ return {
601
+ state: 'unknown',
602
+ reason:
603
+ 'Could not check which repositories this Vercel account can reach. Connecting may still work — if it does not, the reason will be shown here.',
604
+ actionUrl: installUrl
605
+ };
606
+ }
607
+
608
+ const owner = gitRepo.split('/')[0]?.toLowerCase() ?? '';
609
+ const match = namespaces.find((entry) => entry.slug?.toLowerCase() === owner);
610
+
611
+ if (match && !match.isAccessRestricted) {
612
+ return { state: 'ready', reason: null, actionUrl: null };
613
+ }
614
+
615
+ if (match?.isAccessRestricted) {
616
+ return {
617
+ state: 'blocked',
618
+ reason: `Vercel can see "${owner}" but its access there is restricted — an owner has to approve Vercel's GitHub app before its repositories can be linked.`,
619
+ actionUrl: installUrl
620
+ };
621
+ }
622
+
623
+ // AN EMPTY LIST IS NOT PROOF OF ANYTHING. The first version treated it as
624
+ // "this account has no GitHub connection" and DISABLED the button on that
625
+ // inference — which was wrong for an account that had GitHub connected and
626
+ // working. This endpoint's silence can also mean a token that cannot read
627
+ // integrations, so an empty answer is reported as unknown and the real
628
+ // attempt is left to give the authoritative answer.
629
+ if (namespaces.length === 0) {
630
+ return {
631
+ state: 'unknown',
632
+ reason:
633
+ "Vercel reports no repositories it can reach with this token. That usually means Vercel's GitHub app is not installed yet — but the token may simply not be allowed to read that, so connecting is still worth trying.",
634
+ actionUrl: installUrl
635
+ };
636
+ }
637
+
638
+ // A non-empty list that omits the owner IS informative: the app is
639
+ // installed somewhere, just not where this repository lives.
640
+ const reachable = namespaces.map((entry) => entry.slug).filter(Boolean).join(', ');
641
+ return {
642
+ state: 'blocked',
643
+ reason: `Vercel can reach ${reachable}, but not "${owner}". Install Vercel's GitHub app on that account or organisation and it will appear here.`,
644
+ actionUrl: installUrl
645
+ };
646
+ },
647
+
648
+ /**
649
+ * Attach a repository to an existing project.
650
+ *
651
+ * THIS ENDPOINT IS NOT IN VERCEL'S PUBLISHED OPENAPI DOCUMENT. It is what
652
+ * `vercel git connect` calls, so it is exercised by the official CLI on every
653
+ * install rather than being a browser-internal route — but it carries no
654
+ * compatibility promise, and it is the one call in this adapter that could
655
+ * change without notice.
656
+ *
657
+ * It is here because the alternative is worse: `PATCH /v9/projects/{id}`
658
+ * accepts no `gitRepository`, and the only documented way to get a connected
659
+ * project is to create a NEW one — which means telling someone their existing
660
+ * project is unusable from Clopen and they should make a second one. The
661
+ * failure path says exactly that, so a break here degrades to the documented
662
+ * route rather than to a dead end.
663
+ */
664
+ async connectRepository(context: DeployContext, repo: { gitRepo: string; gitProvider: string }) {
665
+ const { locator, teamId } = context.binding;
666
+ try {
667
+ await vercelRequest(
668
+ credentialsOf(context),
669
+ `/v9/projects/${encodeURIComponent(locator)}/link`,
670
+ {
671
+ method: 'POST',
672
+ query: { teamId: teamId ?? undefined },
673
+ body: { type: repo.gitProvider || 'github', repo: repo.gitRepo }
674
+ }
675
+ );
676
+ } catch (error) {
677
+ // Vercel's own wording names the prerequisite but not where to fix it,
678
+ // and it arrives at the moment the user has already committed to the
679
+ // action. The pre-check normally prevents this; when it does not, the
680
+ // message at least has to carry the address.
681
+ const message = error instanceof Error ? error.message : String(error);
682
+ if (/login connection/i.test(message)) {
683
+ throw new VercelError(
684
+ `${message} Add it at https://vercel.com/account/login-connections, then try again.`,
685
+ error instanceof VercelError ? error.status : 400,
686
+ 'config'
687
+ );
688
+ }
689
+ throw error;
690
+ }
691
+ },
692
+
693
+ /**
694
+ * Delete a deployment.
695
+ *
696
+ * Vercel refuses for whatever is currently serving production, which is the
697
+ * right refusal — the caller does not offer it there either, so reaching
698
+ * that error means something raced.
699
+ */
700
+ async deleteDeployment(context: DeployContext, id: string) {
701
+ await vercelRequest(credentialsOf(context), `/v13/deployments/${encodeURIComponent(id)}`, {
702
+ method: 'DELETE',
703
+ query: { teamId: context.binding.teamId ?? undefined }
704
+ });
705
+ return { message: 'The deployment has been deleted.' };
706
+ },
707
+
708
+ /**
709
+ * Whether the project is paused, and whether a traffic move is still running.
710
+ *
711
+ * Both are read-only. `lastAliasRequest` is what makes `pending` finishable:
712
+ * rollback and promote both return as soon as Vercel accepts them, and this
713
+ * is the only place the outcome shows up.
714
+ */
715
+ async projectStatus(context: DeployContext): Promise<DeployProjectStatus> {
716
+ const { locator, teamId } = context.binding;
717
+ const project = await fetchProject(credentialsOf(context), locator, teamId);
718
+ const request = project.lastAliasRequest;
719
+
720
+ return {
721
+ paused: project.paused === true,
722
+ aliasRequest:
723
+ request?.type && request.jobStatus
724
+ ? {
725
+ type: request.type,
726
+ status: request.jobStatus,
727
+ toDeploymentId: request.toDeploymentId ?? null
728
+ }
729
+ : null
730
+ };
731
+ },
732
+
733
+ async viewer(context) {
734
+ try {
735
+ const response = await vercelRequest<VercelUser>(credentialsOf(context), '/v2/user');
736
+ return response.data?.user?.username ?? response.data?.user?.email ?? null;
737
+ } catch {
738
+ return null;
739
+ }
740
+ },
741
+
742
+ async currentProduction(context: DeployContext): Promise<Deployment | null> {
743
+ const credentials = credentialsOf(context);
744
+ const { locator, teamId } = context.binding;
745
+
746
+ const project = await fetchProject(credentials, locator, teamId);
747
+ const currentId = currentProductionIdOf(project);
748
+ if (!currentId) return null;
749
+
750
+ const detail = await vercelRequest<VercelDeployment>(
751
+ credentials,
752
+ `/v13/deployments/${encodeURIComponent(currentId)}`,
753
+ { query: { teamId: teamId ?? undefined } }
754
+ );
755
+ return toDeployment(detail.data, currentId);
756
+ }
757
+ };