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

environmentHttp.ts

773 lines26.3 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 // The relay rejected this link's credential, usually because the environment
425 // was deregistered from T3 Connect. The link stays stored until it is linked
426 // again. Optional so newer clients tolerate older environment servers.
427 linkRevoked: Schema.optional(Schema.Boolean),
428});
429export type EnvironmentCloudLinkStateResult = typeof EnvironmentCloudLinkStateResult.Type;
430​
431export const EnvironmentCloudPreferencesRequest = Schema.Struct({
432 publishAgentActivity: Schema.Boolean,
433 // Omit to leave the current value unchanged.
434 holdWebhooksWhileOffline: Schema.optional(Schema.Boolean),
435});
436export type EnvironmentCloudPreferencesRequest = typeof EnvironmentCloudPreferencesRequest.Type;
437​
438export const AuthPairingLinkRevokeResult = Schema.Struct({
439 revoked: Schema.Boolean,
440});
441export type AuthPairingLinkRevokeResult = typeof AuthPairingLinkRevokeResult.Type;
442​
443export const AuthClientSessionRevokeResult = Schema.Struct({
444 revoked: Schema.Boolean,
445});
446export type AuthClientSessionRevokeResult = typeof AuthClientSessionRevokeResult.Type;
447​
448export const AuthOtherClientSessionsRevokeResult = Schema.Struct({
449 revokedCount: Schema.Number,
450});
451export type AuthOtherClientSessionsRevokeResult = typeof AuthOtherClientSessionsRevokeResult.Type;
452​
453class EnvironmentMetadataHttpApi extends HttpApiGroup.make("metadata").add(
454 HttpApiEndpoint.get("descriptor", "/.well-known/t3/environment", {
455 success: ExecutionEnvironmentDescriptor,
456 }),
457) {}
458​
459class EnvironmentAuthHttpApi extends HttpApiGroup.make("auth")
460 .add(
461 HttpApiEndpoint.get("session", "/api/auth/session", {
462 headers: OptionalBearerHeaders,
463 success: AuthSessionState,
464 error: [EnvironmentInternalError],
465 }),
466 )
467 .add(
468 HttpApiEndpoint.post("browserSession", "/api/auth/browser-session", {
469 payload: AuthBrowserSessionRequest,
470 success: AuthBrowserSessionResult,
471 error: EnvironmentSessionCreationErrors,
472 }),
473 )
474 .add(
475 HttpApiEndpoint.post("token", "/oauth/token", {
476 headers: OptionalDpopProofHeaders,
477 payload: AuthTokenExchangeRequest,
478 success: AuthAccessTokenResult,
479 error: EnvironmentTokenExchangeErrors,
480 }),
481 )
482 .add(
483 HttpApiEndpoint.post("webSocketTicket", "/api/auth/websocket-ticket", {
484 headers: OptionalBearerHeaders,
485 success: AuthWebSocketTicketResult,
486 error: [EnvironmentInternalError],
487 }).middleware(EnvironmentAuthenticatedAuth),
488 )
489 .add(
490 HttpApiEndpoint.post("pairingCredential", "/api/auth/pairing-token", {
491 headers: OptionalBearerHeaders,
492 payload: AuthCreatePairingCredentialInput,
493 success: AuthPairingCredentialResult,
494 error: EnvironmentPairingCredentialErrors,
495 }).middleware(EnvironmentAuthenticatedAuth),
496 )
497 .add(
498 HttpApiEndpoint.get("pairingLinks", "/api/auth/pairing-links", {
499 headers: OptionalBearerHeaders,
500 success: Schema.Array(AuthPairingLink),
501 error: EnvironmentScopedOperationErrors,
502 }).middleware(EnvironmentAuthenticatedAuth),
503 )
504 .add(
505 HttpApiEndpoint.post("revokePairingLink", "/api/auth/pairing-links/revoke", {
506 headers: OptionalBearerHeaders,
507 payload: AuthRevokePairingLinkInput,
508 success: AuthPairingLinkRevokeResult,
509 error: EnvironmentScopedOperationErrors,
510 }).middleware(EnvironmentAuthenticatedAuth),
511 )
512 .add(
513 HttpApiEndpoint.get("clients", "/api/auth/clients", {
514 headers: OptionalBearerHeaders,
515 success: Schema.Array(AuthClientSession),
516 error: EnvironmentScopedOperationErrors,
517 }).middleware(EnvironmentAuthenticatedAuth),
518 )
519 .add(
520 HttpApiEndpoint.post("revokeClient", "/api/auth/clients/revoke", {
521 headers: OptionalBearerHeaders,
522 payload: AuthRevokeClientSessionInput,
523 success: AuthClientSessionRevokeResult,
524 error: EnvironmentSessionRevokeErrors,
525 }).middleware(EnvironmentAuthenticatedAuth),
526 )
527 .add(
528 HttpApiEndpoint.post("revokeOtherClients", "/api/auth/clients/revoke-others", {
529 headers: OptionalBearerHeaders,
530 success: AuthOtherClientSessionsRevokeResult,
531 error: EnvironmentScopedOperationErrors,
532 }).middleware(EnvironmentAuthenticatedAuth),
533 ) {}
534​
535/**
536 * The OAuth authorization server outside agents use to sign in to `/mcp`.
537 * `authorize` is where the agent sends the browser: it answers a redirect to
538 * the web app's approval page, or a plain error page for a request that names
539 * an unverified client or redirect, so the response is not a schema.
540 */
541class EnvironmentMcpOAuthHttpApi extends HttpApiGroup.make("mcpOAuth")
542 .add(
543 HttpApiEndpoint.get("protectedResource", "/.well-known/oauth-protected-resource", {
544 success: AuthMcpProtectedResourceMetadata,
545 }),
546 )
547 .add(
548 HttpApiEndpoint.get("mcpProtectedResource", "/.well-known/oauth-protected-resource/mcp", {
549 success: AuthMcpProtectedResourceMetadata,
550 }),
551 )
552 .add(
553 HttpApiEndpoint.get("authorizationServer", "/.well-known/oauth-authorization-server", {
554 success: AuthMcpAuthorizationServerMetadata,
555 }),
556 )
557 .add(
558 HttpApiEndpoint.post("register", "/oauth/mcp/register", {
559 payload: AuthMcpClientRegistration,
560 success: AuthMcpRegisteredClient,
561 error: AuthMcpRegistrationError,
562 }),
563 )
564 .add(HttpApiEndpoint.get("authorize", "/oauth/mcp/authorize"))
565 .add(
566 HttpApiEndpoint.post("approval", "/oauth/mcp/approval", {
567 payload: AuthMcpAuthorizationRequest,
568 success: [AuthMcpApprovalDetails, AuthMcpApprovalRedirect],
569 error: AuthMcpApprovalError,
570 }),
571 )
572 .add(
573 HttpApiEndpoint.post("decision", "/oauth/mcp/decision", {
574 payload: AuthMcpApprovalDecisionRequest,
575 success: AuthMcpApprovalRedirect,
576 error: AuthMcpApprovalError,
577 }),
578 )
579 .add(
580 HttpApiEndpoint.post("token", "/oauth/mcp/token", {
581 payload: AuthMcpTokenRequest,
582 success: AuthMcpTokenResult,
583 error: AuthMcpTokenError,
584 }),
585 ) {}
586​
587const EnvironmentOrchestrationThreadSnapshotParams = Schema.Struct({
588 threadId: ThreadId,
589});
590​
591/**
592 * `compactTurnItems=1` opts into `turnItemsOmitLocalVisible`. Other values are
593 * ignored, and older servers ignore the whole query.
594 */
595const EnvironmentOrchestrationThreadBoundedSnapshotQuery = Schema.Struct({
596 compactTurnItems: Schema.optionalKey(Schema.String),
597});
598​
599const EnvironmentOrchestrationThreadHistoryQuery = Schema.Struct({
600 cursor: TrimmedNonEmptyString,
601 throughEntryId: Schema.optional(TrimmedNonEmptyString),
602 view: Schema.optional(Schema.Literals(["conversation", "activity"])),
603});
604​
605const EnvironmentOrchestrationThreadHistoryErrors = [
606 EnvironmentRequestInvalidError,
607 EnvironmentScopeRequiredError,
608 EnvironmentResourceNotFoundError,
609 EnvironmentInternalError,
610] as const;
611​
612class EnvironmentOrchestrationHttpApi extends HttpApiGroup.make("orchestration")
613 .add(
614 HttpApiEndpoint.get("shellSnapshot", "/api/orchestration/shell", {
615 headers: OrchestrationProtocolHeaders,
616 success: OrchestrationV2ShellSnapshot,
617 error: EnvironmentOrchestrationSnapshotErrors,
618 }).middleware(EnvironmentAuthenticatedAuth),
619 )
620 .add(
621 HttpApiEndpoint.get("threadSnapshot", "/api/orchestration/threads/:threadId", {
622 headers: OrchestrationProtocolHeaders,
623 params: EnvironmentOrchestrationThreadSnapshotParams,
624 success: OrchestrationV2ThreadDetailSnapshot,
625 error: EnvironmentOrchestrationThreadSnapshotErrors,
626 }).middleware(EnvironmentAuthenticatedAuth),
627 )
628 .add(
629 HttpApiEndpoint.get("threadBoundedSnapshot", "/api/orchestration/threads/:threadId/bounded", {
630 headers: OrchestrationProtocolHeaders,
631 params: EnvironmentOrchestrationThreadSnapshotParams,
632 query: EnvironmentOrchestrationThreadBoundedSnapshotQuery,
633 success: OrchestrationV2ThreadBoundedSnapshot,
634 error: EnvironmentOrchestrationThreadSnapshotErrors,
635 }).middleware(EnvironmentAuthenticatedAuth),
636 )
637 .add(
638 HttpApiEndpoint.get("threadHistoryPage", "/api/orchestration/threads/:threadId/history", {
639 headers: OrchestrationProtocolHeaders,
640 params: EnvironmentOrchestrationThreadSnapshotParams,
641 query: EnvironmentOrchestrationThreadHistoryQuery,
642 success: OrchestrationV2ThreadHistoryPage,
643 error: EnvironmentOrchestrationThreadHistoryErrors,
644 }).middleware(EnvironmentAuthenticatedAuth),
645 ) {}
646​
647class EnvironmentProjectsHttpApi extends HttpApiGroup.make("projects")
648 .add(
649 HttpApiEndpoint.get("snapshot", "/api/projects", {
650 headers: OptionalBearerHeaders,
651 success: ProjectSnapshot,
652 error: EnvironmentProjectSnapshotErrors,
653 }).middleware(EnvironmentAuthenticatedAuth),
654 )
655 .add(
656 HttpApiEndpoint.post("mutate", "/api/projects/mutate", {
657 headers: OptionalBearerHeaders,
658 payload: ProjectMutation,
659 success: Project,
660 error: EnvironmentProjectMutationErrors,
661 }).middleware(EnvironmentAuthenticatedAuth),
662 ) {}
663​
664/** Large, compressible pull-request payloads travel over HTTP rather than the RPC socket. */
665class EnvironmentPullRequestsHttpApi extends HttpApiGroup.make("pullRequests").add(
666 HttpApiEndpoint.post("diff", "/api/pull-requests/diff", {
667 headers: OptionalBearerHeaders,
668 payload: PullRequestDiffInput,
669 success: PullRequestDiffResult,
670 error: [
671 PullRequestUnavailableError,
672 PullRequestOperationError,
673 EnvironmentAuthInvalidError,
674 EnvironmentScopeRequiredError,
675 EnvironmentInternalError,
676 ],
677 }).middleware(EnvironmentAuthenticatedAuth),
678) {}
679​
680class EnvironmentConnectHttpApi extends HttpApiGroup.make("connect")
681 .add(
682 HttpApiEndpoint.post("linkProof", "/api/connect/link-proof", {
683 headers: OptionalBearerHeaders,
684 payload: RelayLinkProofRequest,
685 success: RelayEnvironmentLinkProof,
686 error: EnvironmentHttpCloudErrors,
687 }).middleware(EnvironmentAuthenticatedAuth),
688 )
689 .add(
690 HttpApiEndpoint.post("relayConfig", "/api/connect/relay-config", {
691 headers: OptionalBearerHeaders,
692 payload: RelayEnvironmentConfigRequest,
693 success: EnvironmentCloudRelayConfigResult,
694 error: [...EnvironmentHttpCloudErrors, EnvironmentCloudEndpointUnavailableError],
695 }).middleware(EnvironmentAuthenticatedAuth),
696 )
697 .add(
698 HttpApiEndpoint.get("linkState", "/api/connect/link-state", {
699 headers: OptionalBearerHeaders,
700 success: EnvironmentCloudLinkStateResult,
701 error: EnvironmentHttpCloudErrors,
702 }).middleware(EnvironmentAuthenticatedAuth),
703 )
704 .add(
705 HttpApiEndpoint.post("unlink", "/api/connect/unlink", {
706 headers: OptionalBearerHeaders,
707 success: EnvironmentCloudRelayConfigResult,
708 error: EnvironmentHttpCloudErrors,
709 }).middleware(EnvironmentAuthenticatedAuth),
710 )
711 .add(
712 HttpApiEndpoint.post("preferences", "/api/connect/preferences", {
713 headers: OptionalBearerHeaders,
714 payload: EnvironmentCloudPreferencesRequest,
715 success: EnvironmentCloudLinkStateResult,
716 error: EnvironmentHttpCloudErrors,
717 }).middleware(EnvironmentAuthenticatedAuth),
718 )
719 .add(
720 HttpApiEndpoint.post("health", "/api/t3-connect/health", {
721 payload: RelayCloudEnvironmentHealthRequest,
722 success: RelayEnvironmentHealthResponse,
723 error: EnvironmentHttpCloudErrors,
724 }),
725 )
726 .add(
727 HttpApiEndpoint.post("mintCredential", "/api/connect/mint-credential", {
728 payload: RelayCloudMintCredentialRequest,
729 success: RelayEnvironmentMintResponse,
730 error: EnvironmentHttpCloudErrors,
731 }),
732 )
733 .add(
734 HttpApiEndpoint.post("t3MintCredential", "/api/t3-connect/mint-credential", {
735 payload: RelayCloudMintCredentialRequest,
736 success: RelayEnvironmentMintResponse,
737 error: EnvironmentHttpCloudErrors,
738 }),
739 ) {}
740​
741/**
742 * Public entry point for webhook tasks. Unauthenticated by design: the token
743 * in the path, and an optional body signature, are the credential. The handler
744 * reads the raw body itself so a signature is checked over the exact bytes.
745 */
746const WebhookParams = Schema.Struct({
747 hookId: TrimmedNonEmptyString,
748 token: TrimmedNonEmptyString,
749});
750const WebhookAccepted = Schema.Struct({ deliveryId: TrimmedNonEmptyString }).pipe(
751 HttpApiSchema.status(202),
752);
753const webhookEndpoint = {
754 params: WebhookParams,
755 success: WebhookAccepted,
756} as const;
757const WEBHOOK_PATH = "/api/hooks/:hookId/:token";
758​
759class EnvironmentWebhooksHttpApi extends HttpApiGroup.make("webhooks")
760 .add(HttpApiEndpoint.post("webhookPost", WEBHOOK_PATH, webhookEndpoint))
761 .add(HttpApiEndpoint.put("webhookPut", WEBHOOK_PATH, webhookEndpoint))
762 .add(HttpApiEndpoint.patch("webhookPatch", WEBHOOK_PATH, webhookEndpoint))
763 .add(HttpApiEndpoint.get("webhookGet", WEBHOOK_PATH, webhookEndpoint)) {}
764​
765export class EnvironmentHttpApi extends HttpApi.make("environment")
766 .add(EnvironmentMetadataHttpApi)
767 .add(EnvironmentAuthHttpApi)
768 .add(EnvironmentMcpOAuthHttpApi)
769 .add(EnvironmentOrchestrationHttpApi)
770 .add(EnvironmentPullRequestsHttpApi)
771 .add(EnvironmentProjectsHttpApi)
772 .add(EnvironmentConnectHttpApi)
773 .add(EnvironmentWebhooksHttpApi) {}