Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

environmentHttp.ts

758 lines25.6 KB

1import * as Context from "effect/Context";
2import type * as DateTime from "effect/DateTime";
3import * as Schema from "effect/Schema";
4import * as HttpApi from "effect/http-api/HttpApi";
5import * as HttpApiEndpoint from "effect/http-api/HttpApiEndpoint";
6import * as HttpApiGroup from "effect/http-api/HttpApiGroup";
7import * as HttpApiMiddleware from "effect/http-api/HttpApiMiddleware";
8import * as HttpApiSchema from "effect/http-api/HttpApiSchema";
9import * as HttpServerRespondable from "effect/http/HttpServerRespondable";
10import * as HttpServerResponse from "effect/http/HttpServerResponse";
11​
12import {
13 AuthAccessTokenResult,
14 AuthBrowserSessionRequest,
15 AuthBrowserSessionResult,
16 AuthClientSession,
17 AuthCreatePairingCredentialInput,
18 AuthMcpApprovalDecisionRequest,
19 AuthMcpApprovalDetails,
20 AuthMcpApprovalError,
21 AuthMcpApprovalRedirect,
22 AuthMcpAuthorizationRequest,
23 AuthMcpAuthorizationServerMetadata,
24 AuthMcpClientRegistration,
25 AuthMcpProtectedResourceMetadata,
26 AuthMcpRegisteredClient,
27 AuthMcpRegistrationError,
28 AuthMcpTokenError,
29 AuthMcpTokenRequest,
30 AuthMcpTokenResult,
31 AuthPairingCredentialResult,
32 AuthPairingLink,
33 AuthRevokeClientSessionInput,
34 AuthRevokePairingLinkInput,
35 AuthEnvironmentScope,
36 AuthTokenExchangeRequest,
37 AuthSessionState,
38 AuthWebSocketTicketResult,
39 ServerAuthSessionMethod,
40} from "./auth.ts";
41import {
42 ExecutionEnvironmentDescriptor,
43 ORCHESTRATION_PROTOCOL_HEADER,
44 ORCHESTRATION_PROTOCOL_VERSION_TEXT,
45} from "./environment.ts";
46import {
47 DpopFailureReason,
48 AuthSessionId,
49 ThreadId,
50 TrimmedNonEmptyString,
51} from "./baseSchemas.ts";
52import {
53 OrchestrationV2ShellSnapshot,
54 OrchestrationV2ThreadBoundedSnapshot,
55 OrchestrationV2ThreadDetailSnapshot,
56 OrchestrationV2ThreadHistoryPage,
57} from "./orchestrationV2.ts";
58import { Project, ProjectMutation, ProjectSnapshot } from "./project.ts";
59import {
60 PullRequestDiffInput,
61 PullRequestDiffResult,
62 PullRequestOperationError,
63 PullRequestUnavailableError,
64} from "./pullRequest.ts";
65import {
66 RelayCloudEnvironmentHealthRequest,
67 RelayCloudMintCredentialRequest,
68 RelayEnvironmentConfigRequest,
69 RelayEnvironmentHealthResponse,
70 RelayEnvironmentLinkProof,
71 RelayEnvironmentMintResponse,
72 RelayLinkProofRequest,
73} from "./relay.ts";
74​
75const OptionalBearerHeaders = Schema.Struct({
76 authorization: Schema.optionalKey(Schema.String),
77 dpop: Schema.optionalKey(Schema.String),
78});
79​
80const OrchestrationProtocolHeaders = Schema.Struct({
81 authorization: Schema.optionalKey(Schema.String),
82 dpop: Schema.optionalKey(Schema.String),
83 [ORCHESTRATION_PROTOCOL_HEADER]: Schema.Literal(ORCHESTRATION_PROTOCOL_VERSION_TEXT),
84});
85​
86const OptionalDpopProofHeaders = Schema.Struct({
87 dpop: Schema.optionalKey(Schema.String),
88});
89​
90export const EnvironmentRequestInvalidReason = Schema.Literals([
91 "invalid_scope",
92 "scope_not_granted",
93 "invalid_command",
94 "invalid_history_cursor",
95]);
96export type EnvironmentRequestInvalidReason = typeof EnvironmentRequestInvalidReason.Type;
97​
98export const EnvironmentAuthInvalidReason = Schema.Literals([
99 "missing_credential",
100 "invalid_credential",
101]);
102export type EnvironmentAuthInvalidReason = typeof EnvironmentAuthInvalidReason.Type;
103​
104export const EnvironmentOperationForbiddenReason = Schema.Literals([
105 "current_session_revoke_not_allowed",
106]);
107export type EnvironmentOperationForbiddenReason = typeof EnvironmentOperationForbiddenReason.Type;
108​
109export const EnvironmentInternalErrorReason = Schema.Literals([
110 "bootstrap_validation_failed",
111 "browser_session_issuance_failed",
112 "browser_session_cookie_failed",
113 "access_token_issuance_failed",
114 "websocket_ticket_issuance_failed",
115 "pairing_credential_issuance_failed",
116 "pairing_links_load_failed",
117 "pairing_link_revoke_failed",
118 "client_sessions_load_failed",
119 "client_session_revoke_failed",
120 "project_snapshot_failed",
121 "project_mutation_failed",
122 "orchestration_snapshot_failed",
123 "orchestration_thread_snapshot_failed",
124 "orchestration_thread_bounded_snapshot_failed",
125 "orchestration_thread_history_failed",
126 "internal_error",
127]);
128export type EnvironmentInternalErrorReason = typeof EnvironmentInternalErrorReason.Type;
129​
130export class EnvironmentRequestInvalidError extends Schema.TaggedError<EnvironmentRequestInvalidError>()(
131 "EnvironmentRequestInvalidError",
132 {
133 code: Schema.Literal("invalid_request"),
134 reason: EnvironmentRequestInvalidReason,
135 traceId: TrimmedNonEmptyString,
136 },
137 { httpApiStatus: 400 },
138) {
139 [HttpServerRespondable.symbol]() {
140 return HttpServerResponse.schemaJson(EnvironmentRequestInvalidError)(this, { status: 400 });
141 }
142​
143 override get message(): string {
144 return `The environment rejected the request (${this.reason}).`;
145 }
147​
148export class EnvironmentAuthInvalidError extends Schema.TaggedError<EnvironmentAuthInvalidError>()(
149 "EnvironmentAuthInvalidError",
150 {
151 code: Schema.Literal("auth_invalid"),
152 reason: EnvironmentAuthInvalidReason,
153 // Older servers do not send a DPoP failure category.
154 dpopFailureReason: Schema.optionalKey(DpopFailureReason),
155 traceId: TrimmedNonEmptyString,
156 },
157 { httpApiStatus: 401 },
158) {
159 [HttpServerRespondable.symbol]() {
160 return HttpServerResponse.schemaJson(EnvironmentAuthInvalidError)(this, { status: 401 });
161 }
162​
163 override get message(): string {
164 return `The environment rejected this client's credentials (${this.reason}).`;
165 }
167​
168export class EnvironmentScopeRequiredError extends Schema.TaggedError<EnvironmentScopeRequiredError>()(
169 "EnvironmentScopeRequiredError",
170 {
171 code: Schema.Literal("insufficient_scope"),
172 requiredScope: AuthEnvironmentScope,
173 requiredPermission: Schema.optionalKey(Schema.String),
174 traceId: TrimmedNonEmptyString,
175 },
176 { httpApiStatus: 403 },
177) {
178 [HttpServerRespondable.symbol]() {
179 return HttpServerResponse.schemaJson(EnvironmentScopeRequiredError)(this, { status: 403 });
180 }
181​
182 override get message(): string {
183 return `This request needs the ${this.requiredPermission ?? this.requiredScope} scope, which this client does not have.`;
184 }
186​
187export class EnvironmentOperationForbiddenError extends Schema.TaggedError<EnvironmentOperationForbiddenError>()(
188 "EnvironmentOperationForbiddenError",
189 {
190 code: Schema.Literal("operation_forbidden"),
191 reason: EnvironmentOperationForbiddenReason,
192 traceId: TrimmedNonEmptyString,
193 },
194 { httpApiStatus: 403 },
195) {
196 [HttpServerRespondable.symbol]() {
197 return HttpServerResponse.schemaJson(EnvironmentOperationForbiddenError)(this, { status: 403 });
198 }
199​
200 override get message(): string {
201 return `The environment refused this operation (${this.reason}).`;
202 }
204​
205export class EnvironmentInternalError extends Schema.TaggedError<EnvironmentInternalError>()(
206 "EnvironmentInternalError",
207 {
208 code: Schema.Literal("internal_error"),
209 reason: EnvironmentInternalErrorReason,
210 traceId: TrimmedNonEmptyString,
211 },
212 { httpApiStatus: 500 },
213) {
214 [HttpServerRespondable.symbol]() {
215 return HttpServerResponse.schemaJson(EnvironmentInternalError)(this, { status: 500 });
216 }
217​
218 override get message(): string {
219 return `The environment failed to answer this request (${this.reason}).`;
220 }
222​
223export const EnvironmentResourceNotFoundReason = Schema.Literals(["thread_not_found"]);
224export type EnvironmentResourceNotFoundReason = typeof EnvironmentResourceNotFoundReason.Type;
225​
226export class EnvironmentResourceNotFoundError extends Schema.TaggedError<EnvironmentResourceNotFoundError>()(
227 "EnvironmentResourceNotFoundError",
228 {
229 code: Schema.Literal("not_found"),
230 reason: EnvironmentResourceNotFoundReason,
231 traceId: TrimmedNonEmptyString,
232 },
233 { httpApiStatus: 404 },
234) {
235 [HttpServerRespondable.symbol]() {
236 return HttpServerResponse.schemaJson(EnvironmentResourceNotFoundError)(this, { status: 404 });
237 }
238​
239 override get message(): string {
240 return `The environment could not find what this request named (${this.reason}).`;
241 }
243​
244export const EnvironmentHttpCommonError = Schema.Union([
245 EnvironmentRequestInvalidError,
246 EnvironmentAuthInvalidError,
247 EnvironmentScopeRequiredError,
248 EnvironmentOperationForbiddenError,
249 EnvironmentResourceNotFoundError,
250 EnvironmentInternalError,
251]);
252export type EnvironmentHttpCommonError = typeof EnvironmentHttpCommonError.Type;
253​
254const EnvironmentAuthenticationErrors = [
255 EnvironmentAuthInvalidError,
256 EnvironmentInternalError,
257] as const;
258​
259export class EnvironmentHttpBadRequestError extends Schema.TaggedError<EnvironmentHttpBadRequestError>()(
260 "EnvironmentHttpBadRequestError",
261 {
262 message: Schema.String,
263 },
264 { httpApiStatus: 400 },
265) {
266 [HttpServerRespondable.symbol]() {
267 return HttpServerResponse.schemaJson(EnvironmentHttpBadRequestError)(this, { status: 400 });
268 }
270​
271export class EnvironmentHttpUnauthorizedError extends Schema.TaggedError<EnvironmentHttpUnauthorizedError>()(
272 "EnvironmentHttpUnauthorizedError",
273 {
274 message: Schema.String,
275 },
276 { httpApiStatus: 401 },
277) {
278 [HttpServerRespondable.symbol]() {
279 return HttpServerResponse.schemaJson(EnvironmentHttpUnauthorizedError)(this, { status: 401 });
280 }
282​
283export class EnvironmentHttpForbiddenError extends Schema.TaggedError<EnvironmentHttpForbiddenError>()(
284 "EnvironmentHttpForbiddenError",
285 {
286 message: Schema.String,
287 },
288 { httpApiStatus: 403 },
289) {
290 [HttpServerRespondable.symbol]() {
291 return HttpServerResponse.schemaJson(EnvironmentHttpForbiddenError)(this, { status: 403 });
292 }
294​
295export class EnvironmentHttpInternalServerError extends Schema.TaggedError<EnvironmentHttpInternalServerError>()(
296 "EnvironmentHttpInternalServerError",
297 {
298 message: Schema.String,
299 },
300 { httpApiStatus: 500 },
301) {
302 [HttpServerRespondable.symbol]() {
303 return HttpServerResponse.schemaJson(EnvironmentHttpInternalServerError)(this, { status: 500 });
304 }
306​
307export class EnvironmentHttpConflictError extends Schema.TaggedError<EnvironmentHttpConflictError>()(
308 "EnvironmentHttpConflictError",
309 {
310 message: Schema.String,
311 },
312 { httpApiStatus: 409 },
313) {
314 [HttpServerRespondable.symbol]() {
315 return HttpServerResponse.schemaJson(EnvironmentHttpConflictError)(this, { status: 409 });
316 }
318​
319export class EnvironmentCloudEndpointUnavailableError extends Schema.TaggedError<EnvironmentCloudEndpointUnavailableError>()(
320 "EnvironmentCloudEndpointUnavailableError",
321 {
322 message: Schema.String,
323 endpointRuntimeStatus: Schema.Unknown,
324 },
325 { httpApiStatus: 503 },
326) {
327 [HttpServerRespondable.symbol]() {
328 return HttpServerResponse.schemaJson(EnvironmentCloudEndpointUnavailableError)(this, {
329 status: 503,
330 });
331 }
333const EnvironmentSessionCreationErrors = [
334 EnvironmentAuthInvalidError,
335 EnvironmentInternalError,
336] as const;
337const EnvironmentTokenExchangeErrors = [
338 EnvironmentRequestInvalidError,
339 EnvironmentAuthInvalidError,
340 EnvironmentInternalError,
341] as const;
342const EnvironmentScopedOperationErrors = [
343 EnvironmentScopeRequiredError,
344 EnvironmentInternalError,
345] as const;
346const EnvironmentPairingCredentialErrors = [
347 EnvironmentRequestInvalidError,
348 ...EnvironmentScopedOperationErrors,
349] as const;
350const EnvironmentSessionRevokeErrors = [
351 EnvironmentScopeRequiredError,
352 EnvironmentOperationForbiddenError,
353 EnvironmentInternalError,
354] as const;
355const EnvironmentProjectSnapshotErrors = [
356 EnvironmentScopeRequiredError,
357 EnvironmentInternalError,
358] as const;
359const EnvironmentOrchestrationSnapshotErrors = [
360 EnvironmentScopeRequiredError,
361 EnvironmentInternalError,
362] as const;
363const EnvironmentOrchestrationThreadSnapshotErrors = [
364 EnvironmentScopeRequiredError,
365 EnvironmentResourceNotFoundError,
366 EnvironmentInternalError,
367] as const;
368const EnvironmentProjectMutationErrors = [
369 EnvironmentRequestInvalidError,
370 EnvironmentScopeRequiredError,
371 EnvironmentInternalError,
372] as const;
373​
374export interface EnvironmentSessionPrincipalShape {
375 readonly sessionId: AuthSessionId;
376 readonly subject: string;
377 readonly method: ServerAuthSessionMethod;
378 readonly scopes: ReadonlySet<AuthEnvironmentScope>;
379 readonly proofKeyThumbprint?: string;
380 readonly expiresAt?: DateTime.DateTime;
382​
383export class EnvironmentAuthenticatedPrincipal extends Context.Service<
384 EnvironmentAuthenticatedPrincipal,
385 EnvironmentSessionPrincipalShape
386>()("@t3tools/contracts/environmentHttp/EnvironmentAuthenticatedPrincipal") {}
387​
388export class EnvironmentAuthenticatedAuth extends HttpApiMiddleware.Service<
389 EnvironmentAuthenticatedAuth,
390 { provides: EnvironmentAuthenticatedPrincipal }
391>()("EnvironmentAuthenticatedAuth", {
392 error: EnvironmentAuthenticationErrors,
393}) {}
394​
395const EnvironmentHttpCloudErrors = [
396 EnvironmentHttpBadRequestError,
397 EnvironmentHttpUnauthorizedError,
398 EnvironmentHttpForbiddenError,
399 EnvironmentHttpConflictError,
400 EnvironmentHttpInternalServerError,
401 EnvironmentScopeRequiredError,
402] as const;
403​
404export const EnvironmentCloudRelayConfigResult = Schema.Struct({
405 ok: Schema.Boolean,
406 endpointRuntimeStatus: Schema.Unknown,
407});
408export type EnvironmentCloudRelayConfigResult = typeof EnvironmentCloudRelayConfigResult.Type;
409​
410export const EnvironmentCloudLinkStateResult = Schema.Struct({
411 linked: Schema.Boolean,
412 cloudUserId: Schema.NullOr(Schema.String),
413 relayUrl: Schema.NullOr(Schema.String),
414 relayIssuer: Schema.NullOr(Schema.String),
415 // A managed Cloudflare tunnel is provisioned for this link. False for a
416 // publish-only link (activity publishing without a relay-managed tunnel), so
417 // clients can present the two capabilities as independent settings.
418 // Optional so newer clients tolerate older environment servers.
419 managedTunnelActive: Schema.optional(Schema.Boolean),
420 publishAgentActivity: Schema.Boolean,
421 // Opt-in: T3 Connect holds webhook requests while this environment is
422 // offline. Optional so newer clients tolerate older environment servers.
423 holdWebhooksWhileOffline: Schema.optional(Schema.Boolean),
424});
425export type EnvironmentCloudLinkStateResult = typeof EnvironmentCloudLinkStateResult.Type;
426​
427export const EnvironmentCloudPreferencesRequest = Schema.Struct({
428 publishAgentActivity: Schema.Boolean,
429 // Omit to leave the current value unchanged.
430 holdWebhooksWhileOffline: Schema.optional(Schema.Boolean),
431});
432export type EnvironmentCloudPreferencesRequest = typeof EnvironmentCloudPreferencesRequest.Type;
433​
434export const AuthPairingLinkRevokeResult = Schema.Struct({
435 revoked: Schema.Boolean,
436});
437export type AuthPairingLinkRevokeResult = typeof AuthPairingLinkRevokeResult.Type;
438​
439export const AuthClientSessionRevokeResult = Schema.Struct({
440 revoked: Schema.Boolean,
441});
442export type AuthClientSessionRevokeResult = typeof AuthClientSessionRevokeResult.Type;
443​
444export const AuthOtherClientSessionsRevokeResult = Schema.Struct({
445 revokedCount: Schema.Number,
446});
447export type AuthOtherClientSessionsRevokeResult = typeof AuthOtherClientSessionsRevokeResult.Type;
448​
449class EnvironmentMetadataHttpApi extends HttpApiGroup.make("metadata").add(
450 HttpApiEndpoint.get("descriptor", "/.well-known/t3/environment", {
451 success: ExecutionEnvironmentDescriptor,
452 }),
453) {}
454​
455class EnvironmentAuthHttpApi extends HttpApiGroup.make("auth")
456 .add(
457 HttpApiEndpoint.get("session", "/api/auth/session", {
458 headers: OptionalBearerHeaders,
459 success: AuthSessionState,
460 error: [EnvironmentInternalError],
461 }),
462 )
463 .add(
464 HttpApiEndpoint.post("browserSession", "/api/auth/browser-session", {
465 payload: AuthBrowserSessionRequest,
466 success: AuthBrowserSessionResult,
467 error: EnvironmentSessionCreationErrors,
468 }),
469 )
470 .add(
471 HttpApiEndpoint.post("token", "/oauth/token", {
472 headers: OptionalDpopProofHeaders,
473 payload: AuthTokenExchangeRequest,
474 success: AuthAccessTokenResult,
475 error: EnvironmentTokenExchangeErrors,
476 }),
477 )
478 .add(
479 HttpApiEndpoint.post("webSocketTicket", "/api/auth/websocket-ticket", {
480 headers: OptionalBearerHeaders,
481 success: AuthWebSocketTicketResult,
482 error: [EnvironmentInternalError],
483 }).middleware(EnvironmentAuthenticatedAuth),
484 )
485 .add(
486 HttpApiEndpoint.post("pairingCredential", "/api/auth/pairing-token", {
487 headers: OptionalBearerHeaders,
488 payload: AuthCreatePairingCredentialInput,
489 success: AuthPairingCredentialResult,
490 error: EnvironmentPairingCredentialErrors,
491 }).middleware(EnvironmentAuthenticatedAuth),
492 )
493 .add(
494 HttpApiEndpoint.get("pairingLinks", "/api/auth/pairing-links", {
495 headers: OptionalBearerHeaders,
496 success: Schema.Array(AuthPairingLink),
497 error: EnvironmentScopedOperationErrors,
498 }).middleware(EnvironmentAuthenticatedAuth),
499 )
500 .add(
501 HttpApiEndpoint.post("revokePairingLink", "/api/auth/pairing-links/revoke", {
502 headers: OptionalBearerHeaders,
503 payload: AuthRevokePairingLinkInput,
504 success: AuthPairingLinkRevokeResult,
505 error: EnvironmentScopedOperationErrors,
506 }).middleware(EnvironmentAuthenticatedAuth),
507 )
508 .add(
509 HttpApiEndpoint.get("clients", "/api/auth/clients", {
510 headers: OptionalBearerHeaders,
511 success: Schema.Array(AuthClientSession),
512 error: EnvironmentScopedOperationErrors,
513 }).middleware(EnvironmentAuthenticatedAuth),
514 )
515 .add(
516 HttpApiEndpoint.post("revokeClient", "/api/auth/clients/revoke", {
517 headers: OptionalBearerHeaders,
518 payload: AuthRevokeClientSessionInput,
519 success: AuthClientSessionRevokeResult,
520 error: EnvironmentSessionRevokeErrors,
521 }).middleware(EnvironmentAuthenticatedAuth),
522 )
523 .add(
524 HttpApiEndpoint.post("revokeOtherClients", "/api/auth/clients/revoke-others", {
525 headers: OptionalBearerHeaders,
526 success: AuthOtherClientSessionsRevokeResult,
527 error: EnvironmentScopedOperationErrors,
528 }).middleware(EnvironmentAuthenticatedAuth),
529 ) {}
530​
531/**
532 * The OAuth authorization server outside agents use to sign in to `/mcp`.
533 * `authorize` is where the agent sends the browser: it answers a redirect to
534 * the web app's approval page, or a plain error page for a request that names
535 * an unverified client or redirect, so the response is not a schema.
536 */
537class EnvironmentMcpOAuthHttpApi extends HttpApiGroup.make("mcpOAuth")
538 .add(
539 HttpApiEndpoint.get("protectedResource", "/.well-known/oauth-protected-resource", {
540 success: AuthMcpProtectedResourceMetadata,
541 }),
542 )
543 .add(
544 HttpApiEndpoint.get("mcpProtectedResource", "/.well-known/oauth-protected-resource/mcp", {
545 success: AuthMcpProtectedResourceMetadata,
546 }),
547 )
548 .add(
549 HttpApiEndpoint.get("authorizationServer", "/.well-known/oauth-authorization-server", {
550 success: AuthMcpAuthorizationServerMetadata,
551 }),
552 )
553 .add(
554 HttpApiEndpoint.post("register", "/oauth/mcp/register", {
555 payload: AuthMcpClientRegistration,
556 success: AuthMcpRegisteredClient,
557 error: AuthMcpRegistrationError,
558 }),
559 )
560 .add(HttpApiEndpoint.get("authorize", "/oauth/mcp/authorize"))
561 .add(
562 HttpApiEndpoint.post("approval", "/oauth/mcp/approval", {
563 payload: AuthMcpAuthorizationRequest,
564 success: [AuthMcpApprovalDetails, AuthMcpApprovalRedirect],
565 error: AuthMcpApprovalError,
566 }),
567 )
568 .add(
569 HttpApiEndpoint.post("decision", "/oauth/mcp/decision", {
570 payload: AuthMcpApprovalDecisionRequest,
571 success: AuthMcpApprovalRedirect,
572 error: AuthMcpApprovalError,
573 }),
574 )
575 .add(
576 HttpApiEndpoint.post("token", "/oauth/mcp/token", {
577 payload: AuthMcpTokenRequest,
578 success: AuthMcpTokenResult,
579 error: AuthMcpTokenError,
580 }),
581 ) {}
582​
583const EnvironmentOrchestrationThreadSnapshotParams = Schema.Struct({
584 threadId: ThreadId,
585});
586​
587const EnvironmentOrchestrationThreadHistoryQuery = Schema.Struct({
588 cursor: TrimmedNonEmptyString,
589});
590​
591const EnvironmentOrchestrationThreadHistoryErrors = [
592 EnvironmentRequestInvalidError,
593 EnvironmentScopeRequiredError,
594 EnvironmentResourceNotFoundError,
595 EnvironmentInternalError,
596] as const;
597​
598class EnvironmentOrchestrationHttpApi extends HttpApiGroup.make("orchestration")
599 .add(
600 HttpApiEndpoint.get("shellSnapshot", "/api/orchestration/shell", {
601 headers: OrchestrationProtocolHeaders,
602 success: OrchestrationV2ShellSnapshot,
603 error: EnvironmentOrchestrationSnapshotErrors,
604 }).middleware(EnvironmentAuthenticatedAuth),
605 )
606 .add(
607 HttpApiEndpoint.get("threadSnapshot", "/api/orchestration/threads/:threadId", {
608 headers: OrchestrationProtocolHeaders,
609 params: EnvironmentOrchestrationThreadSnapshotParams,
610 success: OrchestrationV2ThreadDetailSnapshot,
611 error: EnvironmentOrchestrationThreadSnapshotErrors,
612 }).middleware(EnvironmentAuthenticatedAuth),
613 )
614 .add(
615 HttpApiEndpoint.get("threadBoundedSnapshot", "/api/orchestration/threads/:threadId/bounded", {
616 headers: OrchestrationProtocolHeaders,
617 params: EnvironmentOrchestrationThreadSnapshotParams,
618 success: OrchestrationV2ThreadBoundedSnapshot,
619 error: EnvironmentOrchestrationThreadSnapshotErrors,
620 }).middleware(EnvironmentAuthenticatedAuth),
621 )
622 .add(
623 HttpApiEndpoint.get("threadHistoryPage", "/api/orchestration/threads/:threadId/history", {
624 headers: OrchestrationProtocolHeaders,
625 params: EnvironmentOrchestrationThreadSnapshotParams,
626 query: EnvironmentOrchestrationThreadHistoryQuery,
627 success: OrchestrationV2ThreadHistoryPage,
628 error: EnvironmentOrchestrationThreadHistoryErrors,
629 }).middleware(EnvironmentAuthenticatedAuth),
630 ) {}
631​
632class EnvironmentProjectsHttpApi extends HttpApiGroup.make("projects")
633 .add(
634 HttpApiEndpoint.get("snapshot", "/api/projects", {
635 headers: OptionalBearerHeaders,
636 success: ProjectSnapshot,
637 error: EnvironmentProjectSnapshotErrors,
638 }).middleware(EnvironmentAuthenticatedAuth),
639 )
640 .add(
641 HttpApiEndpoint.post("mutate", "/api/projects/mutate", {
642 headers: OptionalBearerHeaders,
643 payload: ProjectMutation,
644 success: Project,
645 error: EnvironmentProjectMutationErrors,
646 }).middleware(EnvironmentAuthenticatedAuth),
647 ) {}
648​
649/** Large, compressible pull-request payloads travel over HTTP rather than the RPC socket. */
650class EnvironmentPullRequestsHttpApi extends HttpApiGroup.make("pullRequests").add(
651 HttpApiEndpoint.post("diff", "/api/pull-requests/diff", {
652 headers: OptionalBearerHeaders,
653 payload: PullRequestDiffInput,
654 success: PullRequestDiffResult,
655 error: [
656 PullRequestUnavailableError,
657 PullRequestOperationError,
658 EnvironmentAuthInvalidError,
659 EnvironmentScopeRequiredError,
660 EnvironmentInternalError,
661 ],
662 }).middleware(EnvironmentAuthenticatedAuth),
663) {}
664​
665class EnvironmentConnectHttpApi extends HttpApiGroup.make("connect")
666 .add(
667 HttpApiEndpoint.post("linkProof", "/api/connect/link-proof", {
668 headers: OptionalBearerHeaders,
669 payload: RelayLinkProofRequest,
670 success: RelayEnvironmentLinkProof,
671 error: EnvironmentHttpCloudErrors,
672 }).middleware(EnvironmentAuthenticatedAuth),
673 )
674 .add(
675 HttpApiEndpoint.post("relayConfig", "/api/connect/relay-config", {
676 headers: OptionalBearerHeaders,
677 payload: RelayEnvironmentConfigRequest,
678 success: EnvironmentCloudRelayConfigResult,
679 error: [...EnvironmentHttpCloudErrors, EnvironmentCloudEndpointUnavailableError],
680 }).middleware(EnvironmentAuthenticatedAuth),
681 )
682 .add(
683 HttpApiEndpoint.get("linkState", "/api/connect/link-state", {
684 headers: OptionalBearerHeaders,
685 success: EnvironmentCloudLinkStateResult,
686 error: EnvironmentHttpCloudErrors,
687 }).middleware(EnvironmentAuthenticatedAuth),
688 )
689 .add(
690 HttpApiEndpoint.post("unlink", "/api/connect/unlink", {
691 headers: OptionalBearerHeaders,
692 success: EnvironmentCloudRelayConfigResult,
693 error: EnvironmentHttpCloudErrors,
694 }).middleware(EnvironmentAuthenticatedAuth),
695 )
696 .add(
697 HttpApiEndpoint.post("preferences", "/api/connect/preferences", {
698 headers: OptionalBearerHeaders,
699 payload: EnvironmentCloudPreferencesRequest,
700 success: EnvironmentCloudLinkStateResult,
701 error: EnvironmentHttpCloudErrors,
702 }).middleware(EnvironmentAuthenticatedAuth),
703 )
704 .add(
705 HttpApiEndpoint.post("health", "/api/t3-connect/health", {
706 payload: RelayCloudEnvironmentHealthRequest,
707 success: RelayEnvironmentHealthResponse,
708 error: EnvironmentHttpCloudErrors,
709 }),
710 )
711 .add(
712 HttpApiEndpoint.post("mintCredential", "/api/connect/mint-credential", {
713 payload: RelayCloudMintCredentialRequest,
714 success: RelayEnvironmentMintResponse,
715 error: EnvironmentHttpCloudErrors,
716 }),
717 )
718 .add(
719 HttpApiEndpoint.post("t3MintCredential", "/api/t3-connect/mint-credential", {
720 payload: RelayCloudMintCredentialRequest,
721 success: RelayEnvironmentMintResponse,
722 error: EnvironmentHttpCloudErrors,
723 }),
724 ) {}
725​
726/**
727 * Public entry point for webhook tasks. Unauthenticated by design: the token
728 * in the path, and an optional body signature, are the credential. The handler
729 * reads the raw body itself so a signature is checked over the exact bytes.
730 */
731const WebhookParams = Schema.Struct({
732 hookId: TrimmedNonEmptyString,
733 token: TrimmedNonEmptyString,
734});
735const WebhookAccepted = Schema.Struct({ deliveryId: TrimmedNonEmptyString }).pipe(
736 HttpApiSchema.status(202),
737);
738const webhookEndpoint = {
739 params: WebhookParams,
740 success: WebhookAccepted,
741} as const;
742const WEBHOOK_PATH = "/api/hooks/:hookId/:token";
743​
744class EnvironmentWebhooksHttpApi extends HttpApiGroup.make("webhooks")
745 .add(HttpApiEndpoint.post("webhookPost", WEBHOOK_PATH, webhookEndpoint))
746 .add(HttpApiEndpoint.put("webhookPut", WEBHOOK_PATH, webhookEndpoint))
747 .add(HttpApiEndpoint.patch("webhookPatch", WEBHOOK_PATH, webhookEndpoint))
748 .add(HttpApiEndpoint.get("webhookGet", WEBHOOK_PATH, webhookEndpoint)) {}
749​
750export class EnvironmentHttpApi extends HttpApi.make("environment")
751 .add(EnvironmentMetadataHttpApi)
752 .add(EnvironmentAuthHttpApi)
753 .add(EnvironmentMcpOAuthHttpApi)
754 .add(EnvironmentOrchestrationHttpApi)
755 .add(EnvironmentPullRequestsHttpApi)
756 .add(EnvironmentProjectsHttpApi)
757 .add(EnvironmentConnectHttpApi)
758 .add(EnvironmentWebhooksHttpApi) {}