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

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,293 @@
1
+ import { APP_ICON_NAMES } from "@catamorphic/app";
2
+ import { SessionArtifactNotFoundError } from "@catamorphic/core";
3
+ import type { FastifyInstance } from "fastify";
4
+ import type { ZodTypeProvider } from "fastify-type-provider-zod";
5
+ import { z } from "zod";
6
+ import type { RouteContext } from "../app.js";
7
+ import { resolveIdentity } from "../http-identity.js";
8
+ import {
9
+ AppVersionSchema,
10
+ ErrorSchema,
11
+ RunSchema,
12
+ TriggerRunSchema,
13
+ } from "../schemas.js";
14
+
15
+ export const SessionArtifactSchema = z.object({
16
+ id: z.string().uuid(),
17
+ projectId: z.string().uuid(),
18
+ sessionId: z.string().uuid().nullable(),
19
+ kind: z.enum(["app", "workflow"]),
20
+ name: z.string(),
21
+ title: z.string(),
22
+ sourcePath: z.string(),
23
+ remoteBranch: z.string(),
24
+ commitSha: z.string(),
25
+ revision: z.number().int(),
26
+ status: z.enum(["active", "discarded"]),
27
+ appName: z.string().nullable(),
28
+ createdAt: z.string(),
29
+ updatedAt: z.string(),
30
+ });
31
+ const SessionParams = z.object({
32
+ projectId: z.string().uuid(),
33
+ sessionId: z.string().uuid(),
34
+ });
35
+ const ArtifactParams = z.object({
36
+ projectId: z.string().uuid(),
37
+ artifactId: z.string().uuid(),
38
+ });
39
+ const Files = z
40
+ .record(z.string().min(1).max(512), z.string())
41
+ .refine((files) => Object.keys(files).length <= 256);
42
+ const Outcome = z.object({
43
+ artifact: SessionArtifactSchema,
44
+ build: AppVersionSchema.nullable(),
45
+ });
46
+
47
+ export function registerSessionArtifactRoutes(
48
+ app: FastifyInstance,
49
+ ctx: RouteContext,
50
+ ) {
51
+ const typed = app.withTypeProvider<ZodTypeProvider>();
52
+ typed.route({
53
+ method: "GET",
54
+ url: "/projects/:projectId/agent/sessions/:sessionId/artifacts",
55
+ schema: {
56
+ params: SessionParams,
57
+ response: {
58
+ 200: z.array(SessionArtifactSchema),
59
+ 400: ErrorSchema,
60
+ 403: ErrorSchema,
61
+ 404: ErrorSchema,
62
+ 409: ErrorSchema,
63
+ 503: ErrorSchema,
64
+ },
65
+ },
66
+ handler: async (request, reply) => {
67
+ if (!ctx.core)
68
+ return reply.status(503).send({ error: "Artifacts are unavailable" });
69
+ return ctx.core.sessionArtifacts.list({
70
+ ...request.params,
71
+ identity: resolveIdentity(request),
72
+ });
73
+ },
74
+ });
75
+ typed.route({
76
+ method: "POST",
77
+ url: "/projects/:projectId/agent/sessions/:sessionId/artifacts",
78
+ bodyLimit: 6 * 1024 * 1024,
79
+ schema: {
80
+ params: SessionParams,
81
+ body: z.object({
82
+ kind: z.enum(["app", "workflow"]),
83
+ name: z.string().min(1).max(100),
84
+ title: z.string().max(200).optional(),
85
+ icon: z.enum(APP_ICON_NAMES).optional(),
86
+ source: z.string().max(5 * 1024 * 1024),
87
+ files: Files.optional(),
88
+ }),
89
+ response: {
90
+ 201: Outcome,
91
+ 400: ErrorSchema,
92
+ 403: ErrorSchema,
93
+ 404: ErrorSchema,
94
+ 409: ErrorSchema,
95
+ 503: ErrorSchema,
96
+ },
97
+ },
98
+ handler: async (request, reply) => {
99
+ if (!ctx.core || (request.body.kind === "app" && !ctx.core.apps))
100
+ return reply.status(503).send({ error: "Artifacts are unavailable" });
101
+ const identity = resolveIdentity(request);
102
+ const artifact = await ctx.core.sessionArtifacts.create({
103
+ ...request.params,
104
+ ...request.body,
105
+ identity,
106
+ });
107
+ const build =
108
+ artifact.appName && ctx.core.apps
109
+ ? await ctx.core.apps.build({
110
+ identity,
111
+ projectId: artifact.projectId,
112
+ appName: artifact.appName,
113
+ artifactId: artifact.id,
114
+ kind: "preview",
115
+ })
116
+ : null;
117
+ if (artifact.appName && request.body.icon && ctx.core.apps)
118
+ await ctx.core.apps.updatePresentation({
119
+ identity,
120
+ projectId: artifact.projectId,
121
+ appName: artifact.appName,
122
+ icon: request.body.icon,
123
+ });
124
+ return reply.status(201).send({ artifact, build });
125
+ },
126
+ });
127
+ typed.route({
128
+ method: "GET",
129
+ url: "/projects/:projectId/session-artifacts/:artifactId",
130
+ schema: {
131
+ params: ArtifactParams,
132
+ response: {
133
+ 200: SessionArtifactSchema,
134
+ 400: ErrorSchema,
135
+ 403: ErrorSchema,
136
+ 404: ErrorSchema,
137
+ 409: ErrorSchema,
138
+ 503: ErrorSchema,
139
+ },
140
+ },
141
+ handler: async (request, reply) => {
142
+ if (!ctx.core)
143
+ return reply.status(503).send({ error: "Artifacts are unavailable" });
144
+ try {
145
+ return await ctx.core.sessionArtifacts.get({
146
+ ...request.params,
147
+ identity: resolveIdentity(request),
148
+ });
149
+ } catch (error) {
150
+ if (error instanceof SessionArtifactNotFoundError)
151
+ return reply.status(404).send({ error: error.message });
152
+ throw error;
153
+ }
154
+ },
155
+ });
156
+ typed.route({
157
+ method: "GET",
158
+ url: "/projects/:projectId/session-artifacts/:artifactId/files",
159
+ schema: {
160
+ params: ArtifactParams,
161
+ response: {
162
+ 200: z.record(z.string(), z.string()),
163
+ 400: ErrorSchema,
164
+ 403: ErrorSchema,
165
+ 404: ErrorSchema,
166
+ 409: ErrorSchema,
167
+ 503: ErrorSchema,
168
+ },
169
+ },
170
+ handler: async (request, reply) => {
171
+ if (!ctx.core)
172
+ return reply.status(503).send({ error: "Artifacts are unavailable" });
173
+ return ctx.core.sessionArtifacts.files({
174
+ ...request.params,
175
+ identity: resolveIdentity(request),
176
+ });
177
+ },
178
+ });
179
+ typed.route({
180
+ method: "PATCH",
181
+ url: "/projects/:projectId/session-artifacts/:artifactId",
182
+ bodyLimit: 6 * 1024 * 1024,
183
+ schema: {
184
+ params: ArtifactParams,
185
+ body: z.object({
186
+ revision: z.number().int().positive(),
187
+ title: z.string().max(200).optional(),
188
+ files: z.record(z.string().min(1).max(512), z.string().nullable()),
189
+ }),
190
+ response: {
191
+ 200: Outcome,
192
+ 400: ErrorSchema,
193
+ 403: ErrorSchema,
194
+ 404: ErrorSchema,
195
+ 409: ErrorSchema,
196
+ 503: ErrorSchema,
197
+ },
198
+ },
199
+ handler: async (request, reply) => {
200
+ if (!ctx.core)
201
+ return reply.status(503).send({ error: "Artifacts are unavailable" });
202
+ const identity = resolveIdentity(request);
203
+ const artifact = await ctx.core.sessionArtifacts.update({
204
+ ...request.params,
205
+ ...request.body,
206
+ identity,
207
+ });
208
+ const build =
209
+ artifact.appName && ctx.core.apps
210
+ ? await ctx.core.apps.build({
211
+ identity,
212
+ projectId: artifact.projectId,
213
+ appName: artifact.appName,
214
+ artifactId: artifact.id,
215
+ kind: "preview",
216
+ })
217
+ : null;
218
+ return { artifact, build };
219
+ },
220
+ });
221
+ typed.route({
222
+ method: "DELETE",
223
+ url: "/projects/:projectId/session-artifacts/:artifactId",
224
+ schema: {
225
+ params: ArtifactParams,
226
+ response: {
227
+ 204: z.null(),
228
+ 400: ErrorSchema,
229
+ 403: ErrorSchema,
230
+ 404: ErrorSchema,
231
+ 409: ErrorSchema,
232
+ 503: ErrorSchema,
233
+ },
234
+ },
235
+ handler: async (request, reply) => {
236
+ if (!ctx.core)
237
+ return reply.status(503).send({ error: "Artifacts are unavailable" });
238
+ const identity = resolveIdentity(request);
239
+ const artifact = await ctx.core.sessionArtifacts.discard({
240
+ ...request.params,
241
+ identity,
242
+ });
243
+ if (artifact.sessionId && ctx.core.watchers)
244
+ await ctx.core.watchers.stop({
245
+ identity,
246
+ projectId: artifact.projectId,
247
+ sessionId: artifact.sessionId,
248
+ watcherId: artifact.id,
249
+ });
250
+ return reply.status(204).send(null);
251
+ },
252
+ });
253
+ typed.route({
254
+ method: "POST",
255
+ url: "/projects/:projectId/session-artifacts/:artifactId/runs",
256
+ schema: {
257
+ params: ArtifactParams,
258
+ body: TriggerRunSchema.extend({ environment: z.string().optional() }),
259
+ response: {
260
+ 201: RunSchema,
261
+ 400: ErrorSchema,
262
+ 403: ErrorSchema,
263
+ 404: ErrorSchema,
264
+ 409: ErrorSchema,
265
+ 503: ErrorSchema,
266
+ },
267
+ },
268
+ handler: async (request, reply) => {
269
+ if (!ctx.core)
270
+ return reply.status(503).send({ error: "Artifacts are unavailable" });
271
+ const identity = resolveIdentity(request);
272
+ const artifact = await ctx.core.sessionArtifacts.get({
273
+ ...request.params,
274
+ identity,
275
+ });
276
+ if (artifact.kind !== "workflow")
277
+ return reply.status(400).send({ error: "This artifact is an app" });
278
+ await ctx.core.sessionArtifacts.assertActive({
279
+ ...request.params,
280
+ identity,
281
+ });
282
+ const run = await ctx.core.runs.triggerAtCommit({
283
+ ...request.body,
284
+ identity,
285
+ projectId: artifact.projectId,
286
+ workflowName: artifact.name,
287
+ commitSha: artifact.commitSha,
288
+ remoteBranch: artifact.remoteBranch,
289
+ });
290
+ return reply.status(201).send(run);
291
+ },
292
+ });
293
+ }
@@ -0,0 +1,80 @@
1
+ import { SessionMailboxNotFoundError } 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
+ AcknowledgeSessionMailboxSchema,
8
+ ErrorSchema,
9
+ OkSchema,
10
+ ProjectIdParamsSchema,
11
+ SessionMailboxIdParamsSchema,
12
+ SessionMailboxListQuerySchema,
13
+ SessionMailboxListSchema,
14
+ } from "../schemas.js";
15
+
16
+ export function registerSessionMailboxRoutes(
17
+ app: FastifyInstance,
18
+ ctx: RouteContext,
19
+ ) {
20
+ const typed = app.withTypeProvider<ZodTypeProvider>();
21
+
22
+ typed.route({
23
+ method: "GET",
24
+ url: "/projects/:projectId/session-mailboxes",
25
+ schema: {
26
+ params: ProjectIdParamsSchema,
27
+ querystring: SessionMailboxListQuerySchema,
28
+ response: {
29
+ 200: SessionMailboxListSchema,
30
+ 503: ErrorSchema,
31
+ },
32
+ },
33
+ handler: async (request, reply) => {
34
+ const mailboxes = ctx.core?.sessionMailboxes;
35
+ if (!mailboxes) {
36
+ return reply
37
+ .status(503)
38
+ .send({ error: "Agent sessions not configured" });
39
+ }
40
+ const items = await mailboxes.list(
41
+ resolveIdentity(request),
42
+ request.params.projectId,
43
+ request.query,
44
+ );
45
+ return reply.send({ items });
46
+ },
47
+ });
48
+
49
+ typed.route({
50
+ method: "POST",
51
+ url: "/projects/:projectId/session-mailboxes/:mailboxId/acknowledge",
52
+ schema: {
53
+ params: SessionMailboxIdParamsSchema,
54
+ body: AcknowledgeSessionMailboxSchema,
55
+ response: { 200: OkSchema, 404: ErrorSchema, 503: ErrorSchema },
56
+ },
57
+ handler: async (request, reply) => {
58
+ const mailboxes = ctx.core?.sessionMailboxes;
59
+ if (!mailboxes) {
60
+ return reply
61
+ .status(503)
62
+ .send({ error: "Agent sessions not configured" });
63
+ }
64
+ try {
65
+ await mailboxes.acknowledge(
66
+ resolveIdentity(request),
67
+ request.params.projectId,
68
+ request.params.mailboxId,
69
+ request.body,
70
+ );
71
+ return reply.send({ ok: true });
72
+ } catch (error) {
73
+ if (error instanceof SessionMailboxNotFoundError) {
74
+ return reply.status(404).send({ error: error.message });
75
+ }
76
+ throw error;
77
+ }
78
+ },
79
+ });
80
+ }
@@ -0,0 +1,224 @@
1
+ import {
2
+ PREVIEW_REQUEST_MAX_BYTES,
3
+ type PreviewResponse,
4
+ SessionPreviewError,
5
+ } from "@catamorphic/core";
6
+ import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
7
+ import type { RouteContext } from "../app.js";
8
+ import { resolveIdentity } from "../http-identity.js";
9
+ import { workspaceRefusal } from "./session-terminals.js";
10
+
11
+ const SESSION_UUID =
12
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
13
+
14
+ /** Hosts a server in the workspace calls itself in an absolute redirect. */
15
+ const LOOPBACK_HOSTS = ["localhost", "127.0.0.1", "0.0.0.0", "[::1]"];
16
+
17
+ /**
18
+ * Marks an answer as the preview route's own refusal (the workspace is not
19
+ * running, nothing listens on the port), never the previewed server's.
20
+ */
21
+ export const PREVIEW_REFUSAL_HEADER = "x-work-preview-refusal";
22
+
23
+ /** Response headers the route sets itself. */
24
+ const OWN_RESPONSE_HEADERS = [
25
+ "content-length",
26
+ "connection",
27
+ "keep-alive",
28
+ PREVIEW_REFUSAL_HEADER,
29
+ ];
30
+
31
+ /**
32
+ * Previews of servers running in a chat's workspace (ADR 0209):
33
+ * `<prefix>/projects/:projectId/agent/sessions/:sessionId/previews/:port/*`,
34
+ * any method, forwarded to that port inside the workspace by the
35
+ * sandbox's own runtime. The body travels byte for byte; the answer comes
36
+ * back with its status and headers, every `Set-Cookie` kept, and a
37
+ * redirect to the server itself pointed back below the preview's prefix.
38
+ * WebSocket upgrades are not forwarded. Hidden from the API spec: browsers
39
+ * speak it, through a client that adds the member's credentials.
40
+ */
41
+ export function registerSessionPreviewRoutes(
42
+ app: FastifyInstance,
43
+ ctx: RouteContext,
44
+ ): void {
45
+ app.register(async (previews) => {
46
+ previews.removeAllContentTypeParsers();
47
+ previews.addContentTypeParser(
48
+ "*",
49
+ { parseAs: "buffer", bodyLimit: PREVIEW_REQUEST_MAX_BYTES },
50
+ (_request, body, done) => done(null, body),
51
+ );
52
+ // `/previews/3000` gets its slash, so the page's relative URLs land
53
+ // below the preview.
54
+ previews.get(
55
+ "/projects/:projectId/agent/sessions/:sessionId/previews/:port",
56
+ { schema: { hide: true } },
57
+ (request, reply) => {
58
+ const [pathname = "", query] = (request.raw.url ?? "").split("?", 2);
59
+ return reply.redirect(
60
+ `${pathname}/${query === undefined ? "" : `?${query}`}`,
61
+ 308,
62
+ );
63
+ },
64
+ );
65
+ previews.all(
66
+ "/projects/:projectId/agent/sessions/:sessionId/previews/:port/*",
67
+ {
68
+ schema: { hide: true },
69
+ bodyLimit: PREVIEW_REQUEST_MAX_BYTES,
70
+ },
71
+ (request, reply) => serve(ctx, request, reply),
72
+ );
73
+ });
74
+ }
75
+
76
+ async function serve(
77
+ ctx: RouteContext,
78
+ request: FastifyRequest,
79
+ reply: FastifyReply,
80
+ ): Promise<FastifyReply> {
81
+ // Until the server in the workspace answers, any answer is the route's
82
+ // own; a client tells the two apart by this header.
83
+ reply.header(PREVIEW_REFUSAL_HEADER, "1");
84
+ const previews = ctx.core?.sessionPreviews;
85
+ if (!previews)
86
+ return reply.status(503).send({ error: "Agent sessions not configured" });
87
+ const params = request.params as {
88
+ projectId?: string;
89
+ sessionId?: string;
90
+ port?: string;
91
+ };
92
+ const port = Number(params.port);
93
+ if (
94
+ !SESSION_UUID.test(params.projectId ?? "") ||
95
+ !SESSION_UUID.test(params.sessionId ?? "") ||
96
+ !/^\d{1,5}$/.test(params.port ?? "") ||
97
+ port < 1 ||
98
+ port > 65535
99
+ )
100
+ return reply.status(400).send({ error: "Invalid preview address" });
101
+ const target = previewTarget({ url: request.raw.url ?? "", port });
102
+ if (!target)
103
+ return reply.status(400).send({ error: "Invalid preview address" });
104
+ try {
105
+ const response = await previews.request({
106
+ identity: resolveIdentity(request),
107
+ projectId: params.projectId ?? "",
108
+ sessionId: params.sessionId ?? "",
109
+ port,
110
+ method: request.method,
111
+ path: target.path,
112
+ headers: requestHeaderPairs(request),
113
+ ...(Buffer.isBuffer(request.body) && request.body.byteLength > 0
114
+ ? {
115
+ body: new Uint8Array(
116
+ request.body.buffer,
117
+ request.body.byteOffset,
118
+ request.body.byteLength,
119
+ ),
120
+ }
121
+ : {}),
122
+ });
123
+ reply.removeHeader(PREVIEW_REFUSAL_HEADER);
124
+ return send({ reply, response, prefix: target.prefix, port });
125
+ } catch (error) {
126
+ if (error instanceof SessionPreviewError)
127
+ return reply
128
+ .status(error.reason === "invalid" ? 400 : 502)
129
+ .send({ error: error.message, code: error.reason });
130
+ const refused = workspaceRefusal(reply, error);
131
+ if (refused) return refused;
132
+ throw error;
133
+ }
134
+ }
135
+
136
+ /**
137
+ * The preview's prefix (everything through `/previews/<port>`, as the
138
+ * caller addressed it) and the path below it, still percent-encoded.
139
+ */
140
+ export function previewTarget(input: {
141
+ url: string;
142
+ port: number;
143
+ }): { prefix: string; path: string } | undefined {
144
+ const [pathname = "", query] = input.url.split("?", 2);
145
+ const marker = `/previews/${input.port}`;
146
+ const at = pathname.indexOf(`${marker}/`);
147
+ if (at < 0) return undefined;
148
+ const prefix = pathname.slice(0, at + marker.length);
149
+ const rest = pathname.slice(prefix.length) || "/";
150
+ return {
151
+ prefix,
152
+ path: `${rest}${query === undefined ? "" : `?${query}`}`,
153
+ };
154
+ }
155
+
156
+ /**
157
+ * A redirect within the previewed server, below the preview's prefix: a
158
+ * root-relative location, or an absolute one naming the server itself on
159
+ * a loopback host. Anything else (relative, elsewhere) is left alone.
160
+ */
161
+ export function rewritePreviewLocation(input: {
162
+ location: string;
163
+ prefix: string;
164
+ port: number;
165
+ }): string {
166
+ const { location, prefix } = input;
167
+ if (location.startsWith("/") && !location.startsWith("//"))
168
+ return `${prefix}${location}`;
169
+ let parsed: URL;
170
+ try {
171
+ parsed = new URL(location);
172
+ } catch {
173
+ return location;
174
+ }
175
+ const defaultPort = parsed.protocol === "https:" ? 443 : 80;
176
+ const port = parsed.port ? Number(parsed.port) : defaultPort;
177
+ if (
178
+ (parsed.protocol === "http:" || parsed.protocol === "https:") &&
179
+ LOOPBACK_HOSTS.includes(parsed.hostname) &&
180
+ port === input.port
181
+ )
182
+ return `${prefix}${parsed.pathname}${parsed.search}${parsed.hash}`;
183
+ return location;
184
+ }
185
+
186
+ function requestHeaderPairs(request: FastifyRequest): Array<[string, string]> {
187
+ const raw = request.raw.rawHeaders;
188
+ const pairs: Array<[string, string]> = [];
189
+ for (let index = 0; index + 1 < raw.length; index += 2) {
190
+ const name = raw[index];
191
+ const value = raw[index + 1];
192
+ if (name !== undefined && value !== undefined) pairs.push([name, value]);
193
+ }
194
+ return pairs;
195
+ }
196
+
197
+ function send(input: {
198
+ reply: FastifyReply;
199
+ response: PreviewResponse;
200
+ prefix: string;
201
+ port: number;
202
+ }): FastifyReply {
203
+ const { reply, response } = input;
204
+ reply.status(response.status);
205
+ const grouped = new Map<string, string[]>();
206
+ for (const [name, value] of response.headers) {
207
+ const key = name.toLowerCase();
208
+ if (OWN_RESPONSE_HEADERS.includes(key)) continue;
209
+ const values = grouped.get(key) ?? [];
210
+ values.push(
211
+ key === "location"
212
+ ? rewritePreviewLocation({
213
+ location: value,
214
+ prefix: input.prefix,
215
+ port: input.port,
216
+ })
217
+ : value,
218
+ );
219
+ grouped.set(key, values);
220
+ }
221
+ for (const [name, values] of grouped)
222
+ reply.header(name, name === "set-cookie" ? values : values.join(", "));
223
+ return reply.send(Buffer.from(response.body));
224
+ }