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