@catamorphic/fastify-plugin 0.0.0-stage → 0.1.0-alpha.31

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 (160) hide show
  1. package/LICENSE.txt +202 -0
  2. package/NOTICE.txt +32 -0
  3. package/README.md +143 -2
  4. package/dist/app-presentation-tools.d.ts +4 -0
  5. package/dist/app-presentation-tools.d.ts.map +1 -0
  6. package/dist/app.d.ts +27 -0
  7. package/dist/app.d.ts.map +1 -0
  8. package/dist/chunk-baagvvm3.js +164 -0
  9. package/dist/chunk-baagvvm3.js.map +10 -0
  10. package/dist/http-identity.d.ts +52 -0
  11. package/dist/http-identity.d.ts.map +1 -0
  12. package/dist/hung-up.d.ts +7 -0
  13. package/dist/hung-up.d.ts.map +1 -0
  14. package/dist/index.d.ts +11 -0
  15. package/dist/index.d.ts.map +1 -0
  16. package/dist/index.js +10884 -0
  17. package/dist/index.js.map +56 -0
  18. package/dist/mcp-shared.d.ts +117 -0
  19. package/dist/mcp-shared.d.ts.map +1 -0
  20. package/dist/mcp.d.ts +6 -0
  21. package/dist/mcp.d.ts.map +1 -0
  22. package/dist/mcp.js +13 -0
  23. package/dist/mcp.js.map +9 -0
  24. package/dist/plugin.d.ts +113 -0
  25. package/dist/plugin.d.ts.map +1 -0
  26. package/dist/project-capabilities.d.ts +25 -0
  27. package/dist/project-capabilities.d.ts.map +1 -0
  28. package/dist/project-mcp-program.d.ts +15 -0
  29. package/dist/project-mcp-program.d.ts.map +1 -0
  30. package/dist/project-mcp-surface.d.ts +16 -0
  31. package/dist/project-mcp-surface.d.ts.map +1 -0
  32. package/dist/request-logging.d.ts +18 -0
  33. package/dist/request-logging.d.ts.map +1 -0
  34. package/dist/routes/agent-capabilities.d.ts +4 -0
  35. package/dist/routes/agent-capabilities.d.ts.map +1 -0
  36. package/dist/routes/agent.d.ts +4 -0
  37. package/dist/routes/agent.d.ts.map +1 -0
  38. package/dist/routes/apps-mcp.d.ts +4 -0
  39. package/dist/routes/apps-mcp.d.ts.map +1 -0
  40. package/dist/routes/apps.d.ts +12 -0
  41. package/dist/routes/apps.d.ts.map +1 -0
  42. package/dist/routes/client-runners.d.ts +11 -0
  43. package/dist/routes/client-runners.d.ts.map +1 -0
  44. package/dist/routes/code-hosts.d.ts +11 -0
  45. package/dist/routes/code-hosts.d.ts.map +1 -0
  46. package/dist/routes/connection-mcp.d.ts +10 -0
  47. package/dist/routes/connection-mcp.d.ts.map +1 -0
  48. package/dist/routes/connections.d.ts +4 -0
  49. package/dist/routes/connections.d.ts.map +1 -0
  50. package/dist/routes/documents.d.ts +11 -0
  51. package/dist/routes/documents.d.ts.map +1 -0
  52. package/dist/routes/environments.d.ts +4 -0
  53. package/dist/routes/environments.d.ts.map +1 -0
  54. package/dist/routes/git-gateway.d.ts +21 -0
  55. package/dist/routes/git-gateway.d.ts.map +1 -0
  56. package/dist/routes/http-gateway.d.ts +13 -0
  57. package/dist/routes/http-gateway.d.ts.map +1 -0
  58. package/dist/routes/me.d.ts +12 -0
  59. package/dist/routes/me.d.ts.map +1 -0
  60. package/dist/routes/memberships.d.ts +12 -0
  61. package/dist/routes/memberships.d.ts.map +1 -0
  62. package/dist/routes/model-gateway.d.ts +12 -0
  63. package/dist/routes/model-gateway.d.ts.map +1 -0
  64. package/dist/routes/notifications.d.ts +4 -0
  65. package/dist/routes/notifications.d.ts.map +1 -0
  66. package/dist/routes/parse.d.ts +5 -0
  67. package/dist/routes/parse.d.ts.map +1 -0
  68. package/dist/routes/personal-environment.d.ts +13 -0
  69. package/dist/routes/personal-environment.d.ts.map +1 -0
  70. package/dist/routes/plugins.d.ts +4 -0
  71. package/dist/routes/plugins.d.ts.map +1 -0
  72. package/dist/routes/project-mcp.d.ts +25 -0
  73. package/dist/routes/project-mcp.d.ts.map +1 -0
  74. package/dist/routes/projects.d.ts +4 -0
  75. package/dist/routes/projects.d.ts.map +1 -0
  76. package/dist/routes/publications.d.ts +15 -0
  77. package/dist/routes/publications.d.ts.map +1 -0
  78. package/dist/routes/run-errors.d.ts +8 -0
  79. package/dist/routes/run-errors.d.ts.map +1 -0
  80. package/dist/routes/runs.d.ts +4 -0
  81. package/dist/routes/runs.d.ts.map +1 -0
  82. package/dist/routes/session-artifacts.d.ts +27 -0
  83. package/dist/routes/session-artifacts.d.ts.map +1 -0
  84. package/dist/routes/session-mailboxes.d.ts +4 -0
  85. package/dist/routes/session-mailboxes.d.ts.map +1 -0
  86. package/dist/routes/session-previews.d.ts +40 -0
  87. package/dist/routes/session-previews.d.ts.map +1 -0
  88. package/dist/routes/session-terminals.d.ts +15 -0
  89. package/dist/routes/session-terminals.d.ts.map +1 -0
  90. package/dist/routes/triggers.d.ts +20 -0
  91. package/dist/routes/triggers.d.ts.map +1 -0
  92. package/dist/routes/watchers.d.ts +4 -0
  93. package/dist/routes/watchers.d.ts.map +1 -0
  94. package/dist/routes/webhooks.d.ts +11 -0
  95. package/dist/routes/webhooks.d.ts.map +1 -0
  96. package/dist/routes/workflow-enablements.d.ts +4 -0
  97. package/dist/routes/workflow-enablements.d.ts.map +1 -0
  98. package/dist/routes/workflows.d.ts +4 -0
  99. package/dist/routes/workflows.d.ts.map +1 -0
  100. package/dist/schemas.d.ts +17776 -0
  101. package/dist/schemas.d.ts.map +1 -0
  102. package/dist/session-artifact-tools.d.ts +5 -0
  103. package/dist/session-artifact-tools.d.ts.map +1 -0
  104. package/dist/session-event-stream.d.ts +45 -0
  105. package/dist/session-event-stream.d.ts.map +1 -0
  106. package/dist/spa.d.ts +24 -0
  107. package/dist/spa.d.ts.map +1 -0
  108. package/dist/telemetry.d.ts +4 -0
  109. package/dist/telemetry.d.ts.map +1 -0
  110. package/package.json +73 -4
  111. package/src/app-presentation-tools.ts +46 -0
  112. package/src/app.ts +115 -0
  113. package/src/http-identity.ts +145 -0
  114. package/src/hung-up.ts +13 -0
  115. package/src/index.ts +25 -0
  116. package/src/mcp-shared.ts +331 -0
  117. package/src/mcp.ts +10 -0
  118. package/src/plugin.ts +332 -0
  119. package/src/project-capabilities.ts +153 -0
  120. package/src/project-mcp-program.ts +607 -0
  121. package/src/project-mcp-surface.ts +881 -0
  122. package/src/request-logging.ts +47 -0
  123. package/src/routes/agent-capabilities.ts +109 -0
  124. package/src/routes/agent.ts +1566 -0
  125. package/src/routes/apps-mcp.ts +303 -0
  126. package/src/routes/apps.ts +692 -0
  127. package/src/routes/client-runners.ts +251 -0
  128. package/src/routes/code-hosts.ts +247 -0
  129. package/src/routes/connection-mcp.ts +135 -0
  130. package/src/routes/connections.ts +494 -0
  131. package/src/routes/documents.ts +538 -0
  132. package/src/routes/environments.ts +72 -0
  133. package/src/routes/git-gateway.ts +106 -0
  134. package/src/routes/http-gateway.ts +141 -0
  135. package/src/routes/me.ts +122 -0
  136. package/src/routes/memberships.ts +173 -0
  137. package/src/routes/model-gateway.ts +134 -0
  138. package/src/routes/notifications.ts +101 -0
  139. package/src/routes/parse.ts +32 -0
  140. package/src/routes/personal-environment.ts +146 -0
  141. package/src/routes/plugins.ts +341 -0
  142. package/src/routes/project-mcp.ts +394 -0
  143. package/src/routes/projects.ts +708 -0
  144. package/src/routes/publications.ts +222 -0
  145. package/src/routes/run-errors.ts +86 -0
  146. package/src/routes/runs.ts +253 -0
  147. package/src/routes/session-artifacts.ts +293 -0
  148. package/src/routes/session-mailboxes.ts +80 -0
  149. package/src/routes/session-previews.ts +224 -0
  150. package/src/routes/session-terminals.ts +209 -0
  151. package/src/routes/triggers.ts +241 -0
  152. package/src/routes/watchers.ts +94 -0
  153. package/src/routes/webhooks.ts +171 -0
  154. package/src/routes/workflow-enablements.ts +331 -0
  155. package/src/routes/workflows.ts +323 -0
  156. package/src/schemas.ts +2735 -0
  157. package/src/session-artifact-tools.ts +170 -0
  158. package/src/session-event-stream.ts +122 -0
  159. package/src/spa.ts +135 -0
  160. package/src/telemetry.ts +93 -0
@@ -0,0 +1,538 @@
1
+ import {
2
+ DocumentBlobUnavailableError,
3
+ DocumentConflictError,
4
+ DocumentNotFoundError,
5
+ DocumentPathError,
6
+ DocumentTooLargeError,
7
+ ProjectNotFoundError,
8
+ } from "@catamorphic/core";
9
+ import type { FastifyInstance, FastifyReply } from "fastify";
10
+ import type { ZodTypeProvider } from "fastify-type-provider-zod";
11
+ import { z } from "zod";
12
+ import type { RouteContext } from "../app.js";
13
+ import { resolveIdentity } from "../http-identity.js";
14
+ import {
15
+ DocumentContentSchema,
16
+ DocumentEntrySchema,
17
+ DocumentMatchSchema,
18
+ DocumentVersionSchema,
19
+ ErrorSchema,
20
+ ProjectIdParamsSchema,
21
+ ProposalCommentInputSchema,
22
+ ProposalCommentSchema,
23
+ ProposalDiscussionSchema,
24
+ ProposalFileSchema,
25
+ ProposalResultSchema,
26
+ ProposalReviewSchema,
27
+ ProposalSummarySchema,
28
+ ProposeChangeSchema,
29
+ WriteDocumentSchema,
30
+ } from "../schemas.js";
31
+
32
+ /**
33
+ * The documents surface (ADR 0055): one path namespace — the program (git,
34
+ * read-only here) and the project store (`store/…`, versioned, caller-
35
+ * stamped) — filtered by the caller's document refs. JSON for metadata,
36
+ * text and writes (text or base64); `/documents/raw` streams bytes for
37
+ * downloads and binaries.
38
+ */
39
+ export function registerDocumentRoutes(
40
+ app: FastifyInstance,
41
+ ctx: RouteContext,
42
+ ) {
43
+ const typed = app.withTypeProvider<ZodTypeProvider>();
44
+ const core = () => {
45
+ if (!ctx.core)
46
+ throw Object.assign(new Error("Service not configured"), {
47
+ statusCode: 503,
48
+ });
49
+ return ctx.core;
50
+ };
51
+
52
+ const handleErrors = (err: unknown, reply: FastifyReply) => {
53
+ if (err instanceof ProjectNotFoundError) {
54
+ return reply.status(404).send({ error: "Project not found" });
55
+ }
56
+ if (err instanceof DocumentBlobUnavailableError)
57
+ return reply.status(503).send({ error: err.message });
58
+ if (err instanceof DocumentNotFoundError) {
59
+ return reply.status(404).send({ error: err.message });
60
+ }
61
+ if (err instanceof DocumentPathError) {
62
+ return reply.status(400).send({ error: err.message });
63
+ }
64
+ if (err instanceof DocumentTooLargeError) {
65
+ return reply.status(413).send({ error: err.message });
66
+ }
67
+ if (err instanceof DocumentConflictError) {
68
+ return reply
69
+ .status(409)
70
+ .send({ error: err.message, currentVersion: err.currentVersion });
71
+ }
72
+ throw err;
73
+ };
74
+
75
+ typed.route({
76
+ method: "GET",
77
+ url: "/projects/:projectId/documents/storage",
78
+ schema: {
79
+ params: ProjectIdParamsSchema,
80
+ response: {
81
+ 200: z.object({
82
+ location: z.enum(["device", "server"]),
83
+ blobs: z.enum(["connected", "database"]),
84
+ maxDocumentBytes: z.number(),
85
+ uploadIsExplicit: z.boolean(),
86
+ }),
87
+ 404: ErrorSchema,
88
+ },
89
+ },
90
+ handler: async (request, reply) => {
91
+ try {
92
+ const storage = await core().documents.storage({
93
+ identity: resolveIdentity(request),
94
+ projectId: request.params.projectId,
95
+ });
96
+ return reply.send({
97
+ ...storage,
98
+ maxDocumentBytes: Math.min(
99
+ storage.maxDocumentBytes,
100
+ ctx.features.storeUploadMaxBytes,
101
+ ),
102
+ });
103
+ } catch (error) {
104
+ return handleErrors(error, reply);
105
+ }
106
+ },
107
+ });
108
+
109
+ typed.route({
110
+ method: "GET",
111
+ url: "/projects/:projectId/documents",
112
+ schema: {
113
+ params: ProjectIdParamsSchema,
114
+ querystring: z.object({
115
+ prefix: z.string().optional(),
116
+ source: z.enum(["program", "store"]).optional(),
117
+ }),
118
+ response: { 200: DocumentEntrySchema.array(), 404: ErrorSchema },
119
+ },
120
+ handler: async (request, reply) => {
121
+ try {
122
+ return reply.send(
123
+ await core().documents.list({
124
+ identity: resolveIdentity(request),
125
+ projectId: request.params.projectId,
126
+ ...request.query,
127
+ }),
128
+ );
129
+ } catch (err) {
130
+ return handleErrors(err, reply);
131
+ }
132
+ },
133
+ });
134
+
135
+ typed.route({
136
+ method: "GET",
137
+ url: "/projects/:projectId/documents/content",
138
+ schema: {
139
+ params: ProjectIdParamsSchema,
140
+ querystring: z.object({
141
+ path: z.string().min(1),
142
+ version: z.coerce.number().int().positive().optional(),
143
+ }),
144
+ response: {
145
+ 200: DocumentContentSchema,
146
+ 503: ErrorSchema,
147
+ 400: ErrorSchema,
148
+ 404: ErrorSchema,
149
+ },
150
+ },
151
+ handler: async (request, reply) => {
152
+ try {
153
+ const doc = await core().documents.read({
154
+ identity: resolveIdentity(request),
155
+ projectId: request.params.projectId,
156
+ path: request.query.path,
157
+ ...(request.query.version !== undefined
158
+ ? { version: request.query.version }
159
+ : {}),
160
+ });
161
+ return reply.send(doc);
162
+ } catch (err) {
163
+ return handleErrors(err, reply);
164
+ }
165
+ },
166
+ });
167
+
168
+ // Raw bytes: downloads, binaries, editors that want the file as-is.
169
+ typed.route({
170
+ method: "GET",
171
+ url: "/projects/:projectId/documents/raw",
172
+ schema: {
173
+ params: ProjectIdParamsSchema,
174
+ querystring: z.object({
175
+ path: z.string().min(1),
176
+ version: z.coerce.number().int().positive().optional(),
177
+ }),
178
+ },
179
+ handler: async (request, reply) => {
180
+ try {
181
+ const doc = await core().documents.readBytes({
182
+ identity: resolveIdentity(request),
183
+ projectId: request.params.projectId,
184
+ path: request.query.path,
185
+ ...(request.query.version !== undefined
186
+ ? { version: request.query.version }
187
+ : {}),
188
+ });
189
+ reply.header("content-type", doc.contentType);
190
+ reply.header("x-catamorphic-document-source", doc.source);
191
+ if (doc.version !== undefined) {
192
+ reply.header("x-catamorphic-document-version", String(doc.version));
193
+ }
194
+ if (doc.writtenBy) {
195
+ // Header values must be Latin-1 and single-line; ids are host text.
196
+ reply.header(
197
+ "x-catamorphic-written-by",
198
+ encodeURIComponent(doc.writtenBy),
199
+ );
200
+ }
201
+ if (doc.writtenAt)
202
+ reply.header("x-catamorphic-written-at", doc.writtenAt);
203
+ return reply.send(Buffer.from(doc.bytes));
204
+ } catch (err) {
205
+ return handleErrors(err, reply);
206
+ }
207
+ },
208
+ });
209
+
210
+ typed.route({
211
+ method: "PUT",
212
+ url: "/projects/:projectId/documents/content",
213
+ // The body must fit the largest allowed document base64-inflated (4/3)
214
+ // plus the JSON envelope; the handler's storeUploadMaxBytes check owns
215
+ // the accurate 413 for decoded content.
216
+ bodyLimit: Math.ceil((ctx.features.storeUploadMaxBytes * 4) / 3) + 65_536,
217
+ schema: {
218
+ params: ProjectIdParamsSchema,
219
+ body: WriteDocumentSchema,
220
+ response: {
221
+ 200: DocumentEntrySchema,
222
+ 400: ErrorSchema,
223
+ 404: ErrorSchema,
224
+ 409: ErrorSchema.extend({ currentVersion: z.number() }),
225
+ 413: ErrorSchema,
226
+ },
227
+ },
228
+ handler: async (request, reply) => {
229
+ const body = request.body;
230
+ const content =
231
+ body.text !== undefined
232
+ ? body.text
233
+ : new Uint8Array(Buffer.from(body.base64 ?? "", "base64"));
234
+ const size =
235
+ typeof content === "string"
236
+ ? Buffer.byteLength(content)
237
+ : content.byteLength;
238
+ if (size > ctx.features.storeUploadMaxBytes) {
239
+ return reply.status(413).send({
240
+ error: `Document exceeds this server's limit of ${Math.floor(ctx.features.storeUploadMaxBytes / 1024 / 1024)}MB`,
241
+ });
242
+ }
243
+ try {
244
+ return reply.send(
245
+ await core().documents.write({
246
+ identity: resolveIdentity(request),
247
+ projectId: request.params.projectId,
248
+ path: body.path,
249
+ content,
250
+ ...(body.contentType ? { contentType: body.contentType } : {}),
251
+ ...(body.ifVersion !== undefined
252
+ ? { ifVersion: body.ifVersion }
253
+ : {}),
254
+ }),
255
+ );
256
+ } catch (err) {
257
+ return handleErrors(err, reply);
258
+ }
259
+ },
260
+ });
261
+
262
+ typed.route({
263
+ method: "DELETE",
264
+ url: "/projects/:projectId/documents/content",
265
+ schema: {
266
+ params: ProjectIdParamsSchema,
267
+ querystring: z.object({
268
+ path: z.string().min(1),
269
+ ifVersion: z.coerce.number().int().nonnegative().optional(),
270
+ }),
271
+ response: {
272
+ 200: z.object({ version: z.number() }),
273
+ 400: ErrorSchema,
274
+ 404: ErrorSchema,
275
+ 409: ErrorSchema.extend({ currentVersion: z.number() }),
276
+ },
277
+ },
278
+ handler: async (request, reply) => {
279
+ try {
280
+ return reply.send(
281
+ await core().documents.delete({
282
+ identity: resolveIdentity(request),
283
+ projectId: request.params.projectId,
284
+ path: request.query.path,
285
+ ...(request.query.ifVersion !== undefined
286
+ ? { ifVersion: request.query.ifVersion }
287
+ : {}),
288
+ }),
289
+ );
290
+ } catch (err) {
291
+ return handleErrors(err, reply);
292
+ }
293
+ },
294
+ });
295
+
296
+ typed.route({
297
+ method: "GET",
298
+ url: "/projects/:projectId/documents/history",
299
+ schema: {
300
+ params: ProjectIdParamsSchema,
301
+ querystring: z.object({ path: z.string().min(1) }),
302
+ response: {
303
+ 200: DocumentVersionSchema.array(),
304
+ 400: ErrorSchema,
305
+ 404: ErrorSchema,
306
+ },
307
+ },
308
+ handler: async (request, reply) => {
309
+ try {
310
+ return reply.send(
311
+ await core().documents.history({
312
+ identity: resolveIdentity(request),
313
+ projectId: request.params.projectId,
314
+ path: request.query.path,
315
+ }),
316
+ );
317
+ } catch (err) {
318
+ return handleErrors(err, reply);
319
+ }
320
+ },
321
+ });
322
+
323
+ typed.route({
324
+ method: "GET",
325
+ url: "/projects/:projectId/documents/search",
326
+ schema: {
327
+ params: ProjectIdParamsSchema,
328
+ querystring: z.object({
329
+ q: z.string().min(1),
330
+ mode: z.enum(["grep", "text"]).optional(),
331
+ prefix: z.string().optional(),
332
+ limit: z.coerce.number().int().positive().max(200).optional(),
333
+ }),
334
+ response: {
335
+ 200: DocumentMatchSchema.array(),
336
+ 400: ErrorSchema,
337
+ 404: ErrorSchema,
338
+ },
339
+ },
340
+ handler: async (request, reply) => {
341
+ try {
342
+ const { q, ...rest } = request.query;
343
+ return reply.send(
344
+ await core().documents.search({
345
+ identity: resolveIdentity(request),
346
+ projectId: request.params.projectId,
347
+ query: q,
348
+ ...rest,
349
+ }),
350
+ );
351
+ } catch (err) {
352
+ return handleErrors(err, reply);
353
+ }
354
+ },
355
+ });
356
+
357
+ // Propose a change to the program (ADR 0055): files land on a branch from
358
+ // the shared main, authored as the member; a PR opens through the host's
359
+ // bot when a code host is linked.
360
+ typed.route({
361
+ method: "POST",
362
+ url: "/projects/:projectId/proposals",
363
+ schema: {
364
+ params: ProjectIdParamsSchema,
365
+ body: ProposeChangeSchema,
366
+ response: {
367
+ 201: ProposalResultSchema,
368
+ 400: ErrorSchema,
369
+ 403: ErrorSchema,
370
+ 404: ErrorSchema,
371
+ },
372
+ },
373
+ handler: async (request, reply) => {
374
+ if (!ctx.features.proposals) {
375
+ return reply
376
+ .status(403)
377
+ .send({ error: "Proposals are turned off on this server" });
378
+ }
379
+ try {
380
+ const result = await core().proposals.propose({
381
+ identity: resolveIdentity(request),
382
+ projectId: request.params.projectId,
383
+ title: request.body.title,
384
+ ...(request.body.body ? { body: request.body.body } : {}),
385
+ changes: request.body.changes,
386
+ });
387
+ return reply.status(201).send(result);
388
+ } catch (err) {
389
+ return handleErrors(err, reply);
390
+ }
391
+ },
392
+ });
393
+ typed.route({
394
+ method: "GET",
395
+ url: "/projects/:projectId/proposals",
396
+ schema: {
397
+ params: ProjectIdParamsSchema,
398
+ response: {
399
+ 200: z.array(ProposalSummarySchema),
400
+ 403: ErrorSchema,
401
+ 404: ErrorSchema,
402
+ },
403
+ },
404
+ handler: async (request, reply) => {
405
+ if (!ctx.features.proposals)
406
+ return reply
407
+ .status(403)
408
+ .send({ error: "Proposals are turned off on this server" });
409
+ try {
410
+ return await core().proposals.list({
411
+ identity: resolveIdentity(request),
412
+ projectId: request.params.projectId,
413
+ });
414
+ } catch (error) {
415
+ return handleErrors(error, reply);
416
+ }
417
+ },
418
+ });
419
+ typed.route({
420
+ method: "GET",
421
+ url: "/projects/:projectId/proposals/:number",
422
+ schema: {
423
+ params: ProjectIdParamsSchema.extend({
424
+ number: z.coerce.number().int().positive(),
425
+ }),
426
+ response: {
427
+ 200: ProposalReviewSchema,
428
+ 400: ErrorSchema,
429
+ 403: ErrorSchema,
430
+ 404: ErrorSchema,
431
+ },
432
+ },
433
+ handler: async (request, reply) => {
434
+ if (!ctx.features.proposals)
435
+ return reply
436
+ .status(403)
437
+ .send({ error: "Proposals are turned off on this server" });
438
+ try {
439
+ return await core().proposals.read({
440
+ identity: resolveIdentity(request),
441
+ ...request.params,
442
+ });
443
+ } catch (error) {
444
+ return handleErrors(error, reply);
445
+ }
446
+ },
447
+ });
448
+ typed.route({
449
+ method: "GET",
450
+ url: "/projects/:projectId/proposals/:number/files",
451
+ schema: {
452
+ params: ProjectIdParamsSchema.extend({
453
+ number: z.coerce.number().int().positive(),
454
+ }),
455
+ response: {
456
+ 200: z.array(ProposalFileSchema),
457
+ 400: ErrorSchema,
458
+ 403: ErrorSchema,
459
+ 404: ErrorSchema,
460
+ },
461
+ },
462
+ handler: async (request, reply) => {
463
+ if (!ctx.features.proposals)
464
+ return reply
465
+ .status(403)
466
+ .send({ error: "Proposals are turned off on this server" });
467
+ try {
468
+ return await core().proposals.files({
469
+ identity: resolveIdentity(request),
470
+ projectId: request.params.projectId,
471
+ number: request.params.number,
472
+ });
473
+ } catch (error) {
474
+ return handleErrors(error, reply);
475
+ }
476
+ },
477
+ });
478
+ typed.route({
479
+ method: "GET",
480
+ url: "/projects/:projectId/proposals/:number/discussion",
481
+ schema: {
482
+ params: ProjectIdParamsSchema.extend({
483
+ number: z.coerce.number().int().positive(),
484
+ }),
485
+ response: {
486
+ 200: ProposalDiscussionSchema,
487
+ 400: ErrorSchema,
488
+ 403: ErrorSchema,
489
+ 404: ErrorSchema,
490
+ },
491
+ },
492
+ handler: async (request, reply) => {
493
+ if (!ctx.features.proposals)
494
+ return reply
495
+ .status(403)
496
+ .send({ error: "Proposals are turned off on this server" });
497
+ try {
498
+ return await core().proposals.discussion({
499
+ identity: resolveIdentity(request),
500
+ ...request.params,
501
+ });
502
+ } catch (error) {
503
+ return handleErrors(error, reply);
504
+ }
505
+ },
506
+ });
507
+ typed.route({
508
+ method: "POST",
509
+ url: "/projects/:projectId/proposals/:number/comments",
510
+ schema: {
511
+ params: ProjectIdParamsSchema.extend({
512
+ number: z.coerce.number().int().positive(),
513
+ }),
514
+ body: ProposalCommentInputSchema,
515
+ response: {
516
+ 200: ProposalCommentSchema,
517
+ 400: ErrorSchema,
518
+ 403: ErrorSchema,
519
+ 404: ErrorSchema,
520
+ },
521
+ },
522
+ handler: async (request, reply) => {
523
+ if (!ctx.features.proposals)
524
+ return reply
525
+ .status(403)
526
+ .send({ error: "Proposals are turned off on this server" });
527
+ try {
528
+ return await core().proposals.comment({
529
+ identity: resolveIdentity(request),
530
+ ...request.params,
531
+ ...request.body,
532
+ });
533
+ } catch (error) {
534
+ return handleErrors(error, reply);
535
+ }
536
+ },
537
+ });
538
+ }
@@ -0,0 +1,72 @@
1
+ import { AccessDeniedError, AgentNotConfiguredError } from "@catamorphic/core";
2
+ import type { FastifyInstance } from "fastify";
3
+ import type { ZodTypeProvider } from "fastify-type-provider-zod";
4
+ import type { RouteContext } from "../app.js";
5
+ import { resolveIdentity } from "../http-identity.js";
6
+ import {
7
+ EnvironmentListQuerySchema,
8
+ EnvironmentListSchema,
9
+ ErrorSchema,
10
+ ProjectIdParamsSchema,
11
+ } from "../schemas.js";
12
+
13
+ export function registerEnvironmentRoutes(
14
+ app: FastifyInstance,
15
+ ctx: RouteContext,
16
+ ): void {
17
+ const typed = app.withTypeProvider<ZodTypeProvider>();
18
+ typed.route({
19
+ method: "GET",
20
+ url: "/projects/:projectId/environments",
21
+ schema: {
22
+ params: ProjectIdParamsSchema,
23
+ querystring: EnvironmentListQuerySchema,
24
+ response: {
25
+ 200: EnvironmentListSchema,
26
+ 403: ErrorSchema,
27
+ 404: ErrorSchema,
28
+ 503: ErrorSchema,
29
+ },
30
+ },
31
+ handler: async (request, reply) => {
32
+ const service = ctx.core?.executionEnvironments;
33
+ if (!service) {
34
+ return reply
35
+ .status(503)
36
+ .send({ error: "Environment provider not configured" });
37
+ }
38
+ const identity = resolveIdentity(request);
39
+ try {
40
+ const agent = request.query.agentId
41
+ ? await ctx.core?.agentSessions?.getAgent({
42
+ identity,
43
+ projectId: request.params.projectId,
44
+ agentId: request.query.agentId,
45
+ })
46
+ : undefined;
47
+ if (request.query.agentId && !agent)
48
+ return reply.status(404).send({ error: "Agent not configured" });
49
+ const result = await service.discover({
50
+ identity,
51
+ projectId: request.params.projectId,
52
+ requirements: {
53
+ ...agent?.environment?.requirements,
54
+ workload: request.query.workload,
55
+ ...(agent ? { topology: agent.topology } : {}),
56
+ },
57
+ allowed: agent?.environment?.allowed,
58
+ preferred: agent?.environment?.preferred,
59
+ ...(agent?.signIn ? { signIn: agent.signIn } : {}),
60
+ });
61
+ return reply.send(EnvironmentListSchema.parse(result));
62
+ } catch (error) {
63
+ if (error instanceof AgentNotConfiguredError)
64
+ return reply.status(404).send({ error: error.message });
65
+ if (error instanceof AccessDeniedError) {
66
+ return reply.status(403).send({ error: error.message });
67
+ }
68
+ throw error;
69
+ }
70
+ },
71
+ });
72
+ }
@@ -0,0 +1,106 @@
1
+ import { Readable } from "node:stream";
2
+ import type { GitGatewayOperation } from "@catamorphic/core";
3
+ import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
4
+ import type { RouteContext } from "../app.js";
5
+
6
+ /**
7
+ * Git smart HTTP through the gateway (ADR 0175), for sandboxes' `git`:
8
+ * `<prefix>/gateway/git/<alias>/<repository>/info/refs`,
9
+ * `.../git-upload-pack`, and `.../git-receive-pack`. The password (or a
10
+ * bearer) is the session's grant; bodies stream both ways and are never
11
+ * parsed by Fastify. Hidden from the API spec: Git clients speak it.
12
+ */
13
+ export function registerGitGatewayRoutes(
14
+ app: FastifyInstance,
15
+ ctx: RouteContext,
16
+ ): void {
17
+ app.register(async (git) => {
18
+ git.removeAllContentTypeParsers();
19
+ git.addContentTypeParser("*", (_request, _payload, done) => done(null));
20
+ const options = {
21
+ config: { public: true },
22
+ schema: { hide: true },
23
+ } as const;
24
+ git.get("/gateway/git/:alias/*", options, (request, reply) =>
25
+ serve(ctx, request, reply, "GET"),
26
+ );
27
+ git.post("/gateway/git/:alias/*", options, (request, reply) =>
28
+ serve(ctx, request, reply, "POST"),
29
+ );
30
+ });
31
+ }
32
+
33
+ async function serve(
34
+ ctx: RouteContext,
35
+ request: FastifyRequest,
36
+ reply: FastifyReply,
37
+ method: "GET" | "POST",
38
+ ): Promise<FastifyReply> {
39
+ const gateway = ctx.core?.gitGateway;
40
+ if (!gateway)
41
+ return reply
42
+ .status(404)
43
+ .type("text/plain")
44
+ .send("This host has no Git gateway\n");
45
+ const params = request.params as { alias?: string; "*"?: string };
46
+ const alias = params.alias ?? "";
47
+ const rest = params["*"] ?? "";
48
+ const query = request.query as { service?: string };
49
+ const target = gitTarget({ method, path: rest, service: query.service });
50
+ if (!target)
51
+ return reply.status(404).type("text/plain").send("Not a Git request\n");
52
+ const headers: Record<string, string | undefined> = {};
53
+ for (const [name, value] of Object.entries(request.headers))
54
+ headers[name] = Array.isArray(value) ? value.join(", ") : value;
55
+ const response = await gateway.handle({
56
+ alias,
57
+ repositoryPath: target.repositoryPath,
58
+ operation: target.operation,
59
+ authorization: headers.authorization,
60
+ headers,
61
+ ...(method === "POST" ? { body: request.raw } : {}),
62
+ });
63
+ reply.status(response.status);
64
+ for (const [name, value] of Object.entries(response.headers))
65
+ reply.header(name, value);
66
+ // A refused upload may still be arriving; closing lets the client see
67
+ // the answer instead of waiting to finish sending.
68
+ if (method === "POST" && response.status >= 400)
69
+ reply.header("connection", "close");
70
+ return reply.send(
71
+ response.body instanceof Uint8Array
72
+ ? Buffer.from(response.body)
73
+ : Readable.from(response.body),
74
+ );
75
+ }
76
+
77
+ /** The operation and repository a smart-HTTP path names. */
78
+ export function gitTarget(input: {
79
+ method: "GET" | "POST";
80
+ path: string;
81
+ service: string | undefined;
82
+ }): { repositoryPath: string; operation: GitGatewayOperation } | null {
83
+ const path = input.path.replace(/\/+$/, "");
84
+ if (input.method === "GET" && path.endsWith("/info/refs")) {
85
+ if (
86
+ input.service !== "git-upload-pack" &&
87
+ input.service !== "git-receive-pack"
88
+ )
89
+ return null;
90
+ return {
91
+ repositoryPath: path.slice(0, -"/info/refs".length),
92
+ operation: { kind: "advertise", service: input.service },
93
+ };
94
+ }
95
+ if (input.method === "POST" && path.endsWith("/git-upload-pack"))
96
+ return {
97
+ repositoryPath: path.slice(0, -"/git-upload-pack".length),
98
+ operation: { kind: "upload-pack" },
99
+ };
100
+ if (input.method === "POST" && path.endsWith("/git-receive-pack"))
101
+ return {
102
+ repositoryPath: path.slice(0, -"/git-receive-pack".length),
103
+ operation: { kind: "receive-pack" },
104
+ };
105
+ return null;
106
+ }