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

environmentHttp.ts

769 lines26.0 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​
587/**
588 * `compactTurnItems=1` opts into `turnItemsOmitLocalVisible`. Other values are
589 * ignored, and older servers ignore the whole query.
590 */
591const EnvironmentOrchestrationThreadBoundedSnapshotQuery = Schema.Struct({
592 compactTurnItems: Schema.optionalKey(Schema.String),
593});
594​
595const EnvironmentOrchestrationThreadHistoryQuery = Schema.Struct({
596 cursor: TrimmedNonEmptyString,
597 throughEntryId: Schema.optional(TrimmedNonEmptyString),
598 view: Schema.optional(Schema.Literals(["conversation", "activity"])),
599});
600​
601const EnvironmentOrchestrationThreadHistoryErrors = [
602 EnvironmentRequestInvalidError,
603 EnvironmentScopeRequiredError,
604 EnvironmentResourceNotFoundError,
605 EnvironmentInternalError,
606] as const;
607​
608class EnvironmentOrchestrationHttpApi extends HttpApiGroup.make("orchestration")
609 .add(
610 HttpApiEndpoint.get("shellSnapshot", "/api/orchestration/shell", {
611 headers: OrchestrationProtocolHeaders,
612 success: OrchestrationV2ShellSnapshot,
613 error: EnvironmentOrchestrationSnapshotErrors,
614 }).middleware(EnvironmentAuthenticatedAuth),
615 )
616 .add(
617 HttpApiEndpoint.get("threadSnapshot", "/api/orchestration/threads/:threadId", {
618 headers: OrchestrationProtocolHeaders,
619 params: EnvironmentOrchestrationThreadSnapshotParams,
620 success: OrchestrationV2ThreadDetailSnapshot,
621 error: EnvironmentOrchestrationThreadSnapshotErrors,
622 }).middleware(EnvironmentAuthenticatedAuth),
623 )
624 .add(
625 HttpApiEndpoint.get("threadBoundedSnapshot", "/api/orchestration/threads/:threadId/bounded", {
626 headers: OrchestrationProtocolHeaders,
627 params: EnvironmentOrchestrationThreadSnapshotParams,
628 query: EnvironmentOrchestrationThreadBoundedSnapshotQuery,
629 success: OrchestrationV2ThreadBoundedSnapshot,
630 error: EnvironmentOrchestrationThreadSnapshotErrors,
631 }).middleware(EnvironmentAuthenticatedAuth),
632 )
633 .add(
634 HttpApiEndpoint.get("threadHistoryPage", "/api/orchestration/threads/:threadId/history", {
635 headers: OrchestrationProtocolHeaders,
636 params: EnvironmentOrchestrationThreadSnapshotParams,
637 query: EnvironmentOrchestrationThreadHistoryQuery,
638 success: OrchestrationV2ThreadHistoryPage,
639 error: EnvironmentOrchestrationThreadHistoryErrors,
640 }).middleware(EnvironmentAuthenticatedAuth),
641 ) {}
642​
643class EnvironmentProjectsHttpApi extends HttpApiGroup.make("projects")
644 .add(
645 HttpApiEndpoint.get("snapshot", "/api/projects", {
646 headers: OptionalBearerHeaders,
647 success: ProjectSnapshot,
648 error: EnvironmentProjectSnapshotErrors,
649 }).middleware(EnvironmentAuthenticatedAuth),
650 )
651 .add(
652 HttpApiEndpoint.post("mutate", "/api/projects/mutate", {
653 headers: OptionalBearerHeaders,
654 payload: ProjectMutation,
655 success: Project,
656 error: EnvironmentProjectMutationErrors,
657 }).middleware(EnvironmentAuthenticatedAuth),
658 ) {}
659​
660/** Large, compressible pull-request payloads travel over HTTP rather than the RPC socket. */
661class EnvironmentPullRequestsHttpApi extends HttpApiGroup.make("pullRequests").add(
662 HttpApiEndpoint.post("diff", "/api/pull-requests/diff", {
663 headers: OptionalBearerHeaders,
664 payload: PullRequestDiffInput,
665 success: PullRequestDiffResult,
666 error: [
667 PullRequestUnavailableError,
668 PullRequestOperationError,
669 EnvironmentAuthInvalidError,
670 EnvironmentScopeRequiredError,
671 EnvironmentInternalError,
672 ],
673 }).middleware(EnvironmentAuthenticatedAuth),
674) {}
675​
676class EnvironmentConnectHttpApi extends HttpApiGroup.make("connect")
677 .add(
678 HttpApiEndpoint.post("linkProof", "/api/connect/link-proof", {
679 headers: OptionalBearerHeaders,
680 payload: RelayLinkProofRequest,
681 success: RelayEnvironmentLinkProof,
682 error: EnvironmentHttpCloudErrors,
683 }).middleware(EnvironmentAuthenticatedAuth),
684 )
685 .add(
686 HttpApiEndpoint.post("relayConfig", "/api/connect/relay-config", {
687 headers: OptionalBearerHeaders,
688 payload: RelayEnvironmentConfigRequest,
689 success: EnvironmentCloudRelayConfigResult,
690 error: [...EnvironmentHttpCloudErrors, EnvironmentCloudEndpointUnavailableError],
691 }).middleware(EnvironmentAuthenticatedAuth),
692 )
693 .add(
694 HttpApiEndpoint.get("linkState", "/api/connect/link-state", {
695 headers: OptionalBearerHeaders,
696 success: EnvironmentCloudLinkStateResult,
697 error: EnvironmentHttpCloudErrors,
698 }).middleware(EnvironmentAuthenticatedAuth),
699 )
700 .add(
701 HttpApiEndpoint.post("unlink", "/api/connect/unlink", {
702 headers: OptionalBearerHeaders,
703 success: EnvironmentCloudRelayConfigResult,
704 error: EnvironmentHttpCloudErrors,
705 }).middleware(EnvironmentAuthenticatedAuth),
706 )
707 .add(
708 HttpApiEndpoint.post("preferences", "/api/connect/preferences", {
709 headers: OptionalBearerHeaders,
710 payload: EnvironmentCloudPreferencesRequest,
711 success: EnvironmentCloudLinkStateResult,
712 error: EnvironmentHttpCloudErrors,
713 }).middleware(EnvironmentAuthenticatedAuth),
714 )
715 .add(
716 HttpApiEndpoint.post("health", "/api/t3-connect/health", {
717 payload: RelayCloudEnvironmentHealthRequest,
718 success: RelayEnvironmentHealthResponse,
719 error: EnvironmentHttpCloudErrors,
720 }),
721 )
722 .add(
723 HttpApiEndpoint.post("mintCredential", "/api/connect/mint-credential", {
724 payload: RelayCloudMintCredentialRequest,
725 success: RelayEnvironmentMintResponse,
726 error: EnvironmentHttpCloudErrors,
727 }),
728 )
729 .add(
730 HttpApiEndpoint.post("t3MintCredential", "/api/t3-connect/mint-credential", {
731 payload: RelayCloudMintCredentialRequest,
732 success: RelayEnvironmentMintResponse,
733 error: EnvironmentHttpCloudErrors,
734 }),
735 ) {}
736​
737/**
738 * Public entry point for webhook tasks. Unauthenticated by design: the token
739 * in the path, and an optional body signature, are the credential. The handler
740 * reads the raw body itself so a signature is checked over the exact bytes.
741 */
742const WebhookParams = Schema.Struct({
743 hookId: TrimmedNonEmptyString,
744 token: TrimmedNonEmptyString,
745});
746const WebhookAccepted = Schema.Struct({ deliveryId: TrimmedNonEmptyString }).pipe(
747 HttpApiSchema.status(202),
748);
749const webhookEndpoint = {
750 params: WebhookParams,
751 success: WebhookAccepted,
752} as const;
753const WEBHOOK_PATH = "/api/hooks/:hookId/:token";
754​
755class EnvironmentWebhooksHttpApi extends HttpApiGroup.make("webhooks")
756 .add(HttpApiEndpoint.post("webhookPost", WEBHOOK_PATH, webhookEndpoint))
757 .add(HttpApiEndpoint.put("webhookPut", WEBHOOK_PATH, webhookEndpoint))
758 .add(HttpApiEndpoint.patch("webhookPatch", WEBHOOK_PATH, webhookEndpoint))
759 .add(HttpApiEndpoint.get("webhookGet", WEBHOOK_PATH, webhookEndpoint)) {}
760​
761export class EnvironmentHttpApi extends HttpApi.make("environment")
762 .add(EnvironmentMetadataHttpApi)
763 .add(EnvironmentAuthHttpApi)
764 .add(EnvironmentMcpOAuthHttpApi)
765 .add(EnvironmentOrchestrationHttpApi)
766 .add(EnvironmentPullRequestsHttpApi)
767 .add(EnvironmentProjectsHttpApi)
768 .add(EnvironmentConnectHttpApi)
769 .add(EnvironmentWebhooksHttpApi) {}