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

OriginCli.ts

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