The best way to control Claude Code, Codex and more from any computer or phone

main
ts 207 lines 7.11 KB
Raw
1 import * as Context from "effect/Context";
2 import * as Duration from "effect/Duration";
3 import * as Effect from "effect/Effect";
4 import * as Layer from "effect/Layer";
5 import * as Option from "effect/Option";
6 import * as Redacted from "effect/Redacted";
7 import * as Schema from "effect/Schema";
8 import * as FetchHttpClient from "effect/http/FetchHttpClient";
9 import * as HttpClient from "effect/http/HttpClient";
10 import * as HttpClientRequest from "effect/http/HttpClientRequest";
11
12 import * as GitCafeCredentials from "./GitCafeCredentials.ts";
13 import * as GitCafeHosts from "./gitCafeHosts.ts";
14
15 const NO_REDIRECT: RequestInit = { redirect: "manual" };
16 const MAX_REDIRECTS = 3;
17 const TIMEOUT = Duration.seconds(30);
18
19 export const GitCafeApiFailure = Schema.Literals([
20 "missing-tool",
21 "unauthenticated",
22 "rate-limited",
23 "not-found",
24 "failed",
25 ]);
26
27 export class GitCafeApiError extends Schema.TaggedError<GitCafeApiError>()("GitCafeApiError", {
28 host: Schema.String,
29 operation: Schema.String,
30 status: Schema.NullOr(Schema.Int),
31 reason: GitCafeApiFailure,
32 detail: Schema.String,
33 cause: Schema.optional(Schema.Defect()),
34 }) {
35 override get message(): string {
36 return `GitCafe ${this.operation} failed on ${this.host}: ${this.detail}`;
37 }
38 }
39
40 export interface GitCafeApiRequest {
41 readonly host: string;
42 readonly operation: string;
43 readonly method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
44 readonly path: string;
45 readonly body?: unknown;
46 }
47
48 export class GitCafeApi extends Context.Service<
49 GitCafeApi,
50 {
51 readonly request: (input: GitCafeApiRequest) => Effect.Effect<string, GitCafeApiError>;
52 }
53 >()("@t3tools/source-control-gitcafe/server/GitCafeApi") {}
54
55 const decodeProblem = Schema.decodeUnknownOption(
56 Schema.fromJsonString(
57 Schema.Struct({
58 title: Schema.optional(Schema.String),
59 detail: Schema.optional(Schema.String),
60 }),
61 ),
62 );
63
64 const reasonForStatus = (status: number): typeof GitCafeApiFailure.Type =>
65 status === 401
66 ? "unauthenticated"
67 : status === 429
68 ? "rate-limited"
69 : status === 404
70 ? "not-found"
71 : "failed";
72
73 const MAX_PROBLEM_TEXT = 300;
74 const boundedProblemText = (text: string | undefined) => {
75 const line = text?.replace(/\s+/gu, " ").trim();
76 if (!line) return undefined;
77 return line.length > MAX_PROBLEM_TEXT ? `${line.slice(0, MAX_PROBLEM_TEXT)}…` : line;
78 };
79
80 const credentialFailure = (
81 error: GitCafeCredentials.GitCafeCredentialUnavailableError,
82 ): typeof GitCafeApiFailure.Type =>
83 error._tag === "GitCafeCliMissingError"
84 ? "missing-tool"
85 : error._tag === "GitCafeNotSignedInError" || error._tag === "SettingsSecretUnresolvedError"
86 ? "unauthenticated"
87 : "failed";
88
89 const REDIRECTS = new Set([301, 302, 303, 307, 308]);
90 // 307 and 308 keep the method and body; the others only safely repeat a read.
91 const METHOD_PRESERVING = new Set([307, 308]);
92
93 const redirectTarget = (
94 method: string,
95 origin: string,
96 from: string,
97 response: { readonly status: number; readonly location: string | undefined },
98 ): string | null => {
99 if (!REDIRECTS.has(response.status) || response.location === undefined) return null;
100 if (method !== "GET" && !METHOD_PRESERVING.has(response.status)) return null;
101 const target = URL.parse(response.location, from);
102 return target !== null &&
103 target.origin === origin &&
104 target.username === "" &&
105 target.password === "" &&
106 target.pathname.startsWith("/api/")
107 ? target.href
108 : null;
109 };
110
111 /** @public */
112 export const make = Effect.gen(function* () {
113 const httpClient = yield* HttpClient.HttpClient;
114 const credentials = yield* GitCafeCredentials.GitCafeCredentials;
115
116 const request = Effect.fn("GitCafeApi.request")(function* (input: GitCafeApiRequest) {
117 const fail = (
118 fields: Pick<GitCafeApiError, "status" | "reason" | "detail"> & { cause?: unknown },
119 ) =>
120 new GitCafeApiError({
121 host: input.host,
122 operation: input.operation,
123 status: fields.status,
124 reason: fields.reason,
125 detail: fields.detail,
126 ...(fields.cause === undefined ? {} : { cause: fields.cause }),
127 });
128 // Remote URLs must not send tokens outside GitCafe's hosts.
129 const host = GitCafeHosts.gitCafeHost(input.host);
130 if (host === null)
131 return yield* fail({
132 status: null,
133 reason: "failed",
134 detail: `GitCafe lives on ${GitCafeHosts.GITCAFE_HOSTS.join(" and ")}, not ${input.host}.`,
135 });
136 yield* Effect.annotateCurrentSpan({
137 "gitcafe.host": host,
138 "gitcafe.operation": input.operation,
139 "http.request.method": input.method ?? "GET",
140 });
141 const credential = yield* credentials
142 .get(host)
143 .pipe(
144 Effect.mapError((cause) =>
145 fail({ status: null, reason: credentialFailure(cause), detail: cause.message, cause }),
146 ),
147 );
148 const origin = `https://${host}`;
149 const method = input.method ?? "GET";
150 const send = (url: string) => {
151 const base = HttpClientRequest.make(method)(url).pipe(
152 HttpClientRequest.bearerToken(Redacted.value(credential.token)),
153 HttpClientRequest.setHeaders({ accept: "application/json", "user-agent": "t3code" }),
154 );
155 return Effect.gen(function* () {
156 const response = yield* httpClient
157 .execute(
158 input.body === undefined
159 ? base
160 : base.pipe(HttpClientRequest.bodyJsonUnsafe(input.body)),
161 )
162 .pipe(
163 // Client spans expose query strings containing branch names.
164 Effect.provideService(HttpClient.TracerDisabledWhen, () => true),
165 // fetch would carry the bearer token to any redirect target.
166 Effect.provideService(FetchHttpClient.RequestInit, NO_REDIRECT),
167 );
168 return {
169 status: response.status,
170 location: response.headers.location,
171 text: yield* response.text,
172 };
173 }).pipe(
174 Effect.timeout(TIMEOUT),
175 Effect.mapError((cause) =>
176 fail({ status: null, reason: "failed", detail: "Could not reach GitCafe.", cause }),
177 ),
178 );
179 };
180 // A renumbered pull request (provisional number replaced by the synced GitHub one)
181 // answers with a redirect; follow it only within this host's API.
182 let url = `${origin}/api${input.path}`;
183 let response = yield* send(url);
184 for (let hop = 0; hop < MAX_REDIRECTS; hop++) {
185 const next = redirectTarget(method, origin, url, response);
186 if (next === null) break;
187 url = next;
188 response = yield* send(url);
189 }
190 const { status, text } = response;
191 yield* Effect.annotateCurrentSpan({ "http.response.status_code": status });
192 if (status >= 200 && status < 300) return text;
193 // The source may hold a newer token than the one that was refused.
194 if (status === 401) yield* credentials.invalidate(host);
195 const problem = Option.getOrUndefined(decodeProblem(text));
196 return yield* fail({
197 status,
198 reason: reasonForStatus(status),
199 detail:
200 boundedProblemText(problem?.detail ?? problem?.title) ?? `GitCafe answered HTTP ${status}.`,
201 });
202 });
203
204 return GitCafeApi.of({ request });
205 });
206
207 export const layer = Layer.effect(GitCafeApi, make);