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

OriginCli.ts

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