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

environmentHttp.ts

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