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

environmentHttp.ts

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