@zyro-sec/protocol 0.0.0-stage → 1.0.1

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 (62) hide show
  1. package/openapi.json +33222 -0
  2. package/package.json +33 -4
  3. package/script/build.ts +9 -0
  4. package/script/generate-openapi.ts +25 -0
  5. package/script/openapi-parameters.ts +30 -0
  6. package/script/openapi-stabilize.ts +102 -0
  7. package/script/pack.ts +5 -0
  8. package/src/api.ts +264 -0
  9. package/src/client.ts +127 -0
  10. package/src/errors.ts +398 -0
  11. package/src/groups/agent.ts +39 -0
  12. package/src/groups/artifact.ts +103 -0
  13. package/src/groups/automation.ts +75 -0
  14. package/src/groups/blob.ts +20 -0
  15. package/src/groups/command.ts +27 -0
  16. package/src/groups/config.ts +46 -0
  17. package/src/groups/credential.ts +72 -0
  18. package/src/groups/debug.ts +68 -0
  19. package/src/groups/event.ts +86 -0
  20. package/src/groups/experimental.ts +19 -0
  21. package/src/groups/form.ts +26 -0
  22. package/src/groups/fs.ts +136 -0
  23. package/src/groups/generate.ts +120 -0
  24. package/src/groups/integration.ts +230 -0
  25. package/src/groups/job.ts +57 -0
  26. package/src/groups/location.ts +66 -0
  27. package/src/groups/machine.ts +120 -0
  28. package/src/groups/mcp.ts +167 -0
  29. package/src/groups/media.ts +23 -0
  30. package/src/groups/message.ts +124 -0
  31. package/src/groups/migration.ts +28 -0
  32. package/src/groups/model.ts +52 -0
  33. package/src/groups/permission.ts +164 -0
  34. package/src/groups/persistent-pty.ts +153 -0
  35. package/src/groups/plugin.ts +80 -0
  36. package/src/groups/project.ts +51 -0
  37. package/src/groups/provider.ts +45 -0
  38. package/src/groups/pty.ts +153 -0
  39. package/src/groups/push.ts +94 -0
  40. package/src/groups/reference.ts +42 -0
  41. package/src/groups/rpc.ts +30 -0
  42. package/src/groups/server.ts +80 -0
  43. package/src/groups/session.ts +918 -0
  44. package/src/groups/shell.ts +88 -0
  45. package/src/groups/skill.ts +46 -0
  46. package/src/groups/usage.ts +30 -0
  47. package/src/groups/vcs.ts +131 -0
  48. package/src/groups/voice.ts +96 -0
  49. package/src/groups/websearch.ts +46 -0
  50. package/src/groups/worktree.ts +78 -0
  51. package/src/middleware/authorization.ts +6 -0
  52. package/src/middleware/schema-error.ts +7 -0
  53. package/src/simulation.ts +691 -0
  54. package/test/event.test.ts +34 -0
  55. package/test/experimental-identifiers.test.ts +24 -0
  56. package/test/openapi-parameters.test.ts +43 -0
  57. package/test/openapi-patterns.test.ts +28 -0
  58. package/test/openapi-stabilize.test.ts +161 -0
  59. package/test/session-cursor.test.ts +7 -0
  60. package/tsconfig.build.json +11 -0
  61. package/tsconfig.json +14 -0
  62. package/README.md +0 -3
@@ -0,0 +1,230 @@
1
+ import { Integration } from "@zyro-sec/schema/integration"
2
+ import { Location } from "@zyro-sec/schema/location"
3
+ import { Form } from "@zyro-sec/schema/form"
4
+ import { Schema } from "effect"
5
+ import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from "effect/http-api"
6
+ import {
7
+ IntegrationAttemptNotFoundError,
8
+ IntegrationMethodNotFoundError,
9
+ IntegrationNotFoundError,
10
+ InvalidRequestError,
11
+ } from "../errors.js"
12
+ import { LocationQuery, locationQueryOpenApi } from "./location.js"
13
+
14
+ export const IntegrationGroup = HttpApiGroup.make("server.integration")
15
+ .add(
16
+ HttpApiEndpoint.get("integration.list", "/api/integration", {
17
+ query: LocationQuery,
18
+ success: Location.response(Schema.Array(Integration.Info)),
19
+ })
20
+ .annotateMerge(locationQueryOpenApi)
21
+ .annotateMerge(
22
+ OpenApi.annotations({
23
+ identifier: "integration.list",
24
+ summary: "List integrations",
25
+ description: "Retrieve available integrations and their authentication methods.",
26
+ }),
27
+ ),
28
+ )
29
+ .add(
30
+ HttpApiEndpoint.get("integration.get", "/api/integration/:integrationID", {
31
+ params: { integrationID: Integration.ID },
32
+ query: LocationQuery,
33
+ success: Location.response(Integration.Info),
34
+ error: IntegrationNotFoundError,
35
+ })
36
+ .annotateMerge(locationQueryOpenApi)
37
+ .annotateMerge(
38
+ OpenApi.annotations({
39
+ identifier: "integration.get",
40
+ summary: "Get integration",
41
+ description: "Retrieve one integration and its authentication methods.",
42
+ }),
43
+ ),
44
+ )
45
+ .add(
46
+ HttpApiEndpoint.post("integration.wellknown.add", "/api/experimental/integration/wellknown", {
47
+ query: LocationQuery,
48
+ payload: Schema.Struct({ url: Schema.String }),
49
+ success: HttpApiSchema.NoContent,
50
+ error: InvalidRequestError,
51
+ })
52
+ .annotateMerge(locationQueryOpenApi)
53
+ .annotateMerge(
54
+ OpenApi.annotations({
55
+ identifier: "experimental.integration.wellknown.add",
56
+ summary: "Add wellknown integration",
57
+ description: "Discover and persist an experimental wellknown integration source.",
58
+ }),
59
+ ),
60
+ )
61
+ .add(
62
+ HttpApiEndpoint.post("integration.connect.key", "/api/integration/:integrationID/connect/key", {
63
+ params: { integrationID: Integration.ID },
64
+ query: LocationQuery,
65
+ payload: Schema.Struct({
66
+ key: Schema.String,
67
+ answer: Schema.optional(Form.Answer),
68
+ label: Schema.optional(Schema.String),
69
+ }),
70
+ success: HttpApiSchema.NoContent,
71
+ error: [IntegrationNotFoundError, InvalidRequestError],
72
+ })
73
+ .annotateMerge(locationQueryOpenApi)
74
+ .annotateMerge(
75
+ OpenApi.annotations({
76
+ identifier: "integration.connect.key",
77
+ summary: "Connect with key",
78
+ description: "Run a key authentication method and store the resulting credential.",
79
+ }),
80
+ ),
81
+ )
82
+ .add(
83
+ HttpApiEndpoint.post("integration.connect.external", "/api/integration/:integrationID/connect/external", {
84
+ params: { integrationID: Integration.ID },
85
+ query: LocationQuery,
86
+ payload: Schema.Struct({
87
+ methodID: Integration.MethodID,
88
+ answer: Schema.optional(Form.Answer),
89
+ label: Schema.optional(Schema.String),
90
+ }),
91
+ success: HttpApiSchema.NoContent,
92
+ error: [IntegrationNotFoundError, InvalidRequestError],
93
+ })
94
+ .annotateMerge(locationQueryOpenApi)
95
+ .annotateMerge(
96
+ OpenApi.annotations({
97
+ identifier: "integration.connect.external",
98
+ summary: "Connect with external credentials",
99
+ description: "Run an external authentication method and store a reference to its credential source.",
100
+ }),
101
+ ),
102
+ )
103
+ .add(
104
+ HttpApiEndpoint.post("integration.oauth.connect", "/api/integration/:integrationID/connect/oauth", {
105
+ params: { integrationID: Integration.ID },
106
+ query: LocationQuery,
107
+ payload: Schema.Struct({
108
+ methodID: Integration.MethodID,
109
+ answer: Schema.optional(Form.Answer),
110
+ label: Schema.optional(Schema.String),
111
+ }),
112
+ success: Location.response(Integration.Attempt),
113
+ error: InvalidRequestError,
114
+ })
115
+ .annotateMerge(locationQueryOpenApi)
116
+ .annotateMerge(
117
+ OpenApi.annotations({
118
+ identifier: "integration.oauth.connect",
119
+ summary: "Begin OAuth connection",
120
+ description: "Start an OAuth attempt and return the authorization details.",
121
+ }),
122
+ ),
123
+ )
124
+ .add(
125
+ HttpApiEndpoint.get("integration.oauth.status", "/api/integration/:integrationID/connect/oauth/:attemptID", {
126
+ params: { integrationID: Integration.ID, attemptID: Integration.AttemptID },
127
+ query: LocationQuery,
128
+ success: Location.response(Integration.AttemptStatus),
129
+ error: [IntegrationNotFoundError, IntegrationAttemptNotFoundError],
130
+ })
131
+ .annotateMerge(locationQueryOpenApi)
132
+ .annotateMerge(
133
+ OpenApi.annotations({
134
+ identifier: "integration.oauth.status",
135
+ summary: "Get OAuth attempt status",
136
+ description: "Poll the current status of an OAuth attempt.",
137
+ }),
138
+ ),
139
+ )
140
+ .add(
141
+ HttpApiEndpoint.post(
142
+ "integration.oauth.complete",
143
+ "/api/integration/:integrationID/connect/oauth/:attemptID/complete",
144
+ {
145
+ params: { integrationID: Integration.ID, attemptID: Integration.AttemptID },
146
+ query: LocationQuery,
147
+ payload: Schema.Struct({ code: Schema.optional(Schema.String) }),
148
+ success: HttpApiSchema.NoContent,
149
+ error: [IntegrationNotFoundError, IntegrationAttemptNotFoundError, InvalidRequestError],
150
+ },
151
+ )
152
+ .annotateMerge(locationQueryOpenApi)
153
+ .annotateMerge(
154
+ OpenApi.annotations({
155
+ identifier: "integration.oauth.complete",
156
+ summary: "Complete OAuth connection",
157
+ description:
158
+ "Complete a code-based OAuth attempt and store the resulting credential. For an automatic attempt with `paste`, `code` is the redirect URL copied from the browser, and the result arrives through the attempt status.",
159
+ }),
160
+ ),
161
+ )
162
+ .add(
163
+ HttpApiEndpoint.delete("integration.oauth.cancel", "/api/integration/:integrationID/connect/oauth/:attemptID", {
164
+ params: { integrationID: Integration.ID, attemptID: Integration.AttemptID },
165
+ query: LocationQuery,
166
+ success: HttpApiSchema.NoContent,
167
+ })
168
+ .annotateMerge(locationQueryOpenApi)
169
+ .annotateMerge(
170
+ OpenApi.annotations({
171
+ identifier: "integration.oauth.cancel",
172
+ summary: "Cancel OAuth connection",
173
+ description: "Cancel an OAuth attempt and release its resources.",
174
+ }),
175
+ ),
176
+ )
177
+ .add(
178
+ HttpApiEndpoint.post("integration.command.connect", "/api/integration/:integrationID/connect/command", {
179
+ params: { integrationID: Integration.ID },
180
+ query: LocationQuery,
181
+ payload: Schema.Struct({
182
+ methodID: Integration.MethodID,
183
+ label: Schema.optional(Schema.String),
184
+ }),
185
+ success: Location.response(Integration.CommandAttempt),
186
+ error: [IntegrationNotFoundError, IntegrationMethodNotFoundError, InvalidRequestError],
187
+ })
188
+ .annotateMerge(locationQueryOpenApi)
189
+ .annotateMerge(
190
+ OpenApi.annotations({
191
+ identifier: "integration.command.connect",
192
+ summary: "Begin command connection",
193
+ description: "Start a command authentication attempt.",
194
+ }),
195
+ ),
196
+ )
197
+ .add(
198
+ HttpApiEndpoint.get("integration.command.status", "/api/integration/:integrationID/connect/command/:attemptID", {
199
+ params: { integrationID: Integration.ID, attemptID: Integration.AttemptID },
200
+ query: LocationQuery,
201
+ success: Location.response(Integration.CommandAttemptStatus),
202
+ error: [IntegrationNotFoundError, IntegrationAttemptNotFoundError],
203
+ })
204
+ .annotateMerge(locationQueryOpenApi)
205
+ .annotateMerge(
206
+ OpenApi.annotations({
207
+ identifier: "integration.command.status",
208
+ summary: "Get command attempt status",
209
+ description: "Poll the current status and output of a command authentication attempt.",
210
+ }),
211
+ ),
212
+ )
213
+ .add(
214
+ HttpApiEndpoint.delete("integration.command.cancel", "/api/integration/:integrationID/connect/command/:attemptID", {
215
+ params: { integrationID: Integration.ID, attemptID: Integration.AttemptID },
216
+ query: LocationQuery,
217
+ success: HttpApiSchema.NoContent,
218
+ })
219
+ .annotateMerge(locationQueryOpenApi)
220
+ .annotateMerge(
221
+ OpenApi.annotations({
222
+ identifier: "integration.command.cancel",
223
+ summary: "Cancel command connection",
224
+ description: "Cancel a command authentication attempt and terminate its process.",
225
+ }),
226
+ ),
227
+ )
228
+ .annotateMerge(
229
+ OpenApi.annotations({ title: "integration", description: "Integration discovery and authentication routes." }),
230
+ )
@@ -0,0 +1,57 @@
1
+ import { Job } from "@zyro-sec/schema/job"
2
+ import { Session } from "@zyro-sec/schema/session"
3
+ import { Schema, SchemaGetter } from "effect"
4
+ import { HttpApiEndpoint, HttpApiSchema, OpenApi } from "effect/http-api"
5
+ import { InvalidRequestError, SessionNotFoundError } from "../errors.js"
6
+
7
+ const BooleanFromString = Schema.Literals(["true", "false"]).pipe(
8
+ Schema.decodeTo(Schema.Boolean, {
9
+ decode: SchemaGetter.transform((value) => value === "true"),
10
+ encode: SchemaGetter.transform((value): "true" | "false" => (value ? "true" : "false")),
11
+ }),
12
+ )
13
+
14
+ export const ListQuery = Schema.Struct({
15
+ sessionID: Schema.optional(Session.ID).annotate({
16
+ description: "Filter to background jobs owned by this session.",
17
+ }),
18
+ kind: Schema.optional(Job.Kind).annotate({
19
+ description: "Filter by background job kind.",
20
+ }),
21
+ status: Schema.optional(Job.Status).annotate({
22
+ description: "Filter by job status (running, completed, error, or cancelled).",
23
+ }),
24
+ descendants: Schema.optional(BooleanFromString).annotate({
25
+ description: "When sessionID is set, also include background jobs owned by child and nested subagent sessions.",
26
+ }),
27
+ }).annotate({ identifier: "Job.ListQuery" })
28
+ export type ListQuery = typeof ListQuery.Type
29
+
30
+ /** Lives in the `server.experimental` group (see `groups/experimental.ts`). */
31
+ export const JobEndpoints = [
32
+ HttpApiEndpoint.get("job.list", "/api/experimental/job", {
33
+ query: ListQuery,
34
+ success: Schema.Struct({ data: Schema.Array(Job.Info) }),
35
+ error: [InvalidRequestError, SessionNotFoundError],
36
+ }).annotateMerge(
37
+ OpenApi.annotations({
38
+ identifier: "experimental.job.list",
39
+ summary: "List background jobs",
40
+ description:
41
+ "List active and unconsumed background jobs, optionally filtered by owning session, descendants, or kind. Experimental: may change without compatibility guarantees.",
42
+ transform: (operation) => ({ ...operation, tags: ["experimental"] }),
43
+ }),
44
+ ),
45
+ HttpApiEndpoint.post("job.cancel", "/api/experimental/job/:id/cancel", {
46
+ params: { id: Schema.String },
47
+ success: HttpApiSchema.NoContent,
48
+ }).annotateMerge(
49
+ OpenApi.annotations({
50
+ identifier: "experimental.job.cancel",
51
+ summary: "Cancel background job",
52
+ description:
53
+ "Cancel a running background job, interrupting the work it started. Cancelling a job that already finished does nothing. Experimental: may change without compatibility guarantees.",
54
+ transform: (operation) => ({ ...operation, tags: ["experimental"] }),
55
+ }),
56
+ ),
57
+ ] as const
@@ -0,0 +1,66 @@
1
+ import { Location } from "@zyro-sec/schema/location"
2
+ import { Context, Schema } from "effect"
3
+ import { HttpApiEndpoint, HttpApiGroup, HttpApiMiddleware, HttpApiSchema, OpenApi } from "effect/http-api"
4
+ import { ServiceUnavailableError } from "../errors.js"
5
+
6
+ export const LocationQuery = Schema.Struct({
7
+ location: Schema.optional(
8
+ Schema.Struct({
9
+ directory: Schema.optional(Schema.String).annotate({ description: "Absolute path of the directory." }),
10
+ }),
11
+ ).annotateKey({
12
+ description:
13
+ "Location to run the request in, sent as location[directory]. Omit to use the server's default location.",
14
+ }),
15
+ }).annotate({ identifier: "LocationQuery" })
16
+
17
+ export const locationQueryOpenApi = OpenApi.annotations({
18
+ transform: (operation) => {
19
+ const parameters = operation.parameters
20
+ if (!Array.isArray(parameters)) return operation
21
+ return {
22
+ ...operation,
23
+ parameters: parameters.map((parameter) =>
24
+ parameter?.name === "location" && parameter?.in === "query"
25
+ ? { ...parameter, style: "deepObject", explode: true }
26
+ : parameter,
27
+ ),
28
+ }
29
+ },
30
+ })
31
+
32
+ // Middleware is applied per endpoint: reload acts on every loaded location and
33
+ // must not boot the caller's location first.
34
+ export const makeLocationGroup = <LocationId extends HttpApiMiddleware.AnyId, LocationService>(
35
+ locationMiddleware: Context.Key<LocationId, LocationService>,
36
+ ) =>
37
+ HttpApiGroup.make("server.location")
38
+ .add(
39
+ HttpApiEndpoint.get("location.get", "/api/location", {
40
+ query: LocationQuery,
41
+ success: Location.PublicInfo,
42
+ })
43
+ .middleware(locationMiddleware)
44
+ .annotateMerge(locationQueryOpenApi)
45
+ .annotateMerge(
46
+ OpenApi.annotations({
47
+ identifier: "location.get",
48
+ summary: "Get location",
49
+ description: "Resolve the requested location or the server default location.",
50
+ }),
51
+ ),
52
+ )
53
+ .add(
54
+ HttpApiEndpoint.post("location.reload", "/api/location/reload", {
55
+ success: HttpApiSchema.NoContent,
56
+ error: ServiceUnavailableError,
57
+ }).annotateMerge(
58
+ OpenApi.annotations({
59
+ identifier: "location.reload",
60
+ summary: "Reload configuration",
61
+ description:
62
+ "Shut down and rebuild every loaded location. Pending permissions and forms are cancelled; running sessions continue with fresh services at the next step boundary. Emits location.shutdown for client recovery and responds once all replacement builds settle.",
63
+ }),
64
+ ),
65
+ )
66
+ .annotateMerge(OpenApi.annotations({ title: "location" }))
@@ -0,0 +1,120 @@
1
+ import { Schema } from "effect"
2
+ import { HttpApiEndpoint, HttpApiSchema, OpenApi } from "effect/http-api"
3
+ import { ConflictError, ForbiddenError, InvalidRequestError, MachineNotFoundError } from "../errors.js"
4
+
5
+ export const MACHINE_LINK_PATH = "/api/experimental/machine/link"
6
+
7
+ const EXPERIMENTAL = "Behind the machines flag. Experimental: may change without compatibility guarantees."
8
+
9
+ const annotations = (identifier: string, summary: string, description: string) =>
10
+ OpenApi.annotations({
11
+ identifier: `experimental.machine.${identifier}`,
12
+ summary,
13
+ description: `${description} ${EXPERIMENTAL}`,
14
+ transform: (operation) => ({ ...operation, tags: ["experimental"] }),
15
+ })
16
+
17
+ export const MachineInfo = Schema.Struct({
18
+ id: Schema.String,
19
+ online: Schema.Boolean,
20
+ paired: Schema.Boolean,
21
+ os: Schema.optionalKey(Schema.String),
22
+ arch: Schema.optionalKey(Schema.String),
23
+ connection: Schema.optionalKey(
24
+ Schema.Struct({
25
+ kind: Schema.Literals(["websocket", "iroh"]),
26
+ path: Schema.optionalKey(Schema.Literals(["direct", "relayed"])),
27
+ /** Round-trip time in milliseconds. */
28
+ rtt: Schema.optionalKey(Schema.Number),
29
+ }),
30
+ ),
31
+ }).annotate({ identifier: "Machine.Info" })
32
+ export type MachineInfo = typeof MachineInfo.Type
33
+
34
+ export const MachineReach = Schema.Struct({
35
+ type: Schema.Literal("url"),
36
+ url: Schema.String,
37
+ }).annotate({ identifier: "Machine.Reach" })
38
+ export type MachineReach = typeof MachineReach.Type
39
+
40
+ export const MachineAddPayload = Schema.Struct({
41
+ name: Schema.String,
42
+ reach: Schema.Array(MachineReach),
43
+ replace: Schema.optional(Schema.Boolean),
44
+ }).annotate({ identifier: "Machine.AddPayload" })
45
+ export type MachineAddPayload = typeof MachineAddPayload.Type
46
+
47
+ export const MachineInvite = Schema.Struct({
48
+ name: Schema.String,
49
+ join: Schema.String,
50
+ expires: Schema.Int,
51
+ reach: Schema.Array(Schema.Union([MachineReach, Schema.Struct({ type: Schema.Literal("iroh") })])),
52
+ }).annotate({ identifier: "Machine.Invite" })
53
+ export type MachineInvite = typeof MachineInvite.Type
54
+
55
+ /**
56
+ * Whether a request asks to become a WebSocket, the one request the machine link serves and the one the server lets in
57
+ * without its password: a GET with `Upgrade: websocket` and `upgrade` among its `Connection` tokens.
58
+ */
59
+ export function isWebSocketUpgrade(request: {
60
+ readonly method: string
61
+ readonly headers: Readonly<Record<string, string | undefined>>
62
+ }) {
63
+ return (
64
+ request.method === "GET" &&
65
+ request.headers.upgrade?.toLowerCase() === "websocket" &&
66
+ (request.headers.connection ?? "").split(",").some((token) => token.trim().toLowerCase() === "upgrade")
67
+ )
68
+ }
69
+
70
+ /**
71
+ * The same, for code that runs before the router has matched a route: the path is the request's own, up to its query,
72
+ * compared as it was sent. A URL parser would resolve `..` and a leading `//host` to this path, and the router would not.
73
+ */
74
+ export function isMachineLinkUpgrade(request: {
75
+ readonly method: string
76
+ readonly url: string
77
+ readonly headers: Readonly<Record<string, string | undefined>>
78
+ }) {
79
+ return request.url.split("?", 1)[0] === MACHINE_LINK_PATH && isWebSocketUpgrade(request)
80
+ }
81
+
82
+ /** Lives in the `server.experimental` group (see `groups/experimental.ts`). */
83
+ export const MachineLinkEndpoint = HttpApiEndpoint.get("machine.link", MACHINE_LINK_PATH, {
84
+ success: Schema.Boolean,
85
+ }).annotateMerge(
86
+ OpenApi.annotations({
87
+ identifier: "experimental.machine.link",
88
+ summary: "Connect a machine",
89
+ description:
90
+ "Upgrade to a WebSocket that carries a machine's link to this server: binary messages only, each at most 65,535 bytes. It takes no server password. The link's own handshake, which starts with the machine's first message, is the only way in: it admits a key this server has paired or a valid join string, and closes the socket on anything else without saying why. Behind the machines flag; without it the route does not exist. Experimental: may change without compatibility guarantees.",
91
+ transform: (operation) => ({ ...operation, "x-websocket": true, tags: ["experimental"] }),
92
+ }),
93
+ )
94
+
95
+ /** Lives in the `server.experimental` group (see `groups/experimental.ts`). */
96
+ export const MachineEndpoints = [
97
+ MachineLinkEndpoint,
98
+ HttpApiEndpoint.get("machine.list", "/api/experimental/machine", {
99
+ success: Schema.Struct({ data: Schema.Array(MachineInfo) }),
100
+ error: [ForbiddenError],
101
+ }).annotateMerge(annotations("list", "List machines", "List known machines and whether each is paired and online.")),
102
+ HttpApiEndpoint.post("machine.add", "/api/experimental/machine", {
103
+ payload: MachineAddPayload,
104
+ success: Schema.Struct({ data: MachineInvite }),
105
+ error: [InvalidRequestError, ForbiddenError, MachineNotFoundError, ConflictError],
106
+ }).annotateMerge(
107
+ annotations(
108
+ "add",
109
+ "Add or invite a machine",
110
+ "Add a machine by name if it does not exist, then create a single-use join string carrying the given reach addresses.",
111
+ ),
112
+ ),
113
+ HttpApiEndpoint.delete("machine.remove", "/api/experimental/machine/:name", {
114
+ params: { name: Schema.String },
115
+ success: HttpApiSchema.NoContent,
116
+ error: [ForbiddenError, MachineNotFoundError],
117
+ }).annotateMerge(
118
+ annotations("remove", "Remove a machine", "Forget a machine by name, closing any live link and revoking its key."),
119
+ ),
120
+ ] as const
@@ -0,0 +1,167 @@
1
+ import { Mcp } from "@zyro-sec/schema/mcp"
2
+ import { Location } from "@zyro-sec/schema/location"
3
+ import { PtyTicket } from "@zyro-sec/schema/pty-ticket"
4
+ import { Context, Schema } from "effect"
5
+ import { HttpApiEndpoint, HttpApiGroup, HttpApiMiddleware, HttpApiSchema, OpenApi } from "effect/http-api"
6
+ import { ForbiddenError, LocationNotFoundError, McpServerNotFoundError } from "../errors.js"
7
+ import { LocationQuery, locationQueryOpenApi } from "./location.js"
8
+ import { PTY_CONNECT_TICKET_QUERY, PTY_CONNECT_TOKEN_HEADER, PTY_CONNECT_TOKEN_HEADER_VALUE } from "./pty.js"
9
+
10
+ export const MCP_CLIENT_PATH = "/api/experimental/client-mcp"
11
+
12
+ export function hasMcpClientTicketURL(url: URL) {
13
+ return url.pathname === MCP_CLIENT_PATH && !!url.searchParams.get(PTY_CONNECT_TICKET_QUERY)
14
+ }
15
+
16
+ const McpClientQuery = Schema.Struct({
17
+ ...LocationQuery.fields,
18
+ name: Schema.String.check(Schema.isPattern(/^[a-zA-Z0-9_-]+$/)).annotateKey({
19
+ description: "Name of the MCP server the client hosts.",
20
+ }),
21
+ })
22
+
23
+ export const makeMcpGroup = <LocationId extends HttpApiMiddleware.AnyId, LocationService>(
24
+ locationMiddleware: Context.Key<LocationId, LocationService>,
25
+ ) =>
26
+ HttpApiGroup.make("server.mcp")
27
+ .add(
28
+ HttpApiEndpoint.get("mcp.list", "/api/mcp", {
29
+ query: LocationQuery,
30
+ success: Location.response(Schema.Array(Mcp.Server)),
31
+ })
32
+ .annotateMerge(locationQueryOpenApi)
33
+ .annotateMerge(
34
+ OpenApi.annotations({
35
+ identifier: "mcp.list",
36
+ summary: "List MCP servers",
37
+ description: "Retrieve configured MCP servers and their connection status.",
38
+ }),
39
+ ),
40
+ )
41
+ .add(
42
+ HttpApiEndpoint.put("mcp.add", "/api/experimental/mcp/:server", {
43
+ params: { server: Schema.String },
44
+ query: LocationQuery,
45
+ // Wrapped in a struct because the client codegen flattens payload fields and cannot
46
+ // represent a top-level union payload.
47
+ payload: Schema.Struct({ config: Mcp.ServerConfig }),
48
+ success: HttpApiSchema.NoContent,
49
+ })
50
+ .annotateMerge(locationQueryOpenApi)
51
+ .annotateMerge(
52
+ OpenApi.annotations({
53
+ identifier: "experimental.mcp.add",
54
+ summary: "Add MCP server",
55
+ description: "Add an MCP server at runtime or replace an existing one, connecting it immediately.",
56
+ }),
57
+ ),
58
+ )
59
+ .add(
60
+ HttpApiEndpoint.delete("mcp.remove", "/api/experimental/mcp/:server", {
61
+ params: { server: Schema.String },
62
+ query: LocationQuery,
63
+ success: HttpApiSchema.NoContent,
64
+ error: McpServerNotFoundError,
65
+ })
66
+ .annotateMerge(locationQueryOpenApi)
67
+ .annotateMerge(
68
+ OpenApi.annotations({
69
+ identifier: "experimental.mcp.remove",
70
+ summary: "Remove MCP server",
71
+ description: "Stop an MCP server and remove it from the runtime set until restart.",
72
+ }),
73
+ ),
74
+ )
75
+ .add(
76
+ HttpApiEndpoint.post("mcp.connect", "/api/experimental/mcp/:server/connect", {
77
+ params: { server: Schema.String },
78
+ query: LocationQuery,
79
+ success: HttpApiSchema.NoContent,
80
+ error: McpServerNotFoundError,
81
+ })
82
+ .annotateMerge(locationQueryOpenApi)
83
+ .annotateMerge(
84
+ OpenApi.annotations({
85
+ identifier: "experimental.mcp.connect",
86
+ summary: "Connect MCP server",
87
+ description: "Connect an MCP server at runtime, overriding a disabled configuration until restart.",
88
+ }),
89
+ ),
90
+ )
91
+ .add(
92
+ HttpApiEndpoint.post("mcp.disconnect", "/api/experimental/mcp/:server/disconnect", {
93
+ params: { server: Schema.String },
94
+ query: LocationQuery,
95
+ success: HttpApiSchema.NoContent,
96
+ error: McpServerNotFoundError,
97
+ })
98
+ .annotateMerge(locationQueryOpenApi)
99
+ .annotateMerge(
100
+ OpenApi.annotations({
101
+ identifier: "experimental.mcp.disconnect",
102
+ summary: "Disconnect MCP server",
103
+ description: "Disconnect an MCP server at runtime, removing its tools until reconnected.",
104
+ }),
105
+ ),
106
+ )
107
+ .add(
108
+ HttpApiEndpoint.get("mcp.resource.catalog", "/api/mcp/resource", {
109
+ query: LocationQuery,
110
+ success: Location.response(Mcp.ResourceCatalog),
111
+ })
112
+ .annotateMerge(locationQueryOpenApi)
113
+ .annotateMerge(
114
+ OpenApi.annotations({
115
+ identifier: "mcp.resource.catalog",
116
+ summary: "List MCP resources",
117
+ description: "Retrieve resources and resource templates from connected MCP servers.",
118
+ }),
119
+ ),
120
+ )
121
+ .add(
122
+ HttpApiEndpoint.post("mcp.clientToken", `${MCP_CLIENT_PATH}/token`, {
123
+ query: McpClientQuery,
124
+ headers: Schema.Struct({
125
+ [PTY_CONNECT_TOKEN_HEADER]: Schema.optional(Schema.String).annotateKey({
126
+ description: `Must be ${PTY_CONNECT_TOKEN_HEADER_VALUE}; requests without it are refused.`,
127
+ }),
128
+ }),
129
+ success: Location.response(PtyTicket.ConnectToken),
130
+ error: ForbiddenError,
131
+ })
132
+ .annotateMerge(locationQueryOpenApi)
133
+ .annotateMerge(
134
+ OpenApi.annotations({
135
+ identifier: "experimental.mcp.client.token",
136
+ summary: "Create client MCP WebSocket token",
137
+ description:
138
+ "Create a short-lived single-use ticket for opening a client MCP WebSocket connection from a browser.",
139
+ }),
140
+ ),
141
+ )
142
+ // The client handler checks origin and ticket before it boots the location itself.
143
+ .middleware(locationMiddleware)
144
+ .add(
145
+ HttpApiEndpoint.get("mcp.client", MCP_CLIENT_PATH, {
146
+ query: Schema.Struct({
147
+ ...McpClientQuery.fields,
148
+ [PTY_CONNECT_TICKET_QUERY]: Schema.optional(Schema.String).annotateKey({
149
+ description:
150
+ "Single-use ticket from experimental.mcp.client.token, which authorizes the connection without the usual credentials.",
151
+ }),
152
+ }),
153
+ success: Schema.Boolean,
154
+ error: [ForbiddenError, LocationNotFoundError],
155
+ })
156
+ .annotateMerge(locationQueryOpenApi)
157
+ .annotateMerge(
158
+ OpenApi.annotations({
159
+ identifier: "experimental.mcp.client",
160
+ summary: "Attach client MCP server",
161
+ description:
162
+ "Upgrade to a WebSocket over which the client hosts an MCP server named after `name`; its tools stay available while the socket is open. One JSON-RPC message per text frame. Experimental: may change without compatibility guarantees.",
163
+ transform: (operation) => ({ ...operation, "x-websocket": true }),
164
+ }),
165
+ ),
166
+ )
167
+ .annotateMerge(OpenApi.annotations({ title: "mcp", description: "MCP server and resource routes." }))
@@ -0,0 +1,23 @@
1
+ import { Schema } from "effect"
2
+ import { HttpApiEndpoint, HttpApiSchema, OpenApi } from "effect/http-api"
3
+ import { FileNotFoundError, InvalidRequestError } from "../errors.js"
4
+
5
+ export const MediaHash = Schema.String.check(Schema.isPattern(/^[0-9a-f]{64}$/u)).annotate({
6
+ identifier: "MediaHash",
7
+ })
8
+
9
+ /** Lives in the `server.experimental` group (see `groups/experimental.ts`). */
10
+ export const MediaGetEndpoint = HttpApiEndpoint.get("media.get", "/api/experimental/media/:hash", {
11
+ params: { hash: MediaHash },
12
+ success: Schema.Uint8Array.pipe(HttpApiSchema.asUint8Array()),
13
+ error: [FileNotFoundError, InvalidRequestError],
14
+ }).annotateMerge(
15
+ OpenApi.annotations({
16
+ identifier: "experimental.media.get",
17
+ summary: "Read media blob",
18
+ description:
19
+ "Read a content-addressed media blob by SHA-256 hash with immutable Cache-Control, ETag, and 304 Not Modified support. Only blobs a stored message or inbox item still references are served. Experimental: may change without compatibility guarantees.",
20
+ // The route shares the `server.experimental` group with the persistent PTY prototype; tag it on its own.
21
+ transform: (operation) => ({ ...operation, tags: ["experimental"] }),
22
+ }),
23
+ )