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

OriginCli.ts

510 lines18.9 KB

1/**
2 * Requests borrow the `origin` CLI's session token and go straight to `api.cursor.com/v1/origin`
3 * over one long-lived HTTP/2 connection: spawning the CLI per request costs about 0.8s, a warm
4 * request about 0.2s.
5 */
6import * as Clock from "effect/Clock";
7import * as Context from "effect/Context";
8import * as Effect from "effect/Effect";
9import * as Layer from "effect/Layer";
10import * as PlatformError from "effect/PlatformError";
11import * as Redacted from "effect/Redacted";
12import * as Result from "effect/Result";
13import * as Schema from "effect/Schema";
14import * as Semaphore from "effect/Semaphore";
15import { HttpClient, HttpClientRequest } from "effect/http";
16import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient";
17import { Agent } from "@effect/platform-node/Undici";
18import { collectUint8StreamText } from "@t3tools/provider-core/server/collectStreamText";
19import { decodeJsonResult } from "@t3tools/shared/schemaJson";
20import { parseGitRemoteHost } from "@t3tools/source-control-core/shared/definition";
21import { CURSOR_ORIGIN_GIT_HOST } from "../shared/definition.ts";
22import { retryAtFromHeader } from "@t3tools/source-control-core/server/SourceControlRateLimit";
23import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
24import type { SourceControlProviderContext } from "@t3tools/source-control-core/server/SourceControlProvider";
25import { repositoryPathFromRemoteUrl } from "@t3tools/source-control-core/server/SourceControlProvider";
26​
27const DEFAULT_TIMEOUT_MS = 30_000;
28const MISSING_TOKEN_TTL_MS = 10_000;
29/** How long a session is trusted before the CLI is asked again, as the GitHub and GitCafe credentials are. */
30const SESSION_TTL_MS = 5 * 60_000;
31const MAX_OUTPUT_BYTES = 8_000_000;
32const API_BASE_URL = "https://api.cursor.com";
33​
34export const ORIGIN_COMMAND = "origin";
35​
36export class OriginCliError extends Schema.TaggedError<OriginCliError>()("OriginCliError", {
37 operation: Schema.String,
38 cwd: Schema.String,
39 detail: Schema.String,
40 reason: Schema.Literals([
41 "missing-tool",
42 "unauthenticated",
43 "rate-limited",
44 "not-found",
45 "invalid-response",
46 "failed",
47 ]),
48 httpStatus: Schema.optional(Schema.Int),
49 /** When a rate-limited request may be sent again, in epoch milliseconds. */
50 retryAt: Schema.optional(Schema.Number),
51 cause: Schema.optional(Schema.Defect()),
52}) {
53 override get message(): string {
54 return `Cursor Origin failed in ${this.operation}: ${this.detail}`;
55 }
57​
58/** What `origin auth status --json` reports. Only the fields this package reads. */
59const OriginAuthStatusSchema = Schema.Struct({
60 authenticated: Schema.Boolean,
61 tokenValid: Schema.optional(Schema.Boolean),
62 account: Schema.optional(
63 Schema.NullOr(Schema.Struct({ email: Schema.optional(Schema.NullOr(Schema.String)) })),
64 ),
65});
66type OriginAuthStatus = typeof OriginAuthStatusSchema.Type;
67​
68export function parseOriginAuthStatus(raw: string): OriginAuthStatus | null {
69 const decoded = decodeJsonResult(OriginAuthStatusSchema)(raw);
70 return Result.isSuccess(decoded) ? decoded.success : null;
72​
73/** The signed-in account's email, which is what `origin auth status` names it by. */
74export function originAccount(status: OriginAuthStatus | null): string | null {
75 if (!status?.authenticated || status.tokenValid === false) return null;
76 return status.account?.email?.trim() || null;
78​
79const OriginNamespaceListSchema = Schema.Struct({
80 namespaces: Schema.optional(
81 Schema.NullOr(
82 Schema.Array(
83 Schema.Struct({ namespace: Schema.Struct({ slug: Schema.String, type: Schema.String }) }),
84 ),
85 ),
86 ),
87});
88​
89/** `owner/repo` for a REST path, each segment escaped. */
90export function originRepositoryPath(repository: string): string {
91 return `/v1/origin/repos/${repository.split("/").map(encodeURIComponent).join("/")}`;
93​
94/** The message an Origin error body carries, Connect-style or REST-style. */
95function errorBodyMessage(body: string): string | null {
96 const decoded = decodeJsonResult(
97 Schema.Struct({
98 message: Schema.optional(Schema.String),
99 error: Schema.optional(
100 Schema.Union([Schema.String, Schema.Struct({ message: Schema.optional(Schema.String) })]),
101 ),
102 }),
103 )(body);
104 if (Result.isFailure(decoded)) return null;
105 const { message, error } = decoded.success;
106 return message ?? (typeof error === "string" ? error : error?.message) ?? null;
108​
109const UNAUTHENTICATED_DETAIL =
110 "Cursor Origin CLI is not signed in. Run `origin auth login` and retry.";
111​
112/** A failed `origin` command, read from its exit and output. */
113function classifyOriginFailure(input: {
114 readonly operation: string;
115 readonly cwd: string;
116 readonly stdout: string;
117 readonly stderr: string;
118}): OriginCliError {
119 const text = `${input.stderr}\n${input.stdout}`;
120 const reason: OriginCliError["reason"] =
121 /not authenticated|not (?:logged|signed) in|origin auth login|unauthenticated|unauthorized/iu.test(
122 text,
123 )
124 ? "unauthenticated"
125 : /rate.?limit|too many requests|\b429\b/iu.test(text)
126 ? "rate-limited"
127 : /\bnot[_ ]found\b/iu.test(text)
128 ? "not-found"
129 : "failed";
130 const firstLine = input.stderr
131 .split(/\r?\n/u)
132 .map((line) => line.trim())
133 .find((line) => line.length > 0);
134 return new OriginCliError({
135 operation: input.operation,
136 cwd: input.cwd,
137 reason,
138 detail:
139 reason === "unauthenticated"
140 ? UNAUTHENTICATED_DETAIL
141 : input.operation === "authToken"
142 ? "Cursor Origin CLI could not hand over a session token. Check `origin auth status`."
143 : (errorBodyMessage(input.stdout) ??
144 firstLine?.replace(/^Error:\s*/u, "") ??
145 "Cursor Origin CLI command failed."),
146 });
148​
149/** A non-2xx API response. */
150function classifyOriginResponse(input: {
151 readonly operation: string;
152 readonly cwd: string;
153 readonly status: number;
154 readonly body: string;
155 readonly headers: Readonly<Record<string, string | undefined>>;
156 readonly now: number;
157}): OriginCliError {
158 const reason: OriginCliError["reason"] =
159 input.status === 401
160 ? "unauthenticated"
161 : input.status === 429
162 ? "rate-limited"
163 : input.status === 404
164 ? "not-found"
165 : "failed";
166 const reset = Number(input.headers["x-ratelimit-reset"]) * 1_000;
167 const retryAt =
168 reason !== "rate-limited"
169 ? undefined
170 : (retryAtFromHeader(input.headers["retry-after"], input.now) ??
171 (Number.isFinite(reset) && reset > input.now ? reset : undefined));
172 return new OriginCliError({
173 operation: input.operation,
174 cwd: input.cwd,
175 reason,
176 httpStatus: input.status,
177 ...(retryAt === undefined ? {} : { retryAt }),
178 detail:
179 reason === "unauthenticated"
180 ? UNAUTHENTICATED_DETAIL
181 : reason === "rate-limited"
182 ? "Cursor Origin API rate limit exceeded."
183 : (errorBodyMessage(input.body) ??
184 `Cursor Origin request failed (HTTP ${input.status}).`),
185 });
187​
188interface OriginApiInput {
189 readonly cwd: string;
190 readonly operation: string;
191 /** A full `/v1/origin/...` path, query included. */
192 readonly path: string;
193 readonly method?: "GET" | "POST" | "PATCH";
194 readonly body?: unknown;
196​
197export class OriginCli extends Context.Service<
198 OriginCli,
199 {
200 /** Runs `origin …args` and fails with a classified error on a non-zero exit. */
201 readonly execute: (input: {
202 readonly cwd: string;
203 readonly operation: string;
204 readonly args: ReadonlyArray<string>;
205 }) => Effect.Effect<string, OriginCliError>;
206 /** One REST request, decoded with `schema`. */
207 readonly api: <S extends Schema.Codec<unknown, unknown, never, never>>(
208 input: OriginApiInput,
209 schema: S,
210 ) => Effect.Effect<S["Type"], OriginCliError>;
211 /** The signed-in account, held until the session's token is refused. */
212 readonly viewer: (cwd: string) => Effect.Effect<string, OriginCliError>;
213 /** The signed-in user's own namespace slug, which owns their repositories and pull requests. */
214 readonly personalNamespace: (cwd: string) => Effect.Effect<string, OriginCliError>;
215 /** `owner/repo` for the checkout, from the caller's remote or the checkout's primary remote. */
216 readonly resolveRepository: (input: {
217 readonly cwd: string;
218 readonly context?: SourceControlProviderContext;
219 }) => Effect.Effect<string, OriginCliError>;
220 }
221>()("@t3tools/source-control-cursor-origin/server/OriginCli") {}
222​
223const make = Effect.gen(function* () {
224 const host = yield* SourceControlHost.SourceControlHost;
225 const httpClient = yield* HttpClient.HttpClient;
226 const scope = yield* Effect.scope;
227​
228 const run = (input: Parameters<OriginCli["Service"]["execute"]>[0]) =>
229 host.process
230 .run({
231 operation: `CursorOrigin.${input.operation}`,
232 command: ORIGIN_COMMAND,
233 args: input.args,
234 cwd: input.cwd,
235 env: { NO_COLOR: "1" },
236 allowNonZeroExit: true,
237 timeoutMs: DEFAULT_TIMEOUT_MS,
238 maxOutputBytes: MAX_OUTPUT_BYTES,
239 outputMode: "error",
240 })
241 .pipe(
242 Effect.mapError((cause) => {
243 const missing =
244 cause._tag === "VcsProcessSpawnError" &&
245 cause.cause instanceof PlatformError.PlatformError &&
246 cause.cause.reason._tag === "NotFound";
247 return new OriginCliError({
248 operation: input.operation,
249 cwd: input.cwd,
250 reason: missing ? "missing-tool" : "failed",
251 detail: missing
252 ? "Cursor Origin CLI (`origin`) is required but not available on PATH."
253 : "Cursor Origin CLI could not be run.",
254 cause,
255 });
256 }),
257 );
258​
259 const execute: OriginCli["Service"]["execute"] = Effect.fn("OriginCli.execute")(
260 function* (input) {
261 const result = yield* run(input);
262 if (result.exitCode !== 0) return yield* classifyOriginFailure({ ...input, ...result });
263 return result.stdout;
264 },
265 );
266​
267 // The CLI's session token, kept a few minutes or until Origin refuses it. One read at a time, so a burst of
268 // requests on a cold server spawns the CLI once; a failed read is shared for a few seconds, so
269 // a burst while signed out does not queue one CLI process per request either.
270 const tokenLock = yield* Semaphore.make(1);
271 let token: Result.Result<Redacted.Redacted<string>, OriginCliError> | null = null;
272 let tokenExpiresAt = 0;
273 let viewerAccount: string | null = null;
274 let viewerExpiresAt = 0;
275 const currentToken = (cwd: string) =>
276 tokenLock.withPermits(1)(
277 Effect.gen(function* () {
278 const now = yield* Clock.currentTimeMillis;
279 if (token !== null && tokenExpiresAt > now) return yield* Effect.fromResult(token);
280 token = yield* execute({ cwd, operation: "authToken", args: ["auth", "token"] }).pipe(
281 Effect.flatMap((stdout) => {
282 const read = stdout.trim();
283 if (read.length === 0)
284 return Effect.fail(
285 new OriginCliError({
286 operation: "authToken",
287 cwd,
288 reason: "unauthenticated",
289 detail: UNAUTHENTICATED_DETAIL,
290 }),
291 );
292 return Effect.succeed(Redacted.make(read));
293 }),
294 Effect.result,
295 );
296 tokenExpiresAt =
297 (yield* Clock.currentTimeMillis) +
298 (Result.isSuccess(token) ? SESSION_TTL_MS : MISSING_TOKEN_TTL_MS);
299 return yield* Effect.fromResult(token);
300 }),
301 );
302 const forgetSession = (refused: Redacted.Redacted<string>) =>
303 tokenLock.withPermits(1)(
304 Effect.sync(() => {
305 // A late 401 from an old request must not discard another request's fresh token.
306 if (token !== null && Result.isSuccess(token) && token.success === refused) {
307 token = null;
308 viewerAccount = null;
309 }
310 }),
311 );
312​
313 const send = (input: OriginApiInput, bearer: string) => {
314 const request = HttpClientRequest.make(input.method ?? "GET")(
315 `${API_BASE_URL}${input.path}`,
316 ).pipe(HttpClientRequest.bearerToken(bearer), HttpClientRequest.acceptJson);
317 return httpClient
318 .execute(
319 input.body === undefined ? request : HttpClientRequest.bodyJsonUnsafe(request, input.body),
320 )
321 .pipe(
322 Effect.flatMap((response) =>
323 collectUint8StreamText({ stream: response.stream, maxBytes: MAX_OUTPUT_BYTES }).pipe(
324 Effect.map((collected) => ({ response, collected })),
325 ),
326 ),
327 Effect.timeout(DEFAULT_TIMEOUT_MS),
328 Effect.mapError(
329 (cause) =>
330 new OriginCliError({
331 operation: input.operation,
332 cwd: input.cwd,
333 reason: "failed",
334 detail: "Could not reach Cursor Origin.",
335 cause,
336 }),
337 ),
338 Effect.flatMap(({ response, collected }) =>
339 collected.truncated
340 ? Effect.fail(
341 new OriginCliError({
342 operation: input.operation,
343 cwd: input.cwd,
344 reason: "failed",
345 detail: "Cursor Origin sent a response too large to read.",
346 }),
347 )
348 : Effect.succeed({ response, body: collected.text }),
349 ),
350 );
351 };
352​
353 const api: OriginCli["Service"]["api"] = Effect.fn("OriginCli.api")(function* (input, schema) {
354 const bearer = yield* currentToken(input.cwd);
355 let exchange = yield* send(input, Redacted.value(bearer));
356 // A refused token may have been rotated by `origin auth login`; read it again once.
357 if (exchange.response.status === 401) {
358 yield* forgetSession(bearer);
359 exchange = yield* send(input, Redacted.value(yield* currentToken(input.cwd)));
360 }
361 if (exchange.response.status < 200 || exchange.response.status >= 300)
362 return yield* classifyOriginResponse({
363 operation: input.operation,
364 cwd: input.cwd,
365 status: exchange.response.status,
366 body: exchange.body,
367 headers: exchange.response.headers,
368 now: yield* Clock.currentTimeMillis,
369 });
370 const body = exchange.body.trim().length === 0 ? "{}" : exchange.body;
371 return yield* Schema.decodeEffect(Schema.fromJsonString(schema))(body).pipe(
372 Effect.mapError(
373 (cause) =>
374 new OriginCliError({
375 operation: input.operation,
376 cwd: input.cwd,
377 reason: "invalid-response",
378 detail: "Cursor Origin returned a response this version cannot read.",
379 cause,
380 }),
381 ),
382 );
383 });
384​
385 const authStatus = (cwd: string) =>
386 run({ cwd, operation: "authStatus", args: ["auth", "status", "--json"] }).pipe(
387 Effect.flatMap((result) => {
388 const status = parseOriginAuthStatus(result.stdout);
389 if (status !== null) return Effect.succeed(status);
390 return Effect.fail(
391 result.exitCode !== 0
392 ? classifyOriginFailure({ cwd, operation: "authStatus", ...result })
393 : new OriginCliError({
394 cwd,
395 operation: "authStatus",
396 reason: "invalid-response",
397 detail: "Cursor Origin returned an unreadable auth status.",
398 }),
399 );
400 }),
401 );
402​
403 // A session's first question is who is signed in, which the CLI answers in most of a second.
404 // The token read and the API connection's TLS handshake happen meanwhile, so the request that
405 // follows starts warm. The API's root takes no credentials and counts against no limit.
406 const warmUp = (cwd: string) =>
407 Effect.all(
408 [
409 currentToken(cwd),
410 httpClient.execute(HttpClientRequest.get(API_BASE_URL)).pipe(Effect.flatMap((r) => r.text)),
411 ],
412 { concurrency: "unbounded", discard: true },
413 ).pipe(Effect.timeout(DEFAULT_TIMEOUT_MS), Effect.ignore);
414​
415 const viewer: OriginCli["Service"]["viewer"] = Effect.fn("OriginCli.viewer")(function* (cwd) {
416 if (viewerAccount !== null && viewerExpiresAt > (yield* Clock.currentTimeMillis))
417 return viewerAccount;
418 yield* Effect.forkIn(warmUp(cwd), scope);
419 return yield* authStatus(cwd).pipe(
420 Effect.flatMap((status) => {
421 const account = originAccount(status);
422 if (account === null)
423 return Effect.fail(
424 new OriginCliError({
425 operation: "viewer",
426 cwd,
427 reason: "unauthenticated",
428 detail: UNAUTHENTICATED_DETAIL,
429 }),
430 );
431 viewerAccount = account;
432 return Clock.currentTimeMillis.pipe(
433 Effect.map((now) => {
434 viewerExpiresAt = now + SESSION_TTL_MS;
435 return account;
436 }),
437 );
438 }),
439 );
440 });
441​
442 const resolveRepository: OriginCli["Service"]["resolveRepository"] = Effect.fn(
443 "OriginCli.resolveRepository",
444 )(function* (input) {
445 const remoteUrl =
446 input.context?.remoteUrl ??
447 (yield* host.git.resolvePrimaryRemoteName(input.cwd).pipe(
448 Effect.flatMap((remote) => host.git.readConfigValue(input.cwd, `remote.${remote}.url`)),
449 Effect.orElseSucceed(() => null),
450 ));
451 const repository =
452 remoteUrl && parseGitRemoteHost(remoteUrl)?.hostname === CURSOR_ORIGIN_GIT_HOST
453 ? repositoryPathFromRemoteUrl(remoteUrl)
454 : null;
455 if (!repository)
456 return yield* new OriginCliError({
457 operation: "resolveRepository",
458 cwd: input.cwd,
459 reason: "not-found",
460 detail: "This checkout has no Cursor Origin remote.",
461 });
462 return repository;
463 });
464​
465 const personalNamespace: OriginCli["Service"]["personalNamespace"] = (cwd) =>
466 api(
467 { cwd, operation: "personalNamespace", path: "/v1/origin/namespaces" },
468 OriginNamespaceListSchema,
469 ).pipe(
470 Effect.flatMap((list) => {
471 const slug = list.namespaces?.find((entry) => entry.namespace.type === "user")?.namespace
472 .slug;
473 return slug
474 ? Effect.succeed(slug)
475 : Effect.fail(
476 new OriginCliError({
477 operation: "personalNamespace",
478 cwd,
479 reason: "not-found",
480 detail:
481 "This Cursor account has no Origin namespace. Claim one at cursor.com/codebase.",
482 }),
483 );
484 }),
485 );
486​
487 return OriginCli.of({ execute, api, viewer, personalNamespace, resolveRepository });
488});
489​
490/**
491 * Origin answers from a few hundred milliseconds away, so a new TLS connection doubles a request.
492 * Undici's default drops an idle connection after four seconds, which a person reading a pull
493 * request always outlasts; Origin keeps one open for minutes, and HTTP/2 carries a detail's
494 * parallel reads on it at once.
495 */
496const httpClientLayer = NodeHttpClient.layerUndiciNoDispatcher.pipe(
497 Layer.provide(
498 Layer.effect(NodeHttpClient.Dispatcher)(
499 Effect.acquireRelease(
500 Effect.sync(
501 () =>
502 new Agent({ allowH2: true, keepAliveTimeout: 300_000, keepAliveMaxTimeout: 300_000 }),
503 ),
504 (agent) => Effect.promise(() => agent.destroy()),
505 ),
506 ),
507 ),
508);
509​
510export const layer = Layer.effect(OriginCli, make).pipe(Layer.provide(httpClientLayer));