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