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

environmentHttp.ts

957 lines33.4 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 AuthCreatePairingCredentialInput,
17 AuthMcpApprovalDecisionRequest,
18 AuthMcpApprovalDetails,
19 AuthMcpApprovalError,
20 AuthMcpApprovalRedirect,
21 AuthMcpAuthorizationRequest,
22 AuthMcpAuthorizationServerMetadata,
23 AuthMcpClientRegistration,
24 AuthMcpProtectedResourceMetadata,
25 AuthMcpRegisteredClient,
26 AuthMcpRegistrationError,
27 AuthMcpTokenError,
28 AuthMcpTokenRequest,
29 AuthMcpTokenResult,
30 AuthPairingCredentialResult,
31 AuthRevokeClientSessionInput,
32 AuthRevokePairingLinkInput,
33 AuthEnvironmentScope,
34 AuthTokenExchangeRequest,
35 AuthSessionState,
36 AuthWebSocketTicketParams,
37 AuthWebSocketTicketResult,
38 ServerAuthSessionMethod,
39} from "./auth.ts";
40import {
41 ExecutionEnvironmentDescriptor,
42 ORCHESTRATION_PROTOCOL_HEADER,
43 ORCHESTRATION_PROTOCOL_VERSION_TEXT,
44} from "./environment.ts";
45import {
46 DpopFailureReason,
47 AuthSessionId,
48 ThreadId,
49 TrimmedNonEmptyString,
50} from "./baseSchemas.ts";
51import {
52 EnvironmentSpeechAccelerationRequest,
53 EnvironmentSpeechModelRequest,
54 EnvironmentSpeechModels,
55 EnvironmentSpeechModelUnloadTimeoutRequest,
56 EnvironmentSpeechPostProcessingRequest,
57 EnvironmentSpeechPostProcessingResult,
58 EnvironmentSpeechStatus,
59 EnvironmentSpeechTranscriptionResult,
60} from "./speech.ts";
61import {
62 OrchestrationV2ShellSnapshot,
63 OrchestrationV2ThreadBoundedSnapshot,
64 OrchestrationV2ThreadDetailSnapshot,
65 OrchestrationV2ThreadHistoryPage,
66 OrchestrationV2ThreadTranscript,
67} from "./orchestrationV2.ts";
68import { Project, ProjectMutation, ProjectSnapshot } from "./project.ts";
69import {
70 PullRequestDiffInput,
71 PullRequestDiffResult,
72 PullRequestOperationError,
73 PullRequestUnavailableError,
74} from "./pullRequest.ts";
75import {
76 RelayCloudEnvironmentHealthRequest,
77 RelayCloudMintCredentialRequest,
78 RelayEnvironmentConfigRequest,
79 RelayEnvironmentHealthResponse,
80 RelayEnvironmentLinkProof,
81 RelayEnvironmentMintResponse,
82 RelayLinkProofRequest,
83} from "./relay.ts";
84​
85const OptionalBearerHeaders = Schema.Struct({
86 authorization: Schema.optionalKey(Schema.String),
87 dpop: Schema.optionalKey(Schema.String),
88});
89​
90const OrchestrationProtocolHeaders = Schema.Struct({
91 authorization: Schema.optionalKey(Schema.String),
92 dpop: Schema.optionalKey(Schema.String),
93 [ORCHESTRATION_PROTOCOL_HEADER]: Schema.Literal(ORCHESTRATION_PROTOCOL_VERSION_TEXT),
94});
95​
96const OptionalDpopProofHeaders = Schema.Struct({
97 dpop: Schema.optionalKey(Schema.String),
98});
99​
100export const EnvironmentRequestInvalidReason = Schema.Literals([
101 "invalid_scope",
102 "scope_not_granted",
103 "invalid_command",
104 "invalid_history_cursor",
105 "thread_transcript_too_large",
106 "invalid_audio",
107 "speech_unavailable",
108 "speech_busy",
109]);
110export type EnvironmentRequestInvalidReason = typeof EnvironmentRequestInvalidReason.Type;
111​
112export const EnvironmentAuthInvalidReason = Schema.Literals([
113 "missing_credential",
114 "invalid_credential",
115]);
116export type EnvironmentAuthInvalidReason = typeof EnvironmentAuthInvalidReason.Type;
117​
118export const EnvironmentOperationForbiddenReason = Schema.Literals([
119 "current_session_revoke_not_allowed",
120]);
121export type EnvironmentOperationForbiddenReason = typeof EnvironmentOperationForbiddenReason.Type;
122​
123export const EnvironmentInternalErrorReason = Schema.Literals([
124 "bootstrap_validation_failed",
125 "browser_session_issuance_failed",
126 "browser_session_cookie_failed",
127 "access_token_issuance_failed",
128 "websocket_ticket_issuance_failed",
129 "pairing_credential_issuance_failed",
130 "pairing_links_load_failed",
131 "pairing_link_revoke_failed",
132 "client_sessions_load_failed",
133 "client_session_revoke_failed",
134 "project_snapshot_failed",
135 "project_mutation_failed",
136 "orchestration_snapshot_failed",
137 "orchestration_thread_snapshot_failed",
138 "orchestration_thread_bounded_snapshot_failed",
139 "orchestration_thread_history_failed",
140 "internal_error",
141]);
142export type EnvironmentInternalErrorReason = typeof EnvironmentInternalErrorReason.Type;
143​
144export class EnvironmentRequestInvalidError extends Schema.TaggedError<EnvironmentRequestInvalidError>()(
145 "EnvironmentRequestInvalidError",
146 {
147 code: Schema.Literal("invalid_request"),
148 reason: EnvironmentRequestInvalidReason,
149 traceId: TrimmedNonEmptyString,
150 },
151 { httpApiStatus: 400 },
152) {
153 [HttpServerRespondable.symbol]() {
154 return HttpServerResponse.schemaJson(EnvironmentRequestInvalidError)(this, { status: 400 });
155 }
156​
157 override get message(): string {
158 return `The environment rejected the request (${this.reason}).`;
159 }
161​
162export class EnvironmentAuthInvalidError extends Schema.TaggedError<EnvironmentAuthInvalidError>()(
163 "EnvironmentAuthInvalidError",
164 {
165 code: Schema.Literal("auth_invalid"),
166 reason: EnvironmentAuthInvalidReason,
167 dpopFailureReason: Schema.optionalKey(DpopFailureReason),
168 traceId: TrimmedNonEmptyString,
169 },
170 { httpApiStatus: 401 },
171) {
172 [HttpServerRespondable.symbol]() {
173 return HttpServerResponse.schemaJson(EnvironmentAuthInvalidError)(this, { status: 401 });
174 }
175​
176 override get message(): string {
177 return `The environment rejected this client's credentials (${this.reason}).`;
178 }
180​
181export class EnvironmentScopeRequiredError extends Schema.TaggedError<EnvironmentScopeRequiredError>()(
182 "EnvironmentScopeRequiredError",
183 {
184 code: Schema.Literal("insufficient_scope"),
185 requiredScope: AuthEnvironmentScope,
186 requiredPermission: Schema.optionalKey(Schema.String),
187 traceId: TrimmedNonEmptyString,
188 },
189 { httpApiStatus: 403 },
190) {
191 [HttpServerRespondable.symbol]() {
192 return HttpServerResponse.schemaJson(EnvironmentScopeRequiredError)(this, { status: 403 });
193 }
194​
195 override get message(): string {
196 return `This request needs the ${this.requiredPermission ?? this.requiredScope} scope, which this client does not have.`;
197 }
199​
200export class EnvironmentOperationForbiddenError extends Schema.TaggedError<EnvironmentOperationForbiddenError>()(
201 "EnvironmentOperationForbiddenError",
202 {
203 code: Schema.Literal("operation_forbidden"),
204 reason: EnvironmentOperationForbiddenReason,
205 traceId: TrimmedNonEmptyString,
206 },
207 { httpApiStatus: 403 },
208) {
209 [HttpServerRespondable.symbol]() {
210 return HttpServerResponse.schemaJson(EnvironmentOperationForbiddenError)(this, { status: 403 });
211 }
212​
213 override get message(): string {
214 return `The environment refused this operation (${this.reason}).`;
215 }
217​
218export class EnvironmentInternalError extends Schema.TaggedError<EnvironmentInternalError>()(
219 "EnvironmentInternalError",
220 {
221 code: Schema.Literal("internal_error"),
222 reason: EnvironmentInternalErrorReason,
223 traceId: TrimmedNonEmptyString,
224 },
225 { httpApiStatus: 500 },
226) {
227 [HttpServerRespondable.symbol]() {
228 return HttpServerResponse.schemaJson(EnvironmentInternalError)(this, { status: 500 });
229 }
230​
231 override get message(): string {
232 return `The environment failed to answer this request (${this.reason}).`;
233 }
235​
236export const EnvironmentResourceNotFoundReason = Schema.Literals(["thread_not_found"]);
237export type EnvironmentResourceNotFoundReason = typeof EnvironmentResourceNotFoundReason.Type;
238​
239export class EnvironmentResourceNotFoundError extends Schema.TaggedError<EnvironmentResourceNotFoundError>()(
240 "EnvironmentResourceNotFoundError",
241 {
242 code: Schema.Literal("not_found"),
243 reason: EnvironmentResourceNotFoundReason,
244 traceId: TrimmedNonEmptyString,
245 },
246 { httpApiStatus: 404 },
247) {
248 [HttpServerRespondable.symbol]() {
249 return HttpServerResponse.schemaJson(EnvironmentResourceNotFoundError)(this, { status: 404 });
250 }
251​
252 override get message(): string {
253 return `The environment could not find what this request named (${this.reason}).`;
254 }
256​
257export const EnvironmentHttpCommonError = Schema.Union([
258 EnvironmentRequestInvalidError,
259 EnvironmentAuthInvalidError,
260 EnvironmentScopeRequiredError,
261 EnvironmentOperationForbiddenError,
262 EnvironmentResourceNotFoundError,
263 EnvironmentInternalError,
264]);
265export type EnvironmentHttpCommonError = typeof EnvironmentHttpCommonError.Type;
266​
267const EnvironmentAuthenticationErrors = [
268 EnvironmentAuthInvalidError,
269 EnvironmentInternalError,
270] as const;
271​
272export class EnvironmentHttpBadRequestError extends Schema.TaggedError<EnvironmentHttpBadRequestError>()(
273 "EnvironmentHttpBadRequestError",
274 {
275 message: Schema.String,
276 },
277 { httpApiStatus: 400 },
278) {
279 [HttpServerRespondable.symbol]() {
280 return HttpServerResponse.schemaJson(EnvironmentHttpBadRequestError)(this, { status: 400 });
281 }
283​
284export class EnvironmentHttpUnauthorizedError extends Schema.TaggedError<EnvironmentHttpUnauthorizedError>()(
285 "EnvironmentHttpUnauthorizedError",
286 {
287 message: Schema.String,
288 },
289 { httpApiStatus: 401 },
290) {
291 [HttpServerRespondable.symbol]() {
292 return HttpServerResponse.schemaJson(EnvironmentHttpUnauthorizedError)(this, { status: 401 });
293 }
295​
296export class EnvironmentHttpForbiddenError extends Schema.TaggedError<EnvironmentHttpForbiddenError>()(
297 "EnvironmentHttpForbiddenError",
298 {
299 message: Schema.String,
300 },
301 { httpApiStatus: 403 },
302) {
303 [HttpServerRespondable.symbol]() {
304 return HttpServerResponse.schemaJson(EnvironmentHttpForbiddenError)(this, { status: 403 });
305 }
307​
308export class EnvironmentHttpInternalServerError extends Schema.TaggedError<EnvironmentHttpInternalServerError>()(
309 "EnvironmentHttpInternalServerError",
310 {
311 message: Schema.String,
312 },
313 { httpApiStatus: 500 },
314) {
315 [HttpServerRespondable.symbol]() {
316 return HttpServerResponse.schemaJson(EnvironmentHttpInternalServerError)(this, { status: 500 });
317 }
319​
320export class EnvironmentHttpConflictError extends Schema.TaggedError<EnvironmentHttpConflictError>()(
321 "EnvironmentHttpConflictError",
322 {
323 message: Schema.String,
324 },
325 { httpApiStatus: 409 },
326) {
327 [HttpServerRespondable.symbol]() {
328 return HttpServerResponse.schemaJson(EnvironmentHttpConflictError)(this, { status: 409 });
329 }
331​
332export class EnvironmentCloudEndpointUnavailableError extends Schema.TaggedError<EnvironmentCloudEndpointUnavailableError>()(
333 "EnvironmentCloudEndpointUnavailableError",
334 {
335 message: Schema.String,
336 endpointRuntimeStatus: Schema.Unknown,
337 },
338 { httpApiStatus: 503 },
339) {
340 [HttpServerRespondable.symbol]() {
341 return HttpServerResponse.schemaJson(EnvironmentCloudEndpointUnavailableError)(this, {
342 status: 503,
343 });
344 }
346const EnvironmentSessionCreationErrors = [
347 EnvironmentAuthInvalidError,
348 EnvironmentInternalError,
349] as const;
350const EnvironmentTokenExchangeErrors = [
351 EnvironmentRequestInvalidError,
352 EnvironmentAuthInvalidError,
353 EnvironmentInternalError,
354] as const;
355const EnvironmentScopedOperationErrors = [
356 EnvironmentScopeRequiredError,
357 EnvironmentInternalError,
358] as const;
359const EnvironmentPairingCredentialErrors = [
360 EnvironmentRequestInvalidError,
361 // The managed policy does not allow remote clients.
362 EnvironmentHttpForbiddenError,
363 ...EnvironmentScopedOperationErrors,
364] as const;
365const EnvironmentSessionRevokeErrors = [
366 EnvironmentScopeRequiredError,
367 EnvironmentOperationForbiddenError,
368 EnvironmentInternalError,
369] as const;
370const EnvironmentProjectSnapshotErrors = [
371 EnvironmentScopeRequiredError,
372 EnvironmentInternalError,
373] as const;
374const EnvironmentOrchestrationSnapshotErrors = [
375 EnvironmentScopeRequiredError,
376 EnvironmentInternalError,
377] as const;
378const EnvironmentOrchestrationThreadSnapshotErrors = [
379 EnvironmentScopeRequiredError,
380 EnvironmentResourceNotFoundError,
381 EnvironmentInternalError,
382] as const;
383const EnvironmentProjectMutationErrors = [
384 EnvironmentRequestInvalidError,
385 EnvironmentScopeRequiredError,
386 EnvironmentInternalError,
387] as const;
388​
389export interface EnvironmentSessionPrincipalShape {
390 readonly sessionId: AuthSessionId;
391 readonly subject: string;
392 readonly method: ServerAuthSessionMethod;
393 readonly scopes: ReadonlySet<AuthEnvironmentScope>;
394 readonly proofKeyThumbprint?: string;
395 readonly expiresAt?: DateTime.DateTime;
397​
398export class EnvironmentAuthenticatedPrincipal extends Context.Service<
399 EnvironmentAuthenticatedPrincipal,
400 EnvironmentSessionPrincipalShape
401>()("@t3tools/contracts/environmentHttp/EnvironmentAuthenticatedPrincipal") {}
402​
403export class EnvironmentAuthenticatedAuth extends HttpApiMiddleware.Service<
404 EnvironmentAuthenticatedAuth,
405 { provides: EnvironmentAuthenticatedPrincipal }
406>()("EnvironmentAuthenticatedAuth", {
407 error: EnvironmentAuthenticationErrors,
408}) {}
409​
410const EnvironmentHttpCloudErrors = [
411 EnvironmentHttpBadRequestError,
412 EnvironmentHttpUnauthorizedError,
413 EnvironmentHttpForbiddenError,
414 EnvironmentHttpConflictError,
415 EnvironmentHttpInternalServerError,
416 EnvironmentScopeRequiredError,
417] as const;
418​
419export const EnvironmentCloudRelayConfigResult = Schema.Struct({
420 ok: Schema.Boolean,
421 endpointRuntimeStatus: Schema.Unknown,
422});
423export type EnvironmentCloudRelayConfigResult = typeof EnvironmentCloudRelayConfigResult.Type;
424​
425export const EnvironmentConnectReachabilityCause = Schema.Literals([
426 "not_linked",
427 "connector_not_running",
428 "connector_not_ready",
429 "edge_unreachable",
430 "no_connector",
431 "origin_unreachable",
432 "dns_failed",
433 "timeout",
434 "unexpected_response",
435]);
436export type EnvironmentConnectReachabilityCause = typeof EnvironmentConnectReachabilityCause.Type;
437​
438/** Whether other devices can reach this environment through its T3 Connect tunnel. */
439export const EnvironmentConnectReachability = Schema.Union([
440 Schema.Struct({
441 status: Schema.Literal("reachable"),
442 checkedAt: Schema.String,
443 /** Null when cloudflared did not report a count. */
444 readyConnections: Schema.NullOr(Schema.Int),
445 protocol: Schema.NullOr(Schema.String),
446 }),
447 Schema.Struct({
448 status: Schema.Literal("unreachable"),
449 checkedAt: Schema.String,
450 cause: EnvironmentConnectReachabilityCause,
451 reason: Schema.String,
452 hint: Schema.NullOr(Schema.String),
453 fix: Schema.String,
454 }),
455]);
456export type EnvironmentConnectReachability = typeof EnvironmentConnectReachability.Type;
457​
458/** "Tunnel connected · 4 connections · QUIC" for a healthy check. */
459export function formatConnectReachable(
460 result: Extract<EnvironmentConnectReachability, { status: "reachable" }>,
461): string {
462 const count = result.readyConnections;
463 return [
464 "Tunnel connected",
465 ...(count === null ? [] : [`${count} connection${count === 1 ? "" : "s"}`]),
466 ...(result.protocol ? [result.protocol.toUpperCase()] : []),
467 ].join(" · ");
469​
470/**
471 * Sections of docs/user/t3-connect-troubleshooting.md. Each is the GitHub anchor of a
472 * heading there; the test fails when a heading is renamed without updating this list.
473 */
474export const T3_CONNECT_TROUBLESHOOTING_SECTIONS = [
475 "the-hosts-tunnel-is-offline",
476 "port-7844-is-blocked-on-the-host",
477 "the-tunnel-works-but-t3-code-does-not-answer",
478 "the-t3-connect-address-does-not-resolve-or-answer",
479 "this-device-cant-reach-t3-connect",
480 "sign-in-account-or-link-problems",
481 "the-clock-is-off",
482 "the-host-runs-an-older-t3-code",
483 "t3-connect-returned-an-error",
484] as const;
485export type T3ConnectTroubleshootingSection = (typeof T3_CONNECT_TROUBLESHOOTING_SECTIONS)[number];
486​
487/** Clients, the CLI, and server logs link here as "More info". */
488export function t3ConnectTroubleshootingUrl(section: T3ConnectTroubleshootingSection): string {
489 return `https://github.com/pingdotgg/t3code/blob/main/docs/user/t3-connect-troubleshooting.md#${section}`;
491​
492const REACHABILITY_SECTION = {
493 not_linked: "sign-in-account-or-link-problems",
494 connector_not_running: "the-hosts-tunnel-is-offline",
495 connector_not_ready: "the-hosts-tunnel-is-offline",
496 no_connector: "the-hosts-tunnel-is-offline",
497 edge_unreachable: "port-7844-is-blocked-on-the-host",
498 origin_unreachable: "the-tunnel-works-but-t3-code-does-not-answer",
499 unexpected_response: "the-tunnel-works-but-t3-code-does-not-answer",
500 dns_failed: "the-t3-connect-address-does-not-resolve-or-answer",
501 timeout: "the-t3-connect-address-does-not-resolve-or-answer",
502} satisfies Record<EnvironmentConnectReachabilityCause, T3ConnectTroubleshootingSection>;
503​
504export function connectReachabilityHelpUrl(cause: EnvironmentConnectReachabilityCause): string {
505 return t3ConnectTroubleshootingUrl(REACHABILITY_SECTION[cause]);
507​
508export const EnvironmentCloudLinkStateResult = Schema.Struct({
509 linked: Schema.Boolean,
510 cloudUserId: Schema.NullOr(Schema.String),
511 relayUrl: Schema.NullOr(Schema.String),
512 relayIssuer: Schema.NullOr(Schema.String),
513 managedTunnelActive: Schema.optional(Schema.Boolean),
514 publishAgentActivity: Schema.Boolean,
515 holdWebhooksWhileOffline: Schema.optional(Schema.Boolean),
516 linkRevoked: Schema.optional(Schema.Boolean),
517 /** The latest check the server ran on its own, absent until one finishes. */
518 reachability: Schema.optional(EnvironmentConnectReachability),
519});
520export type EnvironmentCloudLinkStateResult = typeof EnvironmentCloudLinkStateResult.Type;
521​
522export const EnvironmentCloudPreferencesRequest = Schema.Struct({
523 publishAgentActivity: Schema.Boolean,
524 holdWebhooksWhileOffline: Schema.optional(Schema.Boolean),
525});
526export type EnvironmentCloudPreferencesRequest = typeof EnvironmentCloudPreferencesRequest.Type;
527​
528export const AuthPairingLinkRevokeResult = Schema.Struct({
529 revoked: Schema.Boolean,
530});
531export type AuthPairingLinkRevokeResult = typeof AuthPairingLinkRevokeResult.Type;
532​
533export const AuthClientSessionRevokeResult = Schema.Struct({
534 revoked: Schema.Boolean,
535});
536export type AuthClientSessionRevokeResult = typeof AuthClientSessionRevokeResult.Type;
537​
538export const AuthOtherClientSessionsRevokeResult = Schema.Struct({
539 revokedCount: Schema.Number,
540});
541export type AuthOtherClientSessionsRevokeResult = typeof AuthOtherClientSessionsRevokeResult.Type;
542​
543class EnvironmentMetadataHttpApi extends HttpApiGroup.make("metadata").add(
544 HttpApiEndpoint.get("descriptor", "/.well-known/t3/environment", {
545 success: ExecutionEnvironmentDescriptor,
546 }),
547) {}
548​
549class EnvironmentAuthHttpApi extends HttpApiGroup.make("auth")
550 .add(
551 HttpApiEndpoint.get("session", "/api/auth/session", {
552 headers: OptionalBearerHeaders,
553 success: AuthSessionState,
554 error: [EnvironmentInternalError],
555 }),
556 )
557 .add(
558 HttpApiEndpoint.post("browserSession", "/api/auth/browser-session", {
559 payload: AuthBrowserSessionRequest,
560 success: AuthBrowserSessionResult,
561 error: EnvironmentSessionCreationErrors,
562 }),
563 )
564 .add(
565 HttpApiEndpoint.post("token", "/oauth/token", {
566 headers: OptionalDpopProofHeaders,
567 payload: AuthTokenExchangeRequest,
568 success: AuthAccessTokenResult,
569 error: EnvironmentTokenExchangeErrors,
570 }),
571 )
572 .add(
573 HttpApiEndpoint.post("webSocketTicket", "/api/auth/websocket-ticket", {
574 headers: OptionalBearerHeaders,
575 success: AuthWebSocketTicketResult,
576 error: [EnvironmentInternalError],
577 }).middleware(EnvironmentAuthenticatedAuth),
578 )
579 .add(
580 HttpApiEndpoint.post("webSocketTicketFor", "/api/auth/websocket-ticket/:use", {
581 headers: OptionalBearerHeaders,
582 params: AuthWebSocketTicketParams,
583 success: AuthWebSocketTicketResult,
584 error: [EnvironmentInternalError],
585 }).middleware(EnvironmentAuthenticatedAuth),
586 )
587 .add(
588 HttpApiEndpoint.post("pairingCredential", "/api/auth/pairing-token", {
589 headers: OptionalBearerHeaders,
590 payload: AuthCreatePairingCredentialInput,
591 success: AuthPairingCredentialResult,
592 error: EnvironmentPairingCredentialErrors,
593 }).middleware(EnvironmentAuthenticatedAuth),
594 )
595 .add(
596 HttpApiEndpoint.post("revokePairingLink", "/api/auth/pairing-links/revoke", {
597 headers: OptionalBearerHeaders,
598 payload: AuthRevokePairingLinkInput,
599 success: AuthPairingLinkRevokeResult,
600 error: EnvironmentScopedOperationErrors,
601 }).middleware(EnvironmentAuthenticatedAuth),
602 )
603 .add(
604 HttpApiEndpoint.post("revokeClient", "/api/auth/clients/revoke", {
605 headers: OptionalBearerHeaders,
606 payload: AuthRevokeClientSessionInput,
607 success: AuthClientSessionRevokeResult,
608 error: EnvironmentSessionRevokeErrors,
609 }).middleware(EnvironmentAuthenticatedAuth),
610 )
611 .add(
612 HttpApiEndpoint.post("revokeOtherClients", "/api/auth/clients/revoke-others", {
613 headers: OptionalBearerHeaders,
614 success: AuthOtherClientSessionsRevokeResult,
615 error: EnvironmentScopedOperationErrors,
616 }).middleware(EnvironmentAuthenticatedAuth),
617 ) {}
618​
619class EnvironmentMcpOAuthHttpApi extends HttpApiGroup.make("mcpOAuth")
620 .add(
621 HttpApiEndpoint.get("protectedResource", "/.well-known/oauth-protected-resource", {
622 success: AuthMcpProtectedResourceMetadata,
623 }),
624 )
625 .add(
626 HttpApiEndpoint.get("mcpProtectedResource", "/.well-known/oauth-protected-resource/mcp", {
627 success: AuthMcpProtectedResourceMetadata,
628 }),
629 )
630 .add(
631 HttpApiEndpoint.get("authorizationServer", "/.well-known/oauth-authorization-server", {
632 success: AuthMcpAuthorizationServerMetadata,
633 }),
634 )
635 .add(
636 HttpApiEndpoint.post("register", "/oauth/mcp/register", {
637 payload: AuthMcpClientRegistration,
638 success: AuthMcpRegisteredClient,
639 error: AuthMcpRegistrationError,
640 }),
641 )
642 .add(HttpApiEndpoint.get("authorize", "/oauth/mcp/authorize"))
643 .add(
644 HttpApiEndpoint.post("approval", "/oauth/mcp/approval", {
645 payload: AuthMcpAuthorizationRequest,
646 success: [AuthMcpApprovalDetails, AuthMcpApprovalRedirect],
647 error: AuthMcpApprovalError,
648 }),
649 )
650 .add(
651 HttpApiEndpoint.post("decision", "/oauth/mcp/decision", {
652 payload: AuthMcpApprovalDecisionRequest,
653 success: AuthMcpApprovalRedirect,
654 error: AuthMcpApprovalError,
655 }),
656 )
657 .add(
658 HttpApiEndpoint.post("token", "/oauth/mcp/token", {
659 payload: AuthMcpTokenRequest,
660 success: AuthMcpTokenResult,
661 error: AuthMcpTokenError,
662 }),
663 ) {}
664​
665const EnvironmentOrchestrationThreadSnapshotParams = Schema.Struct({
666 threadId: ThreadId,
667});
668​
669const EnvironmentOrchestrationShellSnapshotQuery = Schema.Struct({
670 omitIdleSubagents: Schema.optionalKey(Schema.String),
671 omitOlderSettled: Schema.optionalKey(Schema.String),
672});
673​
674const EnvironmentOrchestrationThreadBoundedSnapshotQuery = Schema.Struct({
675 deferWork: Schema.optionalKey(Schema.String),
676 compactTurnItems: Schema.optionalKey(Schema.String),
677 dedupeBodies: Schema.optionalKey(Schema.String),
678 compactIds: Schema.optionalKey(Schema.String),
679});
680​
681const EnvironmentOrchestrationThreadHistoryQuery = Schema.Struct({
682 cursor: TrimmedNonEmptyString,
683 throughEntryId: Schema.optional(TrimmedNonEmptyString),
684 view: Schema.optional(Schema.Literals(["conversation", "activity", "work"])),
685 deferWork: Schema.optionalKey(Schema.String),
686 compactIds: Schema.optionalKey(Schema.String),
687});
688​
689const EnvironmentOrchestrationThreadHistoryErrors = [
690 EnvironmentRequestInvalidError,
691 EnvironmentScopeRequiredError,
692 EnvironmentResourceNotFoundError,
693 EnvironmentInternalError,
694] as const;
695​
696class EnvironmentOrchestrationHttpApi extends HttpApiGroup.make("orchestration")
697 .add(
698 HttpApiEndpoint.get("shellSnapshot", "/api/orchestration/shell", {
699 headers: OrchestrationProtocolHeaders,
700 query: EnvironmentOrchestrationShellSnapshotQuery,
701 success: OrchestrationV2ShellSnapshot,
702 error: EnvironmentOrchestrationSnapshotErrors,
703 }).middleware(EnvironmentAuthenticatedAuth),
704 )
705 .add(
706 HttpApiEndpoint.get("threadSnapshot", "/api/orchestration/threads/:threadId", {
707 headers: OrchestrationProtocolHeaders,
708 params: EnvironmentOrchestrationThreadSnapshotParams,
709 success: OrchestrationV2ThreadDetailSnapshot,
710 error: EnvironmentOrchestrationThreadSnapshotErrors,
711 }).middleware(EnvironmentAuthenticatedAuth),
712 )
713 .add(
714 HttpApiEndpoint.get("threadTranscript", "/api/orchestration/threads/:threadId/transcript", {
715 headers: OrchestrationProtocolHeaders,
716 params: EnvironmentOrchestrationThreadSnapshotParams,
717 success: OrchestrationV2ThreadTranscript,
718 error: [EnvironmentRequestInvalidError, ...EnvironmentOrchestrationThreadSnapshotErrors],
719 }).middleware(EnvironmentAuthenticatedAuth),
720 )
721 .add(
722 HttpApiEndpoint.get("threadBoundedSnapshot", "/api/orchestration/threads/:threadId/bounded", {
723 headers: OrchestrationProtocolHeaders,
724 params: EnvironmentOrchestrationThreadSnapshotParams,
725 query: EnvironmentOrchestrationThreadBoundedSnapshotQuery,
726 success: OrchestrationV2ThreadBoundedSnapshot,
727 error: EnvironmentOrchestrationThreadSnapshotErrors,
728 }).middleware(EnvironmentAuthenticatedAuth),
729 )
730 .add(
731 HttpApiEndpoint.get("threadHistoryPage", "/api/orchestration/threads/:threadId/history", {
732 headers: OrchestrationProtocolHeaders,
733 params: EnvironmentOrchestrationThreadSnapshotParams,
734 query: EnvironmentOrchestrationThreadHistoryQuery,
735 success: OrchestrationV2ThreadHistoryPage,
736 error: EnvironmentOrchestrationThreadHistoryErrors,
737 }).middleware(EnvironmentAuthenticatedAuth),
738 ) {}
739​
740class EnvironmentProjectsHttpApi extends HttpApiGroup.make("projects")
741 .add(
742 HttpApiEndpoint.get("snapshot", "/api/projects", {
743 headers: OptionalBearerHeaders,
744 success: ProjectSnapshot,
745 error: EnvironmentProjectSnapshotErrors,
746 }).middleware(EnvironmentAuthenticatedAuth),
747 )
748 .add(
749 HttpApiEndpoint.post("mutate", "/api/projects/mutate", {
750 headers: OptionalBearerHeaders,
751 payload: ProjectMutation,
752 success: Project,
753 error: EnvironmentProjectMutationErrors,
754 }).middleware(EnvironmentAuthenticatedAuth),
755 ) {}
756​
757class EnvironmentPullRequestsHttpApi extends HttpApiGroup.make("pullRequests").add(
758 HttpApiEndpoint.post("diff", "/api/pull-requests/diff", {
759 headers: OptionalBearerHeaders,
760 payload: PullRequestDiffInput,
761 success: PullRequestDiffResult,
762 error: [
763 PullRequestUnavailableError,
764 PullRequestOperationError,
765 EnvironmentAuthInvalidError,
766 EnvironmentScopeRequiredError,
767 EnvironmentInternalError,
768 ],
769 }).middleware(EnvironmentAuthenticatedAuth),
770) {}
771​
772export class EnvironmentVoiceBodyLimit extends HttpApiMiddleware.Service<EnvironmentVoiceBodyLimit>()(
773 "EnvironmentVoiceBodyLimit",
774 { error: EnvironmentRequestInvalidError },
775) {}
776​
777export class EnvironmentVoiceHttpApi extends HttpApiGroup.make("voice")
778 .add(
779 HttpApiEndpoint.get("status", "/api/voice/status", {
780 headers: OptionalBearerHeaders,
781 success: EnvironmentSpeechStatus,
782 error: [...EnvironmentScopedOperationErrors, EnvironmentRequestInvalidError],
783 }).middleware(EnvironmentAuthenticatedAuth),
784 )
785 .add(
786 HttpApiEndpoint.post("prepareModel", "/api/voice/models/prepare", {
787 headers: OptionalBearerHeaders,
788 success: Schema.Void,
789 error: [...EnvironmentScopedOperationErrors, EnvironmentRequestInvalidError],
790 }).middleware(EnvironmentAuthenticatedAuth),
791 )
792 .add(
793 HttpApiEndpoint.get("models", "/api/voice/models", {
794 headers: OptionalBearerHeaders,
795 query: { benchmarks: Schema.optionalKey(Schema.Literal("1")) },
796 success: EnvironmentSpeechModels,
797 error: [...EnvironmentScopedOperationErrors, EnvironmentRequestInvalidError],
798 }).middleware(EnvironmentAuthenticatedAuth),
799 )
800 .add(
801 HttpApiEndpoint.post("downloadModel", "/api/voice/models/download", {
802 headers: OptionalBearerHeaders,
803 payload: EnvironmentSpeechModelRequest,
804 success: EnvironmentSpeechModels,
805 error: [...EnvironmentScopedOperationErrors, EnvironmentRequestInvalidError],
806 }).middleware(EnvironmentAuthenticatedAuth),
807 )
808 .add(
809 HttpApiEndpoint.post("selectModel", "/api/voice/models/select", {
810 headers: OptionalBearerHeaders,
811 payload: EnvironmentSpeechModelRequest,
812 success: EnvironmentSpeechModels,
813 error: [...EnvironmentScopedOperationErrors, EnvironmentRequestInvalidError],
814 }).middleware(EnvironmentAuthenticatedAuth),
815 )
816 .add(
817 HttpApiEndpoint.post("cancelModelDownload", "/api/voice/models/cancel", {
818 headers: OptionalBearerHeaders,
819 payload: EnvironmentSpeechModelRequest,
820 success: EnvironmentSpeechModels,
821 error: [...EnvironmentScopedOperationErrors, EnvironmentRequestInvalidError],
822 }).middleware(EnvironmentAuthenticatedAuth),
823 )
824 .add(
825 HttpApiEndpoint.post("removeModel", "/api/voice/models/remove", {
826 headers: OptionalBearerHeaders,
827 payload: EnvironmentSpeechModelRequest,
828 success: EnvironmentSpeechModels,
829 error: [...EnvironmentScopedOperationErrors, EnvironmentRequestInvalidError],
830 }).middleware(EnvironmentAuthenticatedAuth),
831 )
832 .add(
833 HttpApiEndpoint.post("updateAcceleration", "/api/voice/acceleration", {
834 headers: OptionalBearerHeaders,
835 payload: EnvironmentSpeechAccelerationRequest,
836 success: EnvironmentSpeechStatus,
837 error: [...EnvironmentScopedOperationErrors, EnvironmentRequestInvalidError],
838 }).middleware(EnvironmentAuthenticatedAuth),
839 )
840 .add(
841 HttpApiEndpoint.post("updateModelUnloadTimeout", "/api/voice/model-unload-timeout", {
842 headers: OptionalBearerHeaders,
843 payload: EnvironmentSpeechModelUnloadTimeoutRequest,
844 success: EnvironmentSpeechStatus,
845 error: [...EnvironmentScopedOperationErrors, EnvironmentRequestInvalidError],
846 }).middleware(EnvironmentAuthenticatedAuth),
847 )
848 .add(
849 HttpApiEndpoint.post("transcribe", "/api/voice/transcribe", {
850 headers: OptionalBearerHeaders,
851 payload: Schema.Uint8Array.pipe(HttpApiSchema.asUint8Array()),
852 success: EnvironmentSpeechTranscriptionResult,
853 error: [...EnvironmentScopedOperationErrors, EnvironmentRequestInvalidError],
854 })
855 .middleware(EnvironmentVoiceBodyLimit)
856 .middleware(EnvironmentAuthenticatedAuth),
857 )
858 .add(
859 HttpApiEndpoint.post("postProcess", "/api/voice/post-process", {
860 headers: OptionalBearerHeaders,
861 payload: EnvironmentSpeechPostProcessingRequest,
862 success: EnvironmentSpeechPostProcessingResult,
863 error: EnvironmentScopedOperationErrors,
864 }).middleware(EnvironmentAuthenticatedAuth),
865 ) {}
866​
867class EnvironmentConnectHttpApi extends HttpApiGroup.make("connect")
868 .add(
869 HttpApiEndpoint.post("linkProof", "/api/connect/link-proof", {
870 headers: OptionalBearerHeaders,
871 payload: RelayLinkProofRequest,
872 success: RelayEnvironmentLinkProof,
873 error: EnvironmentHttpCloudErrors,
874 }).middleware(EnvironmentAuthenticatedAuth),
875 )
876 .add(
877 HttpApiEndpoint.post("relayConfig", "/api/connect/relay-config", {
878 headers: OptionalBearerHeaders,
879 payload: RelayEnvironmentConfigRequest,
880 success: EnvironmentCloudRelayConfigResult,
881 error: [...EnvironmentHttpCloudErrors, EnvironmentCloudEndpointUnavailableError],
882 }).middleware(EnvironmentAuthenticatedAuth),
883 )
884 .add(
885 HttpApiEndpoint.get("linkState", "/api/connect/link-state", {
886 headers: OptionalBearerHeaders,
887 success: EnvironmentCloudLinkStateResult,
888 error: EnvironmentHttpCloudErrors,
889 }).middleware(EnvironmentAuthenticatedAuth),
890 )
891 .add(
892 HttpApiEndpoint.post("checkReachability", "/api/connect/reachability", {
893 headers: OptionalBearerHeaders,
894 success: EnvironmentConnectReachability,
895 error: EnvironmentHttpCloudErrors,
896 }).middleware(EnvironmentAuthenticatedAuth),
897 )
898 .add(
899 HttpApiEndpoint.post("unlink", "/api/connect/unlink", {
900 headers: OptionalBearerHeaders,
901 success: EnvironmentCloudRelayConfigResult,
902 error: EnvironmentHttpCloudErrors,
903 }).middleware(EnvironmentAuthenticatedAuth),
904 )
905 .add(
906 HttpApiEndpoint.post("preferences", "/api/connect/preferences", {
907 headers: OptionalBearerHeaders,
908 payload: EnvironmentCloudPreferencesRequest,
909 success: EnvironmentCloudLinkStateResult,
910 error: EnvironmentHttpCloudErrors,
911 }).middleware(EnvironmentAuthenticatedAuth),
912 )
913 .add(
914 HttpApiEndpoint.post("health", "/api/t3-connect/health", {
915 payload: RelayCloudEnvironmentHealthRequest,
916 success: RelayEnvironmentHealthResponse,
917 error: EnvironmentHttpCloudErrors,
918 }),
919 )
920 .add(
921 HttpApiEndpoint.post("t3MintCredential", "/api/t3-connect/mint-credential", {
922 payload: RelayCloudMintCredentialRequest,
923 success: RelayEnvironmentMintResponse,
924 error: EnvironmentHttpCloudErrors,
925 }),
926 ) {}
927​
928// Path tokens and optional body signatures authenticate webhooks; read raw bytes to verify signatures.
929const WebhookParams = Schema.Struct({
930 hookId: TrimmedNonEmptyString,
931 token: TrimmedNonEmptyString,
932});
933const WebhookAccepted = Schema.Struct({ deliveryId: TrimmedNonEmptyString }).pipe(
934 HttpApiSchema.status(202),
935);
936const webhookEndpoint = {
937 params: WebhookParams,
938 success: WebhookAccepted,
939} as const;
940const WEBHOOK_PATH = "/api/hooks/:hookId/:token";
941​
942class EnvironmentWebhooksHttpApi extends HttpApiGroup.make("webhooks")
943 .add(HttpApiEndpoint.post("webhookPost", WEBHOOK_PATH, webhookEndpoint))
944 .add(HttpApiEndpoint.put("webhookPut", WEBHOOK_PATH, webhookEndpoint))
945 .add(HttpApiEndpoint.patch("webhookPatch", WEBHOOK_PATH, webhookEndpoint))
946 .add(HttpApiEndpoint.get("webhookGet", WEBHOOK_PATH, webhookEndpoint)) {}
947​
948export class EnvironmentHttpApi extends HttpApi.make("environment")
949 .add(EnvironmentMetadataHttpApi)
950 .add(EnvironmentAuthHttpApi)
951 .add(EnvironmentMcpOAuthHttpApi)
952 .add(EnvironmentOrchestrationHttpApi)
953 .add(EnvironmentPullRequestsHttpApi)
954 .add(EnvironmentProjectsHttpApi)
955 .add(EnvironmentVoiceHttpApi)
956 .add(EnvironmentConnectHttpApi)
957 .add(EnvironmentWebhooksHttpApi) {}