@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,141 @@
1
+ import { Readable } from "node:stream";
2
+ import {
3
+ HTTP_REQUEST_MAX_BYTES,
4
+ type HttpGatewayResponse,
5
+ } from "@catamorphic/core";
6
+ import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
7
+ import type { RouteContext } from "../app.js";
8
+
9
+ const HTTP_ROUTE = "/gateway/http/";
10
+
11
+ /**
12
+ * HTTP APIs through the gateway (ADR 0212), for code in sandboxes:
13
+ * `<prefix>/gateway/http/<alias>` and anything below it, the API's own
14
+ * requests below the connection's base URL with the session's grant as a
15
+ * bearer, the Basic password, or `x-work-grant`. The grant is checked
16
+ * before the body is read; the body travels byte for byte and answers
17
+ * stream back as the API sent them. Hidden from the API spec: the API's
18
+ * own clients speak it.
19
+ */
20
+ export function registerHttpGatewayRoutes(
21
+ app: FastifyInstance,
22
+ ctx: RouteContext,
23
+ ): void {
24
+ app.register(async (http) => {
25
+ http.removeAllContentTypeParsers();
26
+ http.addContentTypeParser(
27
+ "*",
28
+ { parseAs: "buffer", bodyLimit: HTTP_REQUEST_MAX_BYTES },
29
+ (_request, body, done) => done(null, body),
30
+ );
31
+ // Runs before Fastify reads a body, for this scope's routes only.
32
+ http.addHook("onRequest", (request, reply) => admit(ctx, request, reply));
33
+ const options = {
34
+ config: { public: true },
35
+ schema: { hide: true },
36
+ bodyLimit: HTTP_REQUEST_MAX_BYTES,
37
+ } as const;
38
+ // The alias itself is the API's base URL (ClickHouse's `/?query=`).
39
+ http.all(`${HTTP_ROUTE}:alias`, options, (request, reply) =>
40
+ serve(ctx, request, reply),
41
+ );
42
+ http.all(`${HTTP_ROUTE}:alias/*`, options, (request, reply) =>
43
+ serve(ctx, request, reply),
44
+ );
45
+ });
46
+ }
47
+
48
+ function requestHeaders(
49
+ request: FastifyRequest,
50
+ ): Record<string, string | undefined> {
51
+ const headers: Record<string, string | undefined> = {};
52
+ for (const [name, value] of Object.entries(request.headers))
53
+ headers[name] = Array.isArray(value) ? value.join(", ") : value;
54
+ return headers;
55
+ }
56
+
57
+ /**
58
+ * The alias, and what follows it in the path exactly as the caller sent
59
+ * it (still percent-encoded, from its slash), from the raw URL: route
60
+ * parameters arrive decoded.
61
+ */
62
+ function routeTarget(request: FastifyRequest): {
63
+ alias: string;
64
+ path: string;
65
+ query?: string;
66
+ } {
67
+ const params = request.params as { alias?: string };
68
+ const raw = request.raw.url ?? "";
69
+ const mark = raw.indexOf("?");
70
+ const pathname = mark < 0 ? raw : raw.slice(0, mark);
71
+ const query = mark < 0 ? "" : raw.slice(mark + 1);
72
+ const at = pathname.indexOf(HTTP_ROUTE);
73
+ const rest = at < 0 ? "" : pathname.slice(at + HTTP_ROUTE.length);
74
+ const slash = rest.indexOf("/");
75
+ return {
76
+ alias: params.alias ?? "",
77
+ path: slash < 0 ? "" : rest.slice(slash),
78
+ ...(query ? { query } : {}),
79
+ };
80
+ }
81
+
82
+ function send(
83
+ reply: FastifyReply,
84
+ response: HttpGatewayResponse,
85
+ ): FastifyReply {
86
+ reply.status(response.status);
87
+ for (const [name, value] of Object.entries(response.headers))
88
+ reply.header(name, value);
89
+ return reply.send(
90
+ response.body instanceof Uint8Array
91
+ ? Buffer.from(response.body)
92
+ : Readable.from(response.body),
93
+ );
94
+ }
95
+
96
+ /** Refuse a caller without a valid grant before its body is read. */
97
+ async function admit(
98
+ ctx: RouteContext,
99
+ request: FastifyRequest,
100
+ reply: FastifyReply,
101
+ ): Promise<FastifyReply | undefined> {
102
+ const gateway = ctx.core?.httpGateway;
103
+ if (!gateway) return undefined;
104
+ const { alias } = routeTarget(request);
105
+ const result = await gateway.admit({
106
+ alias,
107
+ headers: requestHeaders(request),
108
+ });
109
+ if ("admitted" in result) return undefined;
110
+ // The unread body may still be arriving; close rather than drain it.
111
+ reply.header("connection", "close");
112
+ return send(reply, result.refused);
113
+ }
114
+
115
+ async function serve(
116
+ ctx: RouteContext,
117
+ request: FastifyRequest,
118
+ reply: FastifyReply,
119
+ ): Promise<FastifyReply> {
120
+ const gateway = ctx.core?.httpGateway;
121
+ if (!gateway)
122
+ return reply
123
+ .status(404)
124
+ .type("application/json")
125
+ .send({ error: { message: "This host has no HTTP gateway" } });
126
+ const response = await gateway.handle({
127
+ ...routeTarget(request),
128
+ method: request.method,
129
+ headers: requestHeaders(request),
130
+ ...(Buffer.isBuffer(request.body)
131
+ ? {
132
+ body: new Uint8Array(
133
+ request.body.buffer,
134
+ request.body.byteOffset,
135
+ request.body.byteLength,
136
+ ),
137
+ }
138
+ : {}),
139
+ });
140
+ return send(reply, response);
141
+ }
@@ -0,0 +1,122 @@
1
+ import { SESSION_PROTOCOL_VERSION } from "@catamorphic/agent-protocol";
2
+ import { RUNNER_PROTOCOL_VERSION } from "@catamorphic/agent-protocol/runner";
3
+ import {
4
+ type ControlPlanePermission,
5
+ effectiveProjectPermissions,
6
+ hasControlPlanePermission,
7
+ } from "@catamorphic/core";
8
+ import type { FastifyInstance } from "fastify";
9
+ import type { ZodTypeProvider } from "fastify-type-provider-zod";
10
+ import type { RouteContext } from "../app.js";
11
+ import { resolveIdentity } from "../http-identity.js";
12
+ import { MeSchema } from "../schemas.js";
13
+
14
+ /**
15
+ * The agent protocols this server speaks: the session log and its commands
16
+ * (ADR 0197) and the runner protocol its machines run (ADR 0198).
17
+ */
18
+ const AGENT_PROTOCOL = {
19
+ session: SESSION_PROTOCOL_VERSION,
20
+ runner: RUNNER_PROTOCOL_VERSION,
21
+ } as const;
22
+
23
+ const CONTROL_PLANE_PERMISSIONS: readonly ControlPlanePermission[] = [
24
+ "connections:read",
25
+ "connections:write",
26
+ ];
27
+
28
+ /**
29
+ * Introspection (ADR 0055): what THIS caller may do, and what THIS host
30
+ * enables — so a client shows the possible instead of discovering it by
31
+ * 403. Two halves: the identity as resolved (root or scope), summarised
32
+ * per project (which permissions? which agents? which store subtrees?), and
33
+ * the host's feature switches. Versioned so an older host degrades to
34
+ * "assume everything" on a newer client.
35
+ */
36
+ export function registerMeRoutes(app: FastifyInstance, ctx: RouteContext) {
37
+ const typed = app.withTypeProvider<ZodTypeProvider>();
38
+ typed.route({
39
+ method: "GET",
40
+ url: "/me",
41
+ schema: { response: { 200: MeSchema } },
42
+ handler: async (request, reply) => {
43
+ const identity = resolveIdentity(request);
44
+ const projectIds = [
45
+ ...new Set([
46
+ ...(identity.scope ?? []).map((ref) => ref.projectId),
47
+ ...(identity.projectPermissions ?? []).map((ref) => ref.projectId),
48
+ ]),
49
+ ];
50
+ const projects = await Promise.all(
51
+ projectIds.map(async (projectId) => {
52
+ const refs = (identity.scope ?? []).filter(
53
+ (ref) => ref.projectId === projectId,
54
+ );
55
+ const permissions = effectiveProjectPermissions(identity, projectId);
56
+ const overview = await Promise.resolve()
57
+ .then(() => ctx.core?.projects.getOverview({ identity, projectId }))
58
+ .catch(() => undefined);
59
+ const project =
60
+ permissions.includes("program:read") && ctx.core?.projects
61
+ ? await ctx.core.projects.get(identity, projectId)
62
+ : null;
63
+ const roles =
64
+ (await ctx.core?.memberships?.describeMember({
65
+ projectId,
66
+ tenantId: identity.tenantId,
67
+ externalUserId: identity.externalUserId,
68
+ })) ?? [];
69
+ return {
70
+ projectId,
71
+ name: overview?.name ?? projectId,
72
+ source: project?.remoteUrl
73
+ ? {
74
+ remoteUrl: project.remoteUrl,
75
+ defaultBranch: project.defaultBranch,
76
+ }
77
+ : null,
78
+ permissions,
79
+ agents: refs
80
+ .filter((ref) => ref.kind === "agent")
81
+ .map((ref) => (ref as { name: string }).name),
82
+ workflows: refs
83
+ .filter((ref) => ref.kind === "workflow")
84
+ .map((ref) => (ref as { name: string }).name),
85
+ apps: refs
86
+ .filter((ref) => ref.kind === "app")
87
+ .map((ref) => (ref as { name: string }).name),
88
+ documents: refs
89
+ .filter((ref) => ref.kind === "document")
90
+ .map((ref) => {
91
+ const doc = ref as { path: string; access?: "read" | "write" };
92
+ return { path: doc.path, access: doc.access ?? "read" };
93
+ }),
94
+ roles,
95
+ };
96
+ }),
97
+ );
98
+ const features = ctx.features;
99
+ return reply.send({
100
+ version: 1,
101
+ identity: {
102
+ externalUserId: identity.externalUserId,
103
+ root: identity.scope === undefined,
104
+ controlPlanePermissions: CONTROL_PLANE_PERMISSIONS.filter(
105
+ (permission) => hasControlPlanePermission(identity, permission),
106
+ ),
107
+ },
108
+ projects,
109
+ features: {
110
+ publications: features.publications,
111
+ proposals: features.proposals && Boolean(ctx.core?.proposals),
112
+ proposalsOpenPullRequests:
113
+ features.proposals && Boolean(ctx.core?.proposalsOpenPullRequests),
114
+ mcp: features.mcp,
115
+ agentSessions: Boolean(ctx.core?.agentSessions),
116
+ storeUploadMaxBytes: features.storeUploadMaxBytes,
117
+ },
118
+ agentProtocol: AGENT_PROTOCOL,
119
+ });
120
+ },
121
+ });
122
+ }
@@ -0,0 +1,173 @@
1
+ import { ProjectNotFoundError } from "@catamorphic/core";
2
+
3
+ class ServiceNotConfiguredError extends Error {
4
+ readonly statusCode = 503;
5
+ constructor() {
6
+ super("Service not configured");
7
+ }
8
+ }
9
+
10
+ import type { FastifyInstance } from "fastify";
11
+ import type { ZodTypeProvider } from "fastify-type-provider-zod";
12
+ import { z } from "zod";
13
+ import type { RouteContext } from "../app.js";
14
+ import { resolveIdentity } from "../http-identity.js";
15
+ import {
16
+ ErrorSchema,
17
+ GrantMembershipSchema,
18
+ MembershipParamsSchema,
19
+ MembershipSchema,
20
+ ProjectIdParamsSchema,
21
+ ProjectRoleEntrySchema,
22
+ } from "../schemas.js";
23
+
24
+ /**
25
+ * Roles and memberships (ADR 0055). Roles are committed files
26
+ * (`.work/roles/<slug>.json`) — read here, edited through the project file
27
+ * routes like any other file. Memberships are the stock `user → roles +
28
+ * grants` table: what a host's invite writes and its identity resolver
29
+ * reads (`core.memberships.identityFor`). Reads need `memberships:read`
30
+ * (a member may read their own row); changes `memberships:write`.
31
+ */
32
+ export function registerMembershipRoutes(
33
+ app: FastifyInstance,
34
+ ctx: RouteContext,
35
+ ) {
36
+ const typed = app.withTypeProvider<ZodTypeProvider>();
37
+ const core = () => {
38
+ if (!ctx.core) throw new ServiceNotConfiguredError();
39
+ return ctx.core;
40
+ };
41
+
42
+ typed.route({
43
+ method: "GET",
44
+ url: "/projects/:projectId/roles",
45
+ schema: {
46
+ params: ProjectIdParamsSchema,
47
+ response: { 200: ProjectRoleEntrySchema.array(), 404: ErrorSchema },
48
+ },
49
+ handler: async (request, reply) => {
50
+ const identity = resolveIdentity(request);
51
+ try {
52
+ return reply.send(
53
+ await core().roles.list(identity, request.params.projectId),
54
+ );
55
+ } catch (err) {
56
+ if (err instanceof ProjectNotFoundError) {
57
+ return reply.status(404).send({ error: "Project not found" });
58
+ }
59
+ throw err;
60
+ }
61
+ },
62
+ });
63
+
64
+ typed.route({
65
+ method: "GET",
66
+ url: "/projects/:projectId/memberships",
67
+ schema: {
68
+ params: ProjectIdParamsSchema,
69
+ response: { 200: MembershipSchema.array(), 404: ErrorSchema },
70
+ },
71
+ handler: async (request, reply) => {
72
+ const identity = resolveIdentity(request);
73
+ try {
74
+ return reply.send(
75
+ await core().memberships.list({
76
+ identity,
77
+ projectId: request.params.projectId,
78
+ }),
79
+ );
80
+ } catch (err) {
81
+ if (err instanceof ProjectNotFoundError) {
82
+ return reply.status(404).send({ error: "Project not found" });
83
+ }
84
+ throw err;
85
+ }
86
+ },
87
+ });
88
+
89
+ typed.route({
90
+ method: "GET",
91
+ url: "/projects/:projectId/memberships/:externalUserId",
92
+ schema: {
93
+ params: MembershipParamsSchema,
94
+ response: { 200: MembershipSchema, 404: ErrorSchema },
95
+ },
96
+ handler: async (request, reply) => {
97
+ const identity = resolveIdentity(request);
98
+ try {
99
+ const membership = await core().memberships.get({
100
+ identity,
101
+ projectId: request.params.projectId,
102
+ externalUserId: request.params.externalUserId,
103
+ });
104
+ if (!membership) {
105
+ return reply.status(404).send({ error: "Membership not found" });
106
+ }
107
+ return reply.send(membership);
108
+ } catch (err) {
109
+ if (err instanceof ProjectNotFoundError) {
110
+ return reply.status(404).send({ error: "Project not found" });
111
+ }
112
+ throw err;
113
+ }
114
+ },
115
+ });
116
+
117
+ typed.route({
118
+ method: "PUT",
119
+ url: "/projects/:projectId/memberships/:externalUserId",
120
+ schema: {
121
+ params: MembershipParamsSchema,
122
+ body: GrantMembershipSchema,
123
+ response: { 200: MembershipSchema, 404: ErrorSchema },
124
+ },
125
+ handler: async (request, reply) => {
126
+ const identity = resolveIdentity(request);
127
+ try {
128
+ return reply.send(
129
+ await core().memberships.grant({
130
+ identity,
131
+ projectId: request.params.projectId,
132
+ externalUserId: request.params.externalUserId,
133
+ roles: request.body.roles,
134
+ ...(request.body.grants ? { grants: request.body.grants } : {}),
135
+ }),
136
+ );
137
+ } catch (err) {
138
+ if (err instanceof ProjectNotFoundError) {
139
+ return reply.status(404).send({ error: "Project not found" });
140
+ }
141
+ throw err;
142
+ }
143
+ },
144
+ });
145
+
146
+ typed.route({
147
+ method: "DELETE",
148
+ url: "/projects/:projectId/memberships/:externalUserId",
149
+ schema: {
150
+ params: MembershipParamsSchema,
151
+ response: { 204: z.null(), 404: ErrorSchema },
152
+ },
153
+ handler: async (request, reply) => {
154
+ const identity = resolveIdentity(request);
155
+ try {
156
+ const removed = await core().memberships.revoke({
157
+ identity,
158
+ projectId: request.params.projectId,
159
+ externalUserId: request.params.externalUserId,
160
+ });
161
+ if (!removed) {
162
+ return reply.status(404).send({ error: "Membership not found" });
163
+ }
164
+ return reply.status(204).send(null);
165
+ } catch (err) {
166
+ if (err instanceof ProjectNotFoundError) {
167
+ return reply.status(404).send({ error: "Project not found" });
168
+ }
169
+ throw err;
170
+ }
171
+ },
172
+ });
173
+ }
@@ -0,0 +1,134 @@
1
+ import { Readable } from "node:stream";
2
+ import {
3
+ MODEL_REQUEST_MAX_BYTES,
4
+ type ModelGatewayResponse,
5
+ } from "@catamorphic/core";
6
+ import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
7
+ import type { RouteContext } from "../app.js";
8
+
9
+ const MODEL_ROUTE = "/gateway/model/";
10
+
11
+ /**
12
+ * Models through the gateway (ADR 0180), for harnesses in sandboxes:
13
+ * `<prefix>/gateway/model/<alias>/<any path below the provider's base URL>`,
14
+ * the provider's own HTTP API with the session's grant as its key, any
15
+ * method. The grant is checked before the body is read; the body travels
16
+ * byte for byte and answers stream back as the provider sent them. Hidden
17
+ * from the API spec: model clients speak it.
18
+ */
19
+ export function registerModelGatewayRoutes(
20
+ app: FastifyInstance,
21
+ ctx: RouteContext,
22
+ ): void {
23
+ app.register(async (model) => {
24
+ model.removeAllContentTypeParsers();
25
+ model.addContentTypeParser(
26
+ "*",
27
+ { parseAs: "buffer", bodyLimit: MODEL_REQUEST_MAX_BYTES },
28
+ (_request, body, done) => done(null, body),
29
+ );
30
+ // Runs before Fastify reads a body, for this scope's routes only.
31
+ model.addHook("onRequest", (request, reply) => admit(ctx, request, reply));
32
+ model.all(
33
+ `${MODEL_ROUTE}:alias/*`,
34
+ {
35
+ config: { public: true },
36
+ schema: { hide: true },
37
+ bodyLimit: MODEL_REQUEST_MAX_BYTES,
38
+ },
39
+ (request, reply) => serve(ctx, request, reply),
40
+ );
41
+ });
42
+ }
43
+
44
+ function requestHeaders(
45
+ request: FastifyRequest,
46
+ ): Record<string, string | undefined> {
47
+ const headers: Record<string, string | undefined> = {};
48
+ for (const [name, value] of Object.entries(request.headers))
49
+ headers[name] = Array.isArray(value) ? value.join(", ") : value;
50
+ return headers;
51
+ }
52
+
53
+ /**
54
+ * The alias, and the path below it exactly as the caller sent it (still
55
+ * percent-encoded), from the raw URL: route parameters arrive decoded.
56
+ */
57
+ function routeTarget(request: FastifyRequest): {
58
+ alias: string;
59
+ path: string;
60
+ query?: string;
61
+ } {
62
+ const params = request.params as { alias?: string };
63
+ const [pathname = "", query] = (request.raw.url ?? "").split("?", 2);
64
+ const at = pathname.indexOf(MODEL_ROUTE);
65
+ const rest = at < 0 ? "" : pathname.slice(at + MODEL_ROUTE.length);
66
+ const slash = rest.indexOf("/");
67
+ return {
68
+ alias: params.alias ?? "",
69
+ path: slash < 0 ? "" : rest.slice(slash + 1),
70
+ ...(query ? { query } : {}),
71
+ };
72
+ }
73
+
74
+ function send(
75
+ reply: FastifyReply,
76
+ response: ModelGatewayResponse,
77
+ ): FastifyReply {
78
+ reply.status(response.status);
79
+ for (const [name, value] of Object.entries(response.headers))
80
+ reply.header(name, value);
81
+ return reply.send(
82
+ response.body instanceof Uint8Array
83
+ ? Buffer.from(response.body)
84
+ : Readable.from(response.body),
85
+ );
86
+ }
87
+
88
+ /** Refuse a caller without a valid grant before its body is read. */
89
+ async function admit(
90
+ ctx: RouteContext,
91
+ request: FastifyRequest,
92
+ reply: FastifyReply,
93
+ ): Promise<FastifyReply | undefined> {
94
+ const gateway = ctx.core?.modelGateway;
95
+ if (!gateway) return undefined;
96
+ const { alias, path } = routeTarget(request);
97
+ const result = await gateway.admit({
98
+ alias,
99
+ path,
100
+ headers: requestHeaders(request),
101
+ });
102
+ if ("admitted" in result) return undefined;
103
+ // The unread body may still be arriving; close rather than drain it.
104
+ reply.header("connection", "close");
105
+ return send(reply, result.refused);
106
+ }
107
+
108
+ async function serve(
109
+ ctx: RouteContext,
110
+ request: FastifyRequest,
111
+ reply: FastifyReply,
112
+ ): Promise<FastifyReply> {
113
+ const gateway = ctx.core?.modelGateway;
114
+ if (!gateway)
115
+ return reply
116
+ .status(404)
117
+ .type("application/json")
118
+ .send({ error: { message: "This host has no model gateway" } });
119
+ const response = await gateway.handle({
120
+ ...routeTarget(request),
121
+ method: request.method,
122
+ headers: requestHeaders(request),
123
+ ...(Buffer.isBuffer(request.body)
124
+ ? {
125
+ body: new Uint8Array(
126
+ request.body.buffer,
127
+ request.body.byteOffset,
128
+ request.body.byteLength,
129
+ ),
130
+ }
131
+ : {}),
132
+ });
133
+ return send(reply, response);
134
+ }
@@ -0,0 +1,101 @@
1
+ import type { FastifyInstance } from "fastify";
2
+ import type { ZodTypeProvider } from "fastify-type-provider-zod";
3
+ import { z } from "zod";
4
+ import type { RouteContext } from "../app.js";
5
+ import { resolveIdentity } from "../http-identity.js";
6
+ import { AgentSessionSchema, ErrorSchema, OkSchema } from "../schemas.js";
7
+
8
+ const PushConfigSchema = z.object({
9
+ enabled: z.boolean(),
10
+ publicKey: z.string().nullable(),
11
+ });
12
+
13
+ const PushSubscriptionSchema = z.object({
14
+ endpoint: z.string().url(),
15
+ expirationTime: z.number().int().nullable(),
16
+ keys: z.object({ p256dh: z.string().min(1), auth: z.string().min(1) }),
17
+ });
18
+
19
+ const PushUnsubscribeSchema = z.object({ endpoint: z.string().url() });
20
+
21
+ export function registerNotificationRoutes(
22
+ app: FastifyInstance,
23
+ ctx: RouteContext,
24
+ ) {
25
+ const typed = app.withTypeProvider<ZodTypeProvider>();
26
+
27
+ typed.get(
28
+ "/notifications/attention",
29
+ {
30
+ schema: {
31
+ response: { 200: z.array(AgentSessionSchema), 503: ErrorSchema },
32
+ },
33
+ },
34
+ async (request, reply) => {
35
+ if (!ctx.core?.agentSessions)
36
+ return reply
37
+ .status(503)
38
+ .send({ error: "Agent sessions not configured" });
39
+ return reply.send(
40
+ await ctx.core.agentSessions.attention({
41
+ identity: resolveIdentity(request),
42
+ }),
43
+ );
44
+ },
45
+ );
46
+
47
+ typed.get(
48
+ "/notifications/push/config",
49
+ { schema: { response: { 200: PushConfigSchema, 503: ErrorSchema } } },
50
+ async (_request, reply) => {
51
+ if (!ctx.core) {
52
+ return reply
53
+ .status(503)
54
+ .send({ error: "Notifications not configured" });
55
+ }
56
+ return reply.send(ctx.core.notifications.pushConfig);
57
+ },
58
+ );
59
+
60
+ typed.put(
61
+ "/notifications/push/subscription",
62
+ {
63
+ schema: {
64
+ body: PushSubscriptionSchema,
65
+ response: { 200: OkSchema, 409: ErrorSchema, 503: ErrorSchema },
66
+ },
67
+ },
68
+ async (request, reply) => {
69
+ if (!ctx.core?.notifications.transport) {
70
+ return reply.status(409).send({ error: "Push is not enabled" });
71
+ }
72
+ await ctx.core.notifications.subscribe(resolveIdentity(request), {
73
+ ...request.body,
74
+ userAgent: request.headers["user-agent"],
75
+ });
76
+ return reply.send({ ok: true });
77
+ },
78
+ );
79
+
80
+ typed.delete(
81
+ "/notifications/push/subscription",
82
+ {
83
+ schema: {
84
+ body: PushUnsubscribeSchema,
85
+ response: { 200: OkSchema, 503: ErrorSchema },
86
+ },
87
+ },
88
+ async (request, reply) => {
89
+ if (!ctx.core) {
90
+ return reply
91
+ .status(503)
92
+ .send({ error: "Notifications not configured" });
93
+ }
94
+ await ctx.core.notifications.unsubscribe(
95
+ resolveIdentity(request),
96
+ request.body.endpoint,
97
+ );
98
+ return reply.send({ ok: true });
99
+ },
100
+ );
101
+ }
@@ -0,0 +1,32 @@
1
+ import { layoutGraph, parseWorkflowFromProject } from "@catamorphic/parser";
2
+ import type { FastifyInstance } from "fastify";
3
+ import type { ZodTypeProvider } from "fastify-type-provider-zod";
4
+ import type { RouteContext } from "../app.js";
5
+ import {
6
+ ParseWorkflowRequestSchema,
7
+ ParseWorkflowResponseSchema,
8
+ } from "../schemas.js";
9
+ import { attachTriggerKindDisplays } from "./triggers.js";
10
+
11
+ /** Parse in-flight draft files into a graph (the browser cannot run the parser). */
12
+ export function registerParseRoutes(app: FastifyInstance, ctx: RouteContext) {
13
+ const typed = app.withTypeProvider<ZodTypeProvider>();
14
+
15
+ typed.route({
16
+ method: "POST",
17
+ url: "/workflows/parse",
18
+ schema: {
19
+ body: ParseWorkflowRequestSchema,
20
+ response: { 200: ParseWorkflowResponseSchema },
21
+ },
22
+ handler: async (request, reply) => {
23
+ const { files, workflowName, preferredFilePath } = request.body;
24
+ const graph = parseWorkflowFromProject(files, workflowName, {
25
+ preferredFilePath,
26
+ });
27
+ if (!graph) return reply.send(null);
28
+ layoutGraph({ nodes: graph.nodes, edges: graph.edges });
29
+ return reply.send(attachTriggerKindDisplays(ctx.core, graph));
30
+ },
31
+ });
32
+ }