@devries-cameron20 / t3code-1 / commits / 9fcfd4c16e
Fork 0

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

feat(source-control): add Cursor Origin provider (#33093)

Co-authored-by: maria-rcks <254055478+maria-rcks@users.noreply.github.com>

maria committed Nov 9, 2026 at 06:12 UTC 9fcfd4c16e3ce82b67c6ccb02f5ef3aa26df3b8c
21 files changed +2611 -8
apps/mobile/assets/link-icons/cursor-origin.png
Binary files /dev/null and b/apps/mobile/assets/link-icons/cursor-origin.png differ
apps/mobile/src/lib/markdownLinkIcons.generated.ts
+1
@@ -3,6 +3,7 @@ import type { ImageSourcePropType } from "react-native";
3 export const SOURCE_CONTROL_LINK_ICON_SOURCES: Readonly<Record<string, ImageSourcePropType>> = {
4 "azure-devops": require("../../assets/link-icons/azure-devops.png"),
5 bitbucket: require("../../assets/link-icons/bitbucket.png"),
6 + "cursor-origin": require("../../assets/link-icons/cursor-origin.png"),
7 forgejo: require("../../assets/link-icons/forgejo.png"),
8 gitcafe: require("../../assets/link-icons/gitcafe.png"),
9 github: require("../../assets/link-icons/github.png"),
apps/server/package.json
+1
@@ -56,6 +56,7 @@
56 "@t3tools/source-control-azure-devops": "workspace:*",
57 "@t3tools/source-control-bitbucket": "workspace:*",
58 "@t3tools/source-control-core": "workspace:*",
59 + "@t3tools/source-control-cursor-origin": "workspace:*",
60 "@t3tools/source-control-definitions": "workspace:*",
61 "@t3tools/source-control-forgejo": "workspace:*",
62 "@t3tools/source-control-gitcafe": "workspace:*",
apps/server/src/sourceControl/sourceControlDefinitions.ts
+2
@@ -1,5 +1,6 @@
1 import * as AzureDevOpsDriver from "@t3tools/source-control-azure-devops/server/driver";
2 import * as BitbucketDriver from "@t3tools/source-control-bitbucket/server/driver";
3 +import * as CursorOriginDriver from "@t3tools/source-control-cursor-origin/server/driver";
4 import { builtInSourceControlDefinitions } from "@t3tools/source-control-definitions/registry";
5 import * as ForgejoDriver from "@t3tools/source-control-forgejo/server/driver";
6 import * as GitCafeDriver from "@t3tools/source-control-gitcafe/server/driver";
@@ -9,6 +10,7 @@ import * as GitLabDriver from "@t3tools/source-control-gitlab/server/driver";
10 /** In the shared registry's order, which is the order hosts are listed and probed in. */
11 export const BUILT_IN_SOURCE_CONTROL_DRIVER_LIST = [
12 GitHubDriver.driver,
13 + CursorOriginDriver.driver,
14 GitLabDriver.driver,
15 GitCafeDriver.driver,
16 ForgejoDriver.driver,
docs/user/source-control.md
+19 -5
@@ -1,7 +1,7 @@
1 # Source control
2
3 -T3 Code integrates with GitHub, GitLab, Forgejo, Gitea, Bitbucket, Azure DevOps, and GitCafe to clone
4 -and publish repositories, create pull requests, and review changes.
3 +T3 Code integrates with GitHub, GitLab, Forgejo, Gitea, Bitbucket, Azure DevOps, GitCafe, and Cursor
4 +Origin to clone and publish repositories, create pull requests, and review changes.
5
6 ## Review turn changes
7
@@ -129,6 +129,20 @@ sent to `git.cafe`; `CAFE_TOKEN` follows `CAFE_HOST` if you set it. Repositories
129 Line comments are not available for GitCafe pull requests yet.
130 Merging a stack lands it through GitCafe, and updating a branch restacks the layers above it.
131
132 +### Cursor Origin
133 +
134 +Install the [Origin CLI](https://cursor.com/docs/origin/cli) and sign in. Signing in also sets up Git
135 +credentials for `origin.cursor.com`:
136 +
137 +```bash
138 +curl -fsSL https://downloads.cursor.com/origin/install.sh | sh
139 +origin auth login
140 +```
141 +
142 +If cloning or pushing asks for a username, run `origin auth setup-git` to point Git at the CLI's
143 +credentials again. Origin repositories use HTTPS and are published privately. Repositories mirrored
144 +from GitHub keep their pull requests on GitHub; open those from the GitHub remote.
145 +
146 ## Start, clone, or publish a project
147
148 To start from nothing, choose **New project** in the command palette (`Cmd/Ctrl+K`), or
@@ -261,9 +275,9 @@ running count. A tick belongs to the pull request rather than to a commit, so sc
275 single commit keeps them. A file pushed to after you cleared it comes back marked **Changed**.
276
277 On GitHub these are GitHub's own viewed marks, so a review carries between T3 Code and github.com
264 -in either direction. Forgejo, GitLab, Bitbucket, and Azure DevOps expose no record T3 Code can read, so the
265 -server you are connected to keeps them instead: they follow you across the apps connected to that
266 -server, but the host's own site will not show them, and the count reads **viewed in T3 Code**.
278 +in either direction. Forgejo, GitLab, Bitbucket, Azure DevOps, and Cursor Origin expose no record
279 +T3 Code can read, so the server you are connected to keeps them instead: they follow you across the
280 +apps connected to that server, but the host's own site will not show them, and the count reads **viewed in T3 Code**.
281
282 On mobile, open a changed file and mark it viewed from its header. Viewed files collapse,
283 and their marks follow the same rules as on web and desktop.
package.json
+1 -1
@@ -34,7 +34,7 @@
34 "knip": "knip --preprocessor ./scripts/knip-schemas.ts",
35 "knip:check": "vp run knip:check:all",
36 "knip:check:files": "knip --include files,dependencies --no-config-hints",
37 - "knip:check:exports": "knip --workspace apps/server --workspace apps/desktop --workspace apps/web --workspace packages/client-runtime --workspace packages/contracts --workspace packages/effect-acp --workspace packages/effect-codex-app-server --workspace packages/shared --workspace packages/ssh --workspace packages/tailscale --workspace packages/provider-core --workspace packages/provider-acp --workspace packages/provider-acp-registry --workspace packages/provider-testing --workspace packages/provider-pi --workspace packages/provider-muse --workspace packages/provider-opencode --workspace packages/provider-cursor --workspace packages/provider-fx --workspace packages/provider-grok --workspace packages/provider-kiro --workspace packages/secret-provider-core --workspace packages/secret-provider-definitions --workspace packages/secret-provider-onepassword --workspace packages/source-control-core --workspace packages/source-control-definitions --workspace packages/source-control-azure-devops --workspace packages/source-control-bitbucket --workspace packages/source-control-forgejo --workspace packages/source-control-gitcafe --workspace packages/source-control-github --workspace packages/source-control-gitlab --workspace packages/source-control-testing --exports --preprocessor ./scripts/knip-schemas.ts --no-config-hints",
37 + "knip:check:exports": "knip --workspace apps/server --workspace apps/desktop --workspace apps/web --workspace packages/client-runtime --workspace packages/contracts --workspace packages/effect-acp --workspace packages/effect-codex-app-server --workspace packages/shared --workspace packages/ssh --workspace packages/tailscale --workspace packages/provider-core --workspace packages/provider-acp --workspace packages/provider-acp-registry --workspace packages/provider-testing --workspace packages/provider-pi --workspace packages/provider-muse --workspace packages/provider-opencode --workspace packages/provider-cursor --workspace packages/provider-fx --workspace packages/provider-grok --workspace packages/provider-kiro --workspace packages/secret-provider-core --workspace packages/secret-provider-definitions --workspace packages/secret-provider-onepassword --workspace packages/source-control-core --workspace packages/source-control-cursor-origin --workspace packages/source-control-definitions --workspace packages/source-control-azure-devops --workspace packages/source-control-bitbucket --workspace packages/source-control-forgejo --workspace packages/source-control-gitcafe --workspace packages/source-control-github --workspace packages/source-control-gitlab --workspace packages/source-control-testing --exports --preprocessor ./scripts/knip-schemas.ts --no-config-hints",
38 "knip:production": "knip --production --preprocessor ./scripts/knip-schemas.ts",
39 "lint:mobile": "node scripts/mobile-native-static-check.ts",
40 "mobile:install": "node scripts/mobile-native-client.ts ensure",
packages/client-runtime/src/sourceControlClients.test.ts
+22
@@ -38,6 +38,27 @@ describe("sourceControlClients.parseChangeRequestUrl", () => {
38 });
39 });
40
41 + it("reads a Cursor Origin pull request under Origin's git host, not as GitHub's /pull/", () => {
42 + for (const url of [
43 + "https://cursor.com/codebase/Acme.Team/Web-App/pull/42",
44 + "http://www.cursor.com/codebase/Acme.Team/Web-App/pull/42/files?w=1#diff",
45 + ]) {
46 + expect(parse(url), url).toEqual({
47 + host: "origin.cursor.com",
48 + repository: "acme.team/web-app",
49 + number: 42,
50 + });
51 + expect(kindOf(url), url).toBe("cursor-origin");
52 + }
53 + expect(
54 + sourceControlClients.parseChangeRequestUrl("https://cursor.com/codebase/acme/web/pull/42")
55 + ?.link.repositoryUrl,
56 + ).toBe("https://cursor.com/codebase/acme/web");
57 + expect(parse("https://cursor.com/codebase/acme/web")).toBeNull();
58 + expect(kindOf("https://www.cursor.com/updates/pull/42")).toBeUndefined();
59 + expect(kindOf("https://github.com/acme/web/pull/42")).toBe("github");
60 + });
61 +
62 it("reads Forgejo URLs even when the hostname contains github", () => {
63 expect(parse("https://github.internal/team/repo/pulls/7")).toEqual({
64 host: "github.internal",
@@ -254,6 +275,7 @@ describe("sourceControlClients.recognizeRemote", () => {
275 expect(kindOfRemote("https://bitbucket.gitlab.example/o/r")).toBe("gitlab");
276 expect(kindOfRemote("https://bitbucket.visualstudio.com/p/_git/r")).toBe("azure-devops");
277 expect(kindOfRemote("git@git.cafe:pingdotgg/t3code.git")).toBe("gitcafe");
278 + expect(kindOfRemote("https://origin.cursor.com/acme/web.git")).toBe("cursor-origin");
279 });
280
281 it("reads a remote no host claims as an unknown host, and a local path as no host", () => {
packages/source-control-cursor-origin/package.json new
+32
@@ -0,0 +1,32 @@
1 +{
2 + "name": "@t3tools/source-control-cursor-origin",
3 + "private": true,
4 + "type": "module",
5 + "exports": {
6 + "./shared/definition": {
7 + "types": "./src/shared/definition.ts",
8 + "import": "./src/shared/definition.ts"
9 + },
10 + "./server/driver": {
11 + "types": "./src/server/driver.ts",
12 + "import": "./src/server/driver.ts"
13 + }
14 + },
15 + "scripts": {
16 + "typecheck": "effect-tsgo tsrs --noEmit",
17 + "test": "vp test run --config ../../vite.config.ts --dir ."
18 + },
19 + "dependencies": {
20 + "@effect/platform-node": "catalog:",
21 + "@t3tools/contracts": "workspace:*",
22 + "@t3tools/provider-core": "workspace:*",
23 + "@t3tools/shared": "workspace:*",
24 + "@t3tools/source-control-core": "workspace:*",
25 + "effect": "catalog:"
26 + },
27 + "devDependencies": {
28 + "@effect/vitest": "catalog:",
29 + "@types/node": "catalog:",
30 + "vite-plus": "catalog:"
31 + }
32 +}
packages/source-control-cursor-origin/src/server/OriginCli.ts new
+510
@@ -0,0 +1,510 @@
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 + */
6 +import * as Clock from "effect/Clock";
7 +import * as Context from "effect/Context";
8 +import * as Effect from "effect/Effect";
9 +import * as Layer from "effect/Layer";
10 +import * as PlatformError from "effect/PlatformError";
11 +import * as Redacted from "effect/Redacted";
12 +import * as Result from "effect/Result";
13 +import * as Schema from "effect/Schema";
14 +import * as Semaphore from "effect/Semaphore";
15 +import { HttpClient, HttpClientRequest } from "effect/http";
16 +import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient";
17 +import { Agent } from "@effect/platform-node/Undici";
18 +import { collectUint8StreamText } from "@t3tools/provider-core/server/collectStreamText";
19 +import { decodeJsonResult } from "@t3tools/shared/schemaJson";
20 +import { parseGitRemoteHost } from "@t3tools/source-control-core/shared/definition";
21 +import { CURSOR_ORIGIN_GIT_HOST } from "../shared/definition.ts";
22 +import { retryAtFromHeader } from "@t3tools/source-control-core/server/SourceControlRateLimit";
23 +import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
24 +import type { SourceControlProviderContext } from "@t3tools/source-control-core/server/SourceControlProvider";
25 +import { repositoryPathFromRemoteUrl } from "@t3tools/source-control-core/server/SourceControlProvider";
26 +
27 +const DEFAULT_TIMEOUT_MS = 30_000;
28 +const 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. */
30 +const SESSION_TTL_MS = 5 * 60_000;
31 +const MAX_OUTPUT_BYTES = 8_000_000;
32 +const API_BASE_URL = "https://api.cursor.com";
33 +
34 +export const ORIGIN_COMMAND = "origin";
35 +
36 +export 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 + }
56 +}
57 +
58 +/** What `origin auth status --json` reports. Only the fields this package reads. */
59 +const 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 +});
66 +type OriginAuthStatus = typeof OriginAuthStatusSchema.Type;
67 +
68 +export function parseOriginAuthStatus(raw: string): OriginAuthStatus | null {
69 + const decoded = decodeJsonResult(OriginAuthStatusSchema)(raw);
70 + return Result.isSuccess(decoded) ? decoded.success : null;
71 +}
72 +
73 +/** The signed-in account's email, which is what `origin auth status` names it by. */
74 +export function originAccount(status: OriginAuthStatus | null): string | null {
75 + if (!status?.authenticated || status.tokenValid === false) return null;
76 + return status.account?.email?.trim() || null;
77 +}
78 +
79 +const 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. */
90 +export function originRepositoryPath(repository: string): string {
91 + return `/v1/origin/repos/${repository.split("/").map(encodeURIComponent).join("/")}`;
92 +}
93 +
94 +/** The message an Origin error body carries, Connect-style or REST-style. */
95 +function 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;
107 +}
108 +
109 +const 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. */
113 +function 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 + });
147 +}
148 +
149 +/** A non-2xx API response. */
150 +function 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 + });
186 +}
187 +
188 +interface 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;
195 +}
196 +
197 +export 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 +
223 +const 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 + */
496 +const 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 +
510 +export const layer = Layer.effect(OriginCli, make).pipe(Layer.provide(httpClientLayer));
packages/source-control-cursor-origin/src/server/OriginPullRequestProvider.ts new
+1016
@@ -0,0 +1,1016 @@
1 +import * as Cache from "effect/Cache";
2 +import * as Effect from "effect/Effect";
3 +import * as Exit from "effect/Exit";
4 +import * as Fiber from "effect/Fiber";
5 +import * as Hash from "effect/Hash";
6 +import * as Option from "effect/Option";
7 +import * as Result from "effect/Result";
8 +import * as Schema from "effect/Schema";
9 +import type {
10 + PullRequestCapabilities,
11 + PullRequestComment,
12 + PullRequestMergeability,
13 + PullRequestReviewThread,
14 + PullRequestViewerPermissions,
15 +} from "@t3tools/contracts";
16 +import { SourceControlProviderKind } from "@t3tools/contracts";
17 +import {
18 + PullRequestProviderError,
19 + type ProviderChangeRequest,
20 + type ProviderChangeRequestActivity,
21 + type ProviderChangeRequestDetail,
22 + type ProviderRepositoryRef,
23 + type PullRequestProviderApi,
24 +} from "@t3tools/source-control-core/server/PullRequestProvider";
25 +
26 +import * as OriginCli from "./OriginCli.ts";
27 +import {
28 + checksState,
29 + originActor,
30 + originActorId,
31 + originAvatars,
32 + originCheck,
33 + OriginGitRefSchema,
34 + OriginMergeabilitySchema,
35 + preparedMergeability,
36 + OriginCheckRunListSchema,
37 + OriginCommentListSchema,
38 + OriginCommitListSchema,
39 + OriginFileListSchema,
40 + originFilesPatch,
41 + OriginPullRequestListSchema,
42 + OriginPullRequestSchema,
43 + OriginRepositorySchema,
44 + OriginReviewListSchema,
45 + originState,
46 + originUpdatedAt,
47 + type OriginAvatars,
48 + type OriginComment,
49 + type OriginPullRequest,
50 + UNKNOWN_TIME,
51 +} from "./originPullRequests.ts";
52 +
53 +const CAPABILITIES: PullRequestCapabilities = {
54 + diff: true,
55 + comment: true,
56 + actions: ["merge", "ready", "draft", "close", "reopen"],
57 + // Origin merges with a merge commit or a squash; it has no rebase merge.
58 + mergeMethods: ["merge", "squash"],
59 + search: false,
60 + reactions: false,
61 + review: {
62 + inlineComment: true,
63 + reply: true,
64 + resolve: true,
65 + verdicts: ["comment", "approve", "request-changes"],
66 + },
67 + // Origin can request reviewers, but lists no candidates to pick from.
68 + reviewers: { request: false, listCandidates: false },
69 + edit: { changeRequest: true, comment: true },
70 +};
71 +
72 +/**
73 + * Origin reports no per-viewer permission on a pull request, so everything the host can do is
74 + * offered and Origin explains any refusal itself.
75 + */
76 +const VIEWER_PERMISSIONS: PullRequestViewerPermissions = {
77 + actions: CAPABILITIES.actions,
78 + comment: true,
79 + resolve: true,
80 + verdicts: CAPABILITIES.review.verdicts,
81 + requestReviewers: false,
82 +};
83 +
84 +const PAGE_SIZE = 100;
85 +const EXPIRED_LIST_POSITION = "listChangeRequests.resume";
86 +/** Bounds each paged read, so one very long pull request cannot stall its detail. */
87 +const MAX_PAGES = 10;
88 +
89 +const unsupported = (operation: string, detail: string) =>
90 + Effect.fail(
91 + new PullRequestProviderError({
92 + provider: SourceControlProviderKind.make("cursor-origin"),
93 + operation,
94 + reason: "failed",
95 + detail,
96 + }),
97 + );
98 +
99 +function toProviderChangeRequest(pullRequest: OriginPullRequest, avatars?: OriginAvatars) {
100 + return {
101 + number: pullRequest.number,
102 + title: pullRequest.title,
103 + url: pullRequest.webUrl,
104 + author: originActor(pullRequest.author, avatars),
105 + headBranch: pullRequest.head.ref,
106 + baseBranch: pullRequest.base.ref,
107 + state: originState(pullRequest),
108 + isDraft: pullRequest.draft === true,
109 + // A listing cannot afford the base comparison the detail makes, so it does not guess.
110 + mergeability: "unknown",
111 + additions: pullRequest.additions ?? 0,
112 + deletions: pullRequest.deletions ?? 0,
113 + createdAt: pullRequest.createdAt?.trim() || originUpdatedAt(pullRequest),
114 + closedAt: pullRequest.closedAt?.trim() || null,
115 + mergedAt: pullRequest.mergedAt?.trim() || null,
116 + updatedAt: originUpdatedAt(pullRequest),
117 + reviewRequestLogins: [],
118 + labels: (pullRequest.labels ?? []).map((label) => ({
119 + name: label.name,
120 + color: label.color?.replace(/^#/u, "") || "888888",
121 + description: label.description ?? null,
122 + })),
123 + } satisfies ProviderChangeRequest;
124 +}
125 +
126 +const isThreadComment = (comment: OriginComment) => Boolean(comment.thread?.path);
127 +const editedAt = (comment: OriginComment) =>
128 + comment.updatedAt && comment.updatedAt !== comment.createdAt ? comment.updatedAt : null;
129 +
130 +function toThreads(
131 + comments: ReadonlyArray<OriginComment>,
132 + avatars: OriginAvatars,
133 + headSha: string | null,
134 +): PullRequestReviewThread[] {
135 + const threads = new Map<string, PullRequestReviewThread>();
136 + for (const comment of comments) {
137 + const thread = comment.thread;
138 + if (!thread?.path) continue;
139 + const line = thread.endLine ?? thread.startLine ?? null;
140 + const existing = threads.get(thread.id) ?? {
141 + id: thread.id,
142 + path: thread.path,
143 + line: line !== null && line > 0 ? line : null,
144 + side: thread.side === "left" ? ("left" as const) : ("right" as const),
145 + isResolved: Boolean(thread.resolvedAt),
146 + // Origin anchors a thread to the version it was left on and does not move it forward.
147 + isOutdated: Boolean(headSha && thread.version?.headSha && thread.version.headSha !== headSha),
148 + comments: [],
149 + };
150 + threads.set(thread.id, {
151 + ...existing,
152 + comments: [
153 + ...existing.comments,
154 + {
155 + id: comment.id,
156 + author: originActor(comment.author, avatars),
157 + body: comment.body ?? "",
158 + createdAt: comment.createdAt,
159 + editedAt: editedAt(comment),
160 + url: null,
161 + },
162 + ],
163 + });
164 + }
165 + return [...threads.values()];
166 +}
167 +
168 +export const make = Effect.gen(function* () {
169 + const cli = yield* OriginCli.OriginCli;
170 + const scope = yield* Effect.scope;
171 +
172 + const fail = (operation: string) => (error: OriginCli.OriginCliError) =>
173 + new PullRequestProviderError({
174 + provider: SourceControlProviderKind.make("cursor-origin"),
175 + operation,
176 + reason: error.reason === "invalid-response" ? "failed" : error.reason,
177 + ...(error.retryAt === undefined ? {} : { retryAt: error.retryAt }),
178 + detail: error.detail,
179 + cause: error,
180 + });
181 +
182 + // A repository's merge settings change rarely, and every detail read asks for them.
183 + const repositorySettings = yield* Cache.makeWith(
184 + (key: string) => {
185 + const [cwd = "", repository = ""] = key.split("\n");
186 + return recover(
187 + cli.api(
188 + { cwd, operation: "getRepository", path: OriginCli.originRepositoryPath(repository) },
189 + OriginRepositorySchema,
190 + ),
191 + null,
192 + );
193 + },
194 + {
195 + capacity: 64,
196 + timeToLive: (exit) => (Exit.isSuccess(exit) && exit.value !== null ? "5 minutes" : 0),
197 + },
198 + );
199 + const getRepositorySettings = (cwd: string, repository: string) =>
200 + Cache.get(repositorySettings, `${cwd}\n${repository}`);
201 +
202 + const pullPath = (repository: string, number: number, suffix = "") =>
203 + `${OriginCli.originRepositoryPath(repository)}/pulls/${number}${suffix}`;
204 +
205 + // The last version of each pull request a listing or a read returned, most recent last. Reads
206 + // that hang off its head and base start from it alongside the fresh read of the pull request,
207 + // and are redone only when it has moved since.
208 + const lastSeen = new Map<string, OriginPullRequest>();
209 + const remember = (key: string, pullRequest: OriginPullRequest) => {
210 + lastSeen.delete(key);
211 + lastSeen.set(key, pullRequest);
212 + if (lastSeen.size > 1024) lastSeen.delete(lastSeen.keys().next().value ?? "");
213 + };
214 + const sameBasis = (seen: OriginPullRequest, current: OriginPullRequest) =>
215 + seen.head.sha === current.head.sha &&
216 + seen.base.ref === current.base.ref &&
217 + seen.base.sha === current.base.sha &&
218 + seen.version?.headSha === current.version?.headSha &&
219 + seen.version?.baseSha === current.version?.baseSha &&
220 + seen.version?.potentialMergeCommit?.baseSha ===
221 + current.version?.potentialMergeCommit?.baseSha &&
222 + seen.version?.potentialMergeCommit?.state === current.version?.potentialMergeCommit?.state &&
223 + seen.draft === current.draft &&
224 + originState(seen) === originState(current);
225 +
226 + // Opening a pull request reads its detail and its checks at once, and both start from the pull
227 + // request itself. Reads within a second share one request; this package's own writes drop it.
228 + const pullKey = (input: ProviderRepositoryRef & { readonly number: number }) =>
229 + `${input.cwd}\n${input.repository}\n${input.number}`;
230 + const pulls = yield* Cache.makeWith(
231 + (key: string) => {
232 + const [cwd = "", repository = "", number = ""] = key.split("\n");
233 + return cli
234 + .api(
235 + { cwd, operation: "getPullRequest", path: pullPath(repository, Number(number)) },
236 + OriginPullRequestSchema,
237 + )
238 + .pipe(Effect.tap((pullRequest) => Effect.sync(() => remember(key, pullRequest))));
239 + },
240 + { capacity: 256, timeToLive: (exit) => (Exit.isSuccess(exit) ? "1 second" : 0) },
241 + );
242 + const getPull = (input: ProviderRepositoryRef & { readonly number: number }) =>
243 + Cache.get(pulls, pullKey(input));
244 + const forgetPull = (input: ProviderRepositoryRef & { readonly number: number }) =>
245 + Cache.invalidate(pulls, pullKey(input)).pipe(
246 + Effect.andThen(Effect.sync(() => lastSeen.delete(pullKey(input)))),
247 + );
248 +
249 + /** `dependents` of the fresh pull request, started early from the last-seen version. */
250 + const withPull = Effect.fn("OriginPullRequestProvider.withPull")(function* <A>(
251 + input: ProviderRepositoryRef & { readonly number: number },
252 + dependents: (pullRequest: OriginPullRequest) => Effect.Effect<A, OriginCli.OriginCliError>,
253 + ) {
254 + const seen = lastSeen.get(pullKey(input));
255 + const [pullRequest, early] = yield* Effect.all(
256 + [
257 + getPull(input),
258 + seen === undefined ? Effect.succeedNone : Effect.asSome(Effect.result(dependents(seen))),
259 + ],
260 + { concurrency: "unbounded" },
261 + );
262 + if (seen !== undefined && Option.isSome(early)) {
263 + const guess = early.value;
264 + // A refused or rate-limited account fails the fresh read too; asking again spends quota.
265 + if (
266 + Result.isFailure(guess) &&
267 + (guess.failure.reason === "rate-limited" || guess.failure.reason === "unauthenticated")
268 + )
269 + return yield* guess.failure;
270 + // A guess that fails, say for a head since force-pushed away, is only a missed head start.
271 + if (sameBasis(seen, pullRequest))
272 + return [pullRequest, yield* Effect.fromResult(guess)] as const;
273 + }
274 + return [pullRequest, yield* dependents(pullRequest)] as const;
275 + });
276 +
277 + /** Reads every page of a list endpoint, up to `MAX_PAGES`. */
278 + const readPages = Effect.fn("OriginPullRequestProvider.readPages")(function* <
279 + S extends Schema.Codec<
280 + { readonly nextPageToken?: string | null | undefined },
281 + unknown,
282 + never,
283 + never
284 + >,
285 + A,
286 + >(
287 + input: { readonly cwd: string; readonly operation: string; readonly path: string },
288 + schema: S,
289 + items: (page: S["Type"]) => ReadonlyArray<A> | null | undefined,
290 + ) {
291 + const all: A[] = [];
292 + const tokens = new Set<string>();
293 + let token: string | null | undefined;
294 + for (let page = 0; page < MAX_PAGES; page++) {
295 + const query = new URLSearchParams({
296 + pageSize: String(PAGE_SIZE),
297 + ...(token ? { pageToken: token } : {}),
298 + });
299 + const result = yield* cli.api({ ...input, path: `${input.path}?${query}` }, schema);
300 + all.push(...(items(result) ?? []));
301 + token = result.nextPageToken;
302 + if (!token) return { items: all, truncated: false };
303 + // A page token seen before would only read the same pages again.
304 + if (tokens.has(token)) return { items: all, truncated: true };
305 + tokens.add(token);
306 + }
307 + return { items: all, truncated: true };
308 + });
309 +
310 + // The detail and the checks tab both list the head commit's check runs, usually together.
311 + const checkRuns = yield* Cache.makeWith(
312 + (key: string) => {
313 + const [cwd = "", repository = "", sha = ""] = key.split("\n");
314 + return readPages(
315 + {
316 + cwd,
317 + operation: "listChecks",
318 + path: `${OriginCli.originRepositoryPath(repository)}/commits/${encodeURIComponent(sha)}/check-runs`,
319 + },
320 + OriginCheckRunListSchema,
321 + (page) => page.checkRuns,
322 + ).pipe(
323 + Effect.map((page) => ({ checks: page.items.map(originCheck), truncated: page.truncated })),
324 + );
325 + },
326 + { capacity: 256, timeToLive: (exit) => (Exit.isSuccess(exit) ? "1 second" : 0) },
327 + );
328 + const listChecks = (
329 + input: ProviderRepositoryRef & { readonly sha: string | null | undefined },
330 + ) =>
331 + input.sha
332 + ? Cache.get(checkRuns, `${input.cwd}\n${input.repository}\n${input.sha}`)
333 + : Effect.succeed({ checks: [], truncated: false });
334 +
335 + const readPatch = (cwd: string, path: string) =>
336 + readPages({ cwd, operation: "getDiff", path }, OriginFileListSchema, (page) => page.files).pipe(
337 + Effect.map((page) => ({
338 + patch: originFilesPatch(page.items),
339 + // Origin leaves out the hunks of files too large to show.
340 + truncated: page.truncated || page.items.some((file) => file.patch == null),
341 + nextCursor: null,
342 + })),
343 + );
344 + const versionKey = (pullRequest: OriginPullRequest) => {
345 + const head = pullRequest.version?.headSha ?? pullRequest.head.sha;
346 + const base = pullRequest.version?.baseSha ?? pullRequest.base.sha;
347 + return head && base ? `${base}...${head}` : null;
348 + };
349 + // Keyed by `cwd, repository, number, base...head` for a pull request's patch, or by
350 + // `cwd, repository, , commit` for one commit's.
351 + const patches = yield* Cache.makeWith(
352 + (key: string) => {
353 + const [cwd = "", repository = "", number = "", commits = ""] = key.split("\n");
354 + if (number === "")
355 + return readPatch(
356 + cwd,
357 + `${OriginCli.originRepositoryPath(repository)}/commits/${encodeURIComponent(commits)}/files`,
358 + ).pipe(Effect.map((patch) => ({ ...patch, pinned: true })));
359 + // `/files` always answers for the newest version, so a push during the read must not be
360 + // kept under the version the key names.
361 + return readPatch(cwd, pullPath(repository, Number(number), "/files")).pipe(
362 + Effect.flatMap((patch) =>
363 + recover(
364 + cli
365 + .api(
366 + { cwd, operation: "getPullRequest", path: pullPath(repository, Number(number)) },
367 + OriginPullRequestSchema,
368 + )
369 + .pipe(Effect.map(versionKey)),
370 + null,
371 + ).pipe(Effect.map((version) => ({ ...patch, pinned: version === commits }))),
372 + ),
373 + );
374 + },
375 + {
376 + capacity: 64,
377 + timeToLive: (exit) => (Exit.isSuccess(exit) && exit.value.pinned ? "1 hour" : 0),
378 + },
379 + );
380 +
381 + // Every pull request into a branch compares against the same tip, so it is read once a moment.
382 + const baseTips = yield* Cache.makeWith(
383 + (key: string) => {
384 + const [cwd = "", repository = "", branch = ""] = key.split("\n");
385 + return cli
386 + .api(
387 + {
388 + cwd,
389 + operation: "getBaseTip",
390 + path: `${OriginCli.originRepositoryPath(repository)}/git/ref/${encodeURIComponent(`heads/${branch}`)}`,
391 + },
392 + OriginGitRefSchema,
393 + )
394 + .pipe(Effect.map((ref) => ref.object?.sha ?? null));
395 + },
396 + { capacity: 64, timeToLive: (exit) => (Exit.isSuccess(exit) ? "2 seconds" : 0) },
397 + );
398 +
399 + // Whether a head merges cleanly into a base never changes, and `/mergeability` counts ten times
400 + // against the rate limit, so a definite answer is kept for that pair of commits.
401 + const mergeabilities = yield* Cache.makeWith(
402 + (key: string) => {
403 + const [cwd = "", repository = "", number = "", head = ""] = key.split("\n");
404 + return cli
405 + .api(
406 + {
407 + cwd,
408 + operation: "getMergeability",
409 + path: pullPath(
410 + repository,
411 + Number(number),
412 + `/mergeability?${new URLSearchParams({ expectedHeadSha: head })}`,
413 + ),
414 + },
415 + OriginMergeabilitySchema,
416 + )
417 + .pipe(
418 + Effect.map((answer): PullRequestMergeability =>
419 + // A head pushed since the key was made answers for other commits.
420 + answer.headSha && answer.headSha !== head
421 + ? "unknown"
422 + : (answer.blockers ?? []).some((blocker) => blocker.kind === "merge_conflict")
423 + ? "conflicting"
424 + : answer.verdict === "mergeable"
425 + ? "mergeable"
426 + : "unknown",
427 + ),
428 + );
429 + },
430 + {
431 + capacity: 256,
432 + timeToLive: (exit) => (Exit.isSuccess(exit) && exit.value !== "unknown" ? "1 hour" : 0),
433 + },
434 + );
435 +
436 + /**
437 + * Origin prepares a merge for every version, against the base as it stood then. While that is
438 + * still the base's tip, the prepared merge is the answer, for one ref read; once the base has
439 + * moved, only `/mergeability` knows.
440 + */
441 + const mergeabilityOf = (
442 + input: ProviderRepositoryRef & { readonly number: number },
443 + pullRequest: OriginPullRequest,
444 + ): Effect.Effect<PullRequestMergeability, OriginCli.OriginCliError> => {
445 + if (originState(pullRequest) !== "open" || !pullRequest.head.sha)
446 + return Effect.succeed("unknown");
447 + return recover(
448 + Cache.get(baseTips, `${input.cwd}\n${input.repository}\n${pullRequest.base.ref}`),
449 + null,
450 + ).pipe(
451 + // Without the base's tip there is nothing to judge a merge against.
452 + Effect.flatMap((tip) =>
453 + tip === null
454 + ? Effect.succeed("unknown" as const)
455 + : tip ===
456 + (pullRequest.version?.potentialMergeCommit?.baseSha ?? pullRequest.version?.baseSha)
457 + ? Effect.succeed(preparedMergeability(pullRequest))
458 + : recover(
459 + Cache.get(
460 + mergeabilities,
461 + `${input.cwd}\n${input.repository}\n${input.number}\n${pullRequest.head.sha}\n${tip}\n${pullRequest.base.ref}`,
462 + ),
463 + "unknown",
464 + ),
465 + ),
466 + );
467 + };
468 +
469 + // Avatars only change when someone replaces their picture, so each actor's is read once per
470 + // server. An actor the CLI reports without one is cached as "" so it is not asked about again.
471 + const avatarCache = new Map<string, string>();
472 + let avatarRead: Fiber.Fiber<OriginAvatars> | null = null;
473 + const avatarsFor = Effect.fn("OriginPullRequestProvider.avatarsFor")(function* (
474 + cwd: string,
475 + actors: ReadonlyArray<Parameters<typeof originActorId>[0]>,
476 + args: ReadonlyArray<string>,
477 + ) {
478 + if (
479 + actors.every((actor) => {
480 + const id = originActorId(actor);
481 + return id === null || avatarCache.has(id);
482 + })
483 + )
484 + return avatarCache;
485 + if (avatarRead !== null) yield* Fiber.join(avatarRead);
486 + const missing = actors
487 + .map(originActorId)
488 + .filter((id): id is string => id !== null && !avatarCache.has(id));
489 + return missing.length > 0 ? yield* readAvatars(cwd, args, missing) : avatarCache;
490 + });
491 + const readAvatars = (
492 + cwd: string,
493 + args: ReadonlyArray<string>,
494 + ids: ReadonlyArray<string> = [],
495 + ): Effect.Effect<OriginAvatars> =>
496 + cli.execute({ cwd, operation: "readAvatars", args }).pipe(
497 + Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(Schema.Unknown))),
498 + Effect.map((json) => {
499 + for (const [id, url] of originAvatars(json)) avatarCache.set(id, url);
500 + for (const id of ids) if (!avatarCache.has(id)) avatarCache.set(id, "");
501 + return avatarCache;
502 + }),
503 + // A picture is decoration: a failed read leaves initials rather than failing the page.
504 + Effect.orElseSucceed(() => avatarCache),
505 + );
506 + const initialAvatars = Effect.fnUntraced(function* (cwd: string, args: ReadonlyArray<string>) {
507 + if (avatarCache.size > 0) return avatarCache;
508 + if (avatarRead === null)
509 + avatarRead = yield* Effect.forkIn(
510 + readAvatars(cwd, args).pipe(
511 + Effect.ensuring(
512 + Effect.sync(() => {
513 + avatarRead = null;
514 + }),
515 + ),
516 + ),
517 + scope,
518 + );
519 + return yield* Fiber.join(avatarRead);
520 + });
521 +
522 + /** `origin pr view` arguments that print `fields` for one pull request, avatars included. */
523 + const viewArgs = (
524 + input: { readonly repository: string; readonly number: number },
525 + fields: string,
526 + ) => ["pr", "view", String(input.number), "-R", input.repository, "--json", fields];
527 +
528 + // Nothing reads a write's answer, so it is not decoded: a body this version cannot read must not
529 + // turn a write that landed into a failure the user retries.
530 + const write = (
531 + input: { readonly cwd: string },
532 + operation: string,
533 + method: "POST" | "PATCH",
534 + path: string,
535 + body: unknown,
536 + ) =>
537 + cli
538 + .api({ cwd: input.cwd, operation, method, path, body }, Schema.Unknown)
539 + .pipe(Effect.asVoid, Effect.mapError(fail(operation)));
540 +
541 + const recover = <A>(
542 + read: Effect.Effect<A, OriginCli.OriginCliError>,
543 + fallback: A,
544 + keepNotFound = false,
545 + ) =>
546 + read.pipe(
547 + Effect.catchIf(
548 + (error) =>
549 + error.reason !== "rate-limited" &&
550 + error.reason !== "unauthenticated" &&
551 + !(keepNotFound && error.reason === "not-found"),
552 + () => Effect.succeed(fallback),
553 + ),
554 + );
555 +
556 + // Origin pages by a token longer than the service's cursor can carry, so the cursor names it by
557 + // hash. A cursor from before a restart, or one evicted since, fails and asks for a refresh.
558 + const pageTokens = new Map<string, string>();
559 + const pageTokenKey = (token: string) => {
560 + const key = `${(Hash.string(token) >>> 0).toString(36)}-${token.length}`;
561 + pageTokens.delete(key);
562 + pageTokens.set(key, token);
563 + if (pageTokens.size > 256) pageTokens.delete(pageTokens.keys().next().value ?? "");
564 + return key;
565 + };
566 +
567 + // Origin merges a stacked pull request together with every open one below it, which the panel
568 + // does not show, so those merges are left to Origin.
569 + const refuseStackedMerge = Effect.fn("OriginPullRequestProvider.refuseStackedMerge")(function* (
570 + input: ProviderRepositoryRef & { readonly number: number },
571 + ) {
572 + const read = (number: number) =>
573 + getPull({ ...input, number }).pipe(Effect.mapError(fail("runAction")));
574 + const parent = (yield* read(input.number)).stack?.parentPullRequest?.number;
575 + if (parent == null) return;
576 + if (originState(yield* read(Number(parent))) !== "open") return;
577 + return yield* unsupported(
578 + "runAction",
579 + `This pull request is stacked on #${parent}. Merge #${parent} first, or merge the stack on Cursor Origin.`,
580 + );
581 + });
582 +
583 + const provider: PullRequestProviderApi = {
584 + kind: SourceControlProviderKind.make("cursor-origin"),
585 + capabilities: CAPABILITIES,
586 +
587 + getViewer: Effect.fn("OriginPullRequestProvider.getViewer")(
588 + function* (input) {
589 + if (avatarCache.size === 0 && avatarRead === null) {
590 + // The first list follows sign-in, so its pictures can be read while sign-in is checked.
591 + yield* Effect.forkIn(
592 + cli.resolveRepository({ cwd: input.cwd }).pipe(
593 + Effect.flatMap((repository) =>
594 + initialAvatars(input.cwd, [
595 + "pr",
596 + "list",
597 + "-R",
598 + repository,
599 + "-s",
600 + "all",
601 + "-L",
602 + String(PAGE_SIZE),
603 + "--json",
604 + "author",
605 + ]),
606 + ),
607 + Effect.ignore,
608 + ),
609 + scope,
610 + );
611 + }
612 + return yield* cli.viewer(input.cwd);
613 + },
614 + Effect.mapError(fail("getViewer")),
615 + ),
616 +
617 + listChangeRequests: Effect.fn("OriginPullRequestProvider.listChangeRequests")(
618 + function* (input) {
619 + const limit = Math.min(Math.max(input.limit, 1), PAGE_SIZE);
620 + const resume = input.cursor?.resumeAfter;
621 + const pageToken = resume === undefined ? undefined : pageTokens.get(resume);
622 + if (resume !== undefined && pageToken === undefined)
623 + return yield* new OriginCli.OriginCliError({
624 + operation: EXPIRED_LIST_POSITION,
625 + cwd: input.cwd,
626 + reason: "failed",
627 + detail: "This list position has expired. Refresh the list to load more pull requests.",
628 + });
629 + const query = new URLSearchParams({
630 + state: input.state,
631 + pageSize: String(limit),
632 + sortBy: "updated",
633 + ...(input.involvement === "authored" ? { author: input.viewer } : {}),
634 + ...(pageToken === undefined ? {} : { pageToken }),
635 + });
636 + const avatarArgs = [
637 + "pr",
638 + "list",
639 + "-R",
640 + input.repository,
641 + "-s",
642 + input.state,
643 + "-L",
644 + String(limit),
645 + "--json",
646 + "author",
647 + ];
648 + // Share a sign-in's read, or start the pictures alongside the first list.
649 + const [page] = yield* Effect.all(
650 + [
651 + cli.api(
652 + {
653 + cwd: input.cwd,
654 + operation: "listChangeRequests",
655 + path: `${OriginCli.originRepositoryPath(input.repository)}/pulls?${query}`,
656 + },
657 + OriginPullRequestListSchema,
658 + ),
659 + initialAvatars(input.cwd, avatarArgs),
660 + ],
661 + { concurrency: "unbounded" },
662 + );
663 + const pullRequests = page.pullRequests ?? [];
664 + for (const pullRequest of pullRequests)
665 + remember(pullKey({ ...input, number: pullRequest.number }), pullRequest);
666 + // `origin pr list` only reads the first page, so later pages use the pictures already read.
667 + const avatars =
668 + input.cursor === undefined
669 + ? yield* avatarsFor(
670 + input.cwd,
671 + pullRequests.map((pullRequest) => pullRequest.author),
672 + avatarArgs,
673 + )
674 + : avatarCache;
675 + const next = page.nextPageToken || null;
676 + return {
677 + items: pullRequests.map((pullRequest) => toProviderChangeRequest(pullRequest, avatars)),
678 + truncated: next !== null,
679 + continues: next !== null,
680 + ...(next === null ? {} : { resumeAfter: pageTokenKey(next) }),
681 + };
682 + },
683 + Effect.mapError((error) =>
684 + // The list shows only a failure's access hint, and this one needs its refresh advice.
685 + error.operation === EXPIRED_LIST_POSITION
686 + ? new PullRequestProviderError({
687 + provider: SourceControlProviderKind.make("cursor-origin"),
688 + operation: "listChangeRequests",
689 + reason: "failed",
690 + detail: error.detail,
691 + accessHint: error.detail,
692 + cause: error,
693 + })
694 + : fail("listChangeRequests")(error),
695 + ),
696 + ),
697 +
698 + // One read: linked threads poll this, and the full detail costs four.
699 + getChangeRequestSummary: (input) =>
700 + getPull(input).pipe(
701 + Effect.map((pullRequest) => {
702 + const summary = toProviderChangeRequest(pullRequest, avatarCache);
703 + return {
704 + number: summary.number,
705 + title: summary.title,
706 + url: summary.url,
707 + headBranch: summary.headBranch,
708 + baseBranch: summary.baseBranch,
709 + state: summary.state,
710 + isDraft: summary.isDraft,
711 + closedAt: summary.closedAt ?? null,
712 + mergedAt: summary.mergedAt ?? null,
713 + updatedAt: summary.updatedAt,
714 + author: summary.author,
715 + additions: summary.additions,
716 + deletions: summary.deletions,
717 + changedFiles: pullRequest.changedFiles ?? 0,
718 + };
719 + }),
720 + Effect.mapError(fail("getChangeRequestSummary")),
721 + ),
722 +
723 + getChangeRequestChecks: (input) =>
724 + withPull(input, (pullRequest) => listChecks({ ...input, sha: pullRequest.head.sha })).pipe(
725 + Effect.map(([pullRequest, { checks }]) => ({ state: originState(pullRequest), checks })),
726 + Effect.mapError(fail("getChangeRequestChecks")),
727 + ),
728 +
729 + getChangeRequest: Effect.fn("OriginPullRequestProvider.getChangeRequest")(
730 + function* (input) {
731 + const [[pullRequest, [checkRead, avatars, mergeability]], repository] = yield* Effect.all(
732 + [
733 + withPull(input, (pullRequest) =>
734 + Effect.all(
735 + [
736 + recover(listChecks({ ...input, sha: pullRequest.head.sha }), {
737 + checks: [],
738 + truncated: false,
739 + }),
740 + avatarsFor(input.cwd, [pullRequest.author], viewArgs(input, "author")),
741 + mergeabilityOf(input, pullRequest),
742 + ],
743 + { concurrency: "unbounded" },
744 + ),
745 + ),
746 + getRepositorySettings(input.cwd, input.repository),
747 + ],
748 + { concurrency: "unbounded" },
749 + );
750 + const { checks, truncated } = checkRead;
751 + const rollup = checksState(checks);
752 + const detail: ProviderChangeRequestDetail = {
753 + ...toProviderChangeRequest(pullRequest, avatars),
754 + mergeability,
755 + // Checks past the last page read are unknown, so all-green ones read are not a pass.
756 + checksState: truncated && rollup === "passing" ? "pending" : rollup,
757 + headSha: pullRequest.head.sha ?? null,
758 + body: pullRequest.body ?? "",
759 + changedFiles: pullRequest.changedFiles ?? 0,
760 + reviewers: [],
761 + checks,
762 + mergeCapabilities: {
763 + merge: repository?.allowMergeCommit ?? true,
764 + squash: repository?.allowSquashMerge ?? true,
765 + rebase: false,
766 + },
767 + viewerPermissions: VIEWER_PERMISSIONS,
768 + };
769 + return detail;
770 + },
771 + Effect.mapError(fail("getChangeRequest")),
772 + ),
773 +
774 + getChangeRequestActivity: (input) => {
775 + // A part that cannot be read shows as empty and truncated rather than failing the rest.
776 + const part = (operation: string, suffix: string) => ({
777 + cwd: input.cwd,
778 + operation,
779 + path: pullPath(input.repository, input.number, suffix),
780 + });
781 + const unread = { items: [], truncated: true };
782 + return Effect.all(
783 + [
784 + recover(
785 + readPages(
786 + part("listComments", "/comments"),
787 + OriginCommentListSchema,
788 + (page) => page.comments,
789 + ),
790 + unread,
791 + true,
792 + ),
793 + recover(
794 + readPages(
795 + part("listReviews", "/reviews"),
796 + OriginReviewListSchema,
797 + (page) => page.reviews,
798 + ),
799 + unread,
800 + true,
801 + ),
802 + recover(
803 + readPages(
804 + part("listCommits", "/commits"),
805 + OriginCommitListSchema,
806 + (page) => page.commits,
807 + ),
808 + unread,
809 + true,
810 + ),
811 + // The detail is read alongside, so this is usually its cached answer.
812 + recover(getPull(input), null),
813 + ],
814 + { concurrency: 4 },
815 + ).pipe(
816 + Effect.flatMap(([comments, reviews, commits, pullRequest]) =>
817 + avatarsFor(
818 + input.cwd,
819 + [
820 + ...comments.items.map((comment) => comment.author),
821 + ...reviews.items.map((review) => review.author),
822 + ],
823 + viewArgs(input, "author,reviews,comments"),
824 + ).pipe(
825 + Effect.map(
826 + (avatars) =>
827 + [comments, reviews, commits, avatars, pullRequest?.head.sha ?? null] as const,
828 + ),
829 + ),
830 + ),
831 + Effect.mapError(fail("getChangeRequestActivity")),
832 + Effect.map(
833 + ([comments, reviews, commits, avatars, headSha]): ProviderChangeRequestActivity => {
834 + const discussion: PullRequestComment[] = comments.items
835 + .filter((comment) => !isThreadComment(comment))
836 + .map((comment) => ({
837 + id: comment.id,
838 + kind: "issue-comment",
839 + author: originActor(comment.author, avatars),
840 + body: comment.body ?? "",
841 + createdAt: comment.createdAt,
842 + editedAt: editedAt(comment),
843 + url: null,
844 + path: null,
845 + reviewState: null,
846 + }));
847 + const reviewComments: PullRequestComment[] = reviews.items.map((review) => ({
848 + id: review.id,
849 + kind: "review",
850 + author: originActor(review.author, avatars),
851 + body: review.body ?? "",
852 + createdAt: review.submittedAt,
853 + url: null,
854 + path: null,
855 + reviewState: review.dismissal?.dismissedAt
856 + ? "DISMISSED"
857 + : review.verdict === "approve"
858 + ? "APPROVED"
859 + : review.verdict === "request_changes"
860 + ? "CHANGES_REQUESTED"
861 + : "COMMENTED",
862 + }));
863 + const all = [...discussion, ...reviewComments].toSorted((left, right) =>
864 + left.createdAt.localeCompare(right.createdAt),
865 + );
866 + return {
867 + comments: all,
868 + commentCount: all.length,
869 + commentsTruncated: comments.truncated || reviews.truncated,
870 + reviewThreadsTruncated: comments.truncated,
871 + reviewThreads: toThreads(comments.items, avatars, headSha),
872 + commits: commits.items.map((commit) => ({
873 + oid: commit.sha,
874 + messageHeadline: commit.commit.message.split("\n")[0] ?? "",
875 + committedDate:
876 + commit.commit.committer?.date ?? commit.commit.author?.date ?? UNKNOWN_TIME,
877 + ...(commit.stats?.additions == null ? {} : { additions: commit.stats.additions }),
878 + ...(commit.stats?.deletions == null ? {} : { deletions: commit.stats.deletions }),
879 + })),
880 + };
881 + },
882 + ),
883 + );
884 + },
885 +
886 + getViewerPermissions: () => Effect.succeed(VIEWER_PERMISSIONS),
887 +
888 + // A version's patch never changes, and the files read counts five times against the rate limit, so
889 + // a patch is kept by the commits it compares; the pull request read that names them is the
890 + // one the detail is already making.
891 + getDiff: (input) =>
892 + (input.commit === undefined
893 + ? getPull(input).pipe(
894 + Effect.flatMap((pullRequest) => {
895 + const version = versionKey(pullRequest);
896 + return version
897 + ? Cache.get(
898 + patches,
899 + `${input.cwd}\n${input.repository}\n${input.number}\n${version}`,
900 + )
901 + : readPatch(input.cwd, pullPath(input.repository, input.number, "/files"));
902 + }),
903 + )
904 + : Cache.get(patches, `${input.cwd}\n${input.repository}\n\n${input.commit}`)
905 + ).pipe(
906 + Effect.map(({ patch, truncated, nextCursor }) => ({ patch, truncated, nextCursor })),
907 + Effect.mapError(fail("getDiff")),
908 + ),
909 +
910 + listReviewerCandidates: () =>
911 + unsupported("listReviewerCandidates", "Cursor Origin does not list reviewer candidates."),
912 + setReviewerRequest: () =>
913 + unsupported(
914 + "setReviewerRequest",
915 + "Requesting reviewers is not supported for Cursor Origin yet.",
916 + ),
917 + setReaction: () =>
918 + unsupported("setReaction", "Reactions are not supported for Cursor Origin yet."),
919 +
920 + runAction: (input) => {
921 + const path = pullPath(input.repository, input.number);
922 + const action = (() => {
923 + switch (input.action) {
924 + case "merge":
925 + return refuseStackedMerge(input).pipe(
926 + Effect.andThen(
927 + write(input, "runAction", "POST", `${path}/merge`, {
928 + mergeMethod: input.mergeMethod === "squash" ? "squash" : "merge",
929 + }),
930 + ),
931 + );
932 + case "close":
933 + return write(input, "runAction", "PATCH", path, { state: "closed" });
934 + case "reopen":
935 + return write(input, "runAction", "PATCH", path, { state: "open" });
936 + case "ready":
937 + return write(input, "runAction", "PATCH", path, { draft: false });
938 + case "draft":
939 + return write(input, "runAction", "PATCH", path, { draft: true });
940 + default:
941 + return null;
942 + }
943 + })();
944 + return action === null
945 + ? unsupported("runAction", `Cursor Origin does not support ${input.action}.`)
946 + : action.pipe(
947 + Effect.ensuring(forgetPull(input)),
948 + // A merge moves its base, which every other pull request into it compares against.
949 + Effect.ensuring(input.action === "merge" ? Cache.invalidateAll(baseTips) : Effect.void),
950 + );
951 + },
952 +
953 + updateChangeRequest: (input) =>
954 + write(input, "updateChangeRequest", "PATCH", pullPath(input.repository, input.number), {
955 + ...(input.title === undefined ? {} : { title: input.title }),
956 + ...(input.body === undefined ? {} : { body: input.body }),
957 + }).pipe(Effect.ensuring(forgetPull(input))),
958 +
959 + comment: (input) =>
960 + write(input, "comment", "POST", pullPath(input.repository, input.number, "/comments"), {
961 + body: input.body,
962 + }).pipe(Effect.ensuring(forgetPull(input))),
963 +
964 + updateComment: (input) =>
965 + write(
966 + input,
967 + "updateComment",
968 + "PATCH",
969 + `${OriginCli.originRepositoryPath(input.repository)}/pulls/comments/${encodeURIComponent(input.commentId)}`,
970 + { body: input.body },
971 + ).pipe(Effect.ensuring(forgetPull(input))),
972 +
973 + submitReview: (input) =>
974 + write(input, "submitReview", "POST", pullPath(input.repository, input.number, "/reviews"), {
975 + verdict: input.verdict === "request-changes" ? "request_changes" : input.verdict,
976 + body: input.body,
977 + comments: input.comments.map((comment) => {
978 + const side =
979 + comment.position.kind === "deleted"
980 + ? "left"
981 + : comment.position.kind === "added"
982 + ? "right"
983 + : comment.position.side;
984 + const line =
985 + comment.position.kind === "deleted"
986 + ? comment.position.oldLine
987 + : comment.position.kind === "added"
988 + ? comment.position.newLine
989 + : side === "left"
990 + ? comment.position.oldLine
991 + : comment.position.newLine;
992 + return {
993 + body: comment.body,
994 + inline: { path: comment.path, side, startLine: line, endLine: line },
995 + };
996 + }),
997 + }).pipe(Effect.ensuring(forgetPull(input))),
998 +
999 + replyToThread: (input) =>
1000 + write(input, "replyToThread", "POST", pullPath(input.repository, input.number, "/comments"), {
1001 + body: input.body,
1002 + threadId: input.threadId,
1003 + }).pipe(Effect.ensuring(forgetPull(input))),
1004 +
1005 + setThreadResolution: (input) =>
1006 + write(
1007 + input,
1008 + "setThreadResolution",
1009 + "PATCH",
1010 + `${OriginCli.originRepositoryPath(input.repository)}/pulls/threads/${encodeURIComponent(input.threadId)}`,
1011 + { resolved: input.resolved },
1012 + ).pipe(Effect.ensuring(forgetPull(input))),
1013 + };
1014 +
1015 + return provider;
1016 +});
packages/source-control-cursor-origin/src/server/OriginSourceControlProvider.ts new
+353
@@ -0,0 +1,353 @@
1 +import * as Effect from "effect/Effect";
2 +import * as FileSystem from "effect/FileSystem";
3 +import * as Schedule from "effect/Schedule";
4 +import * as Schema from "effect/Schema";
5 +import { SourceControlProviderError, SourceControlProviderKind } from "@t3tools/contracts";
6 +import { CURSOR_ORIGIN_WEB_BASE_URL } from "../shared/definition.ts";
7 +import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
8 +import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
9 +import {
10 + probeSourceControlProvider,
11 + providerAuth,
12 + type SourceControlCliDiscoverySpec,
13 + type SourceControlManagedCliDiscoverySpec,
14 +} from "@t3tools/source-control-core/server/discovery";
15 +
16 +import * as OriginCli from "./OriginCli.ts";
17 +import {
18 + OriginPullRequestListSchema,
19 + OriginPullRequestSchema,
20 + OriginRepositorySchema,
21 + pullReference,
22 + toOriginChangeRequest,
23 + type OriginRepository,
24 +} from "./originPullRequests.ts";
25 +
26 +const isOriginCliError = Schema.is(OriginCli.OriginCliError);
27 +
28 +const discovery = {
29 + type: "cli",
30 + kind: SourceControlProviderKind.make("cursor-origin"),
31 + label: "Cursor Origin",
32 + executable: OriginCli.ORIGIN_COMMAND,
33 + versionArgs: ["--version"],
34 + authArgs: ["auth", "status", "--json"],
35 + parseAuth: (input) => {
36 + const status = OriginCli.parseOriginAuthStatus(input.stdout);
37 + const account = OriginCli.originAccount(status);
38 + if (status === null) return providerAuth({ status: "unknown" });
39 + return status.authenticated && status.tokenValid !== false
40 + ? providerAuth({
41 + status: "authenticated",
42 + account: account ?? undefined,
43 + host: "origin.cursor.com",
44 + })
45 + : providerAuth({
46 + status: "unauthenticated",
47 + detail: "Run `origin auth login` to sign in to Cursor Origin.",
48 + });
49 + },
50 + installHint:
51 + "Install the Origin CLI with `curl -fsSL https://downloads.cursor.com/origin/install.sh | sh`, then run `origin auth login`.",
52 +} satisfies SourceControlCliDiscoverySpec;
53 +
54 +/**
55 + * Discovery names the account by its namespace slug, which is what owns its repositories (and so
56 + * what Publish fills in), rather than the email `origin auth status` reports.
57 + */
58 +export const makeDiscovery = Effect.gen(function* () {
59 + const cli = yield* OriginCli.OriginCli;
60 + const { process } = yield* SourceControlHost.SourceControlHost;
61 + return {
62 + type: "managed-cli",
63 + kind: discovery.kind,
64 + label: discovery.label,
65 + installHint: discovery.installHint,
66 + probe: Effect.fn("OriginSourceControlProvider.discovery")(function* (cwd: string) {
67 + const item = yield* probeSourceControlProvider({ cwd, process, spec: discovery });
68 + if (item.status !== "available" || item.auth.status !== "authenticated") return item;
69 + const namespace = yield* cli.personalNamespace(cwd).pipe(Effect.option);
70 + return { ...item, auth: { ...item.auth, account: namespace } };
71 + }),
72 + // `origin.cursor.com` is recognised from the remote alone, so there is nothing to refine.
73 + refineUnknownRemote: () => Effect.succeed(null),
74 + } satisfies SourceControlManagedCliDiscoverySpec;
75 +});
76 +
77 +const cloneUrls = (repository: OriginRepository, fallbackName: string) => {
78 + const nameWithOwner =
79 + repository.fullName ??
80 + (repository.owner ? `${repository.owner.slug}/${repository.name}` : fallbackName);
81 + const url = repository.cloneUrl ?? `https://origin.cursor.com/${nameWithOwner}.git`;
82 + // Origin documents no SSH clone URL, and `origin auth login` already configures git's HTTPS
83 + // credential helper, so HTTPS stands in for both.
84 + return { nameWithOwner, url, sshUrl: url };
85 +};
86 +
87 +export const make = Effect.gen(function* () {
88 + const cli = yield* OriginCli.OriginCli;
89 + const fs = yield* FileSystem.FileSystem;
90 + const { git } = yield* SourceControlHost.SourceControlHost;
91 +
92 + const mapError = (
93 + operation: string,
94 + cwd: string,
95 + extra?: { readonly repository?: string; readonly reference?: string },
96 + ) =>
97 + Effect.mapError(
98 + (cause: unknown) =>
99 + new SourceControlProviderError({
100 + provider: SourceControlProviderKind.make("cursor-origin"),
101 + operation,
102 + cwd,
103 + command: OriginCli.ORIGIN_COMMAND,
104 + ...(extra?.repository
105 + ? {
106 + repository: SourceControlProvider.transportSafeSourceControlErrorValue(
107 + extra.repository,
108 + ),
109 + }
110 + : {}),
111 + ...(extra?.reference
112 + ? {
113 + reference: SourceControlProvider.transportSafeSourceControlErrorValue(
114 + extra.reference,
115 + ),
116 + }
117 + : {}),
118 + detail: isOriginCliError(cause) ? cause.detail : "Cursor Origin operation failed.",
119 + cause,
120 + }),
121 + );
122 +
123 + const getRepository = (cwd: string, repository: string, operation: string) =>
124 + cli.api(
125 + { cwd, operation, path: OriginCli.originRepositoryPath(repository) },
126 + OriginRepositorySchema,
127 + );
128 +
129 + return SourceControlProvider.SourceControlProvider.of({
130 + kind: SourceControlProviderKind.make("cursor-origin"),
131 +
132 + /** Origin's browser pages live on cursor.com, not on the git host the remote names. */
133 + refineRepositoryIdentity: Effect.fn("OriginSourceControlProvider.refineRepositoryIdentity")(
134 + ({ identity }) => {
135 + const path = SourceControlProvider.repositoryPathFromRemoteUrl(identity.locator.remoteUrl);
136 + return Effect.succeed(
137 + identity.provider === "cursor-origin" && path
138 + ? { ...identity, webUrl: `${CURSOR_ORIGIN_WEB_BASE_URL}/${path}` }
139 + : identity,
140 + );
141 + },
142 + ),
143 +
144 + listChangeRequests: Effect.fn("OriginSourceControlProvider.listChangeRequests")(
145 + function* (input) {
146 + const repository = yield* cli.resolveRepository(input);
147 + const head = SourceControlProvider.sourceBranch(input);
148 + const limit = Math.min(Math.max(input.limit ?? 20, 1), 100);
149 + const query = new URLSearchParams({
150 + head,
151 + state: input.state,
152 + pageSize: String(limit),
153 + sortBy: "updated",
154 + });
155 + const page = yield* cli.api(
156 + {
157 + cwd: input.cwd,
158 + operation: "listChangeRequests",
159 + path: `${OriginCli.originRepositoryPath(repository)}/pulls?${query}`,
160 + },
161 + OriginPullRequestListSchema,
162 + );
163 + return (page.pullRequests ?? []).map(toOriginChangeRequest);
164 + },
165 + (effect, input) =>
166 + effect.pipe(mapError("listChangeRequests", input.cwd, { reference: input.headSelector })),
167 + ),
168 +
169 + getChangeRequest: Effect.fn("OriginSourceControlProvider.getChangeRequest")(
170 + function* (input) {
171 + const reference = pullReference(input.reference);
172 + const repository = reference.repository ?? (yield* cli.resolveRepository(input));
173 + const number = reference.number;
174 + if (number === null)
175 + return yield* new OriginCli.OriginCliError({
176 + operation: "getChangeRequest",
177 + cwd: input.cwd,
178 + reason: "not-found",
179 + detail: "Specify a pull request number or Cursor Origin pull request URL.",
180 + });
181 + return toOriginChangeRequest(
182 + yield* cli.api(
183 + {
184 + cwd: input.cwd,
185 + operation: "getChangeRequest",
186 + path: `${OriginCli.originRepositoryPath(repository)}/pulls/${number}`,
187 + },
188 + OriginPullRequestSchema,
189 + ),
190 + );
191 + },
192 + (effect, input) =>
193 + effect.pipe(mapError("getChangeRequest", input.cwd, { reference: input.reference })),
194 + ),
195 +
196 + createChangeRequest: Effect.fn("OriginSourceControlProvider.createChangeRequest")(
197 + function* (input) {
198 + const repository = input.target?.repository ?? (yield* cli.resolveRepository(input));
199 + // Origin creates drafts unless told otherwise; T3 asks for draft explicitly elsewhere.
200 + yield* cli.api(
201 + {
202 + cwd: input.cwd,
203 + operation: "createChangeRequest",
204 + method: "POST",
205 + path: `${OriginCli.originRepositoryPath(repository)}/pulls`,
206 + body: {
207 + title: input.title,
208 + body: yield* fs.readFileString(input.bodyFile),
209 + head: SourceControlProvider.sourceBranch(input),
210 + base: input.target?.refName ?? input.baseRefName,
211 + draft: false,
212 + },
213 + },
214 + Schema.Unknown,
215 + );
216 + },
217 + (effect, input) =>
218 + effect.pipe(mapError("createChangeRequest", input.cwd, { reference: input.headSelector })),
219 + ),
220 +
221 + getRepositoryCloneUrls: Effect.fn("OriginSourceControlProvider.getRepositoryCloneUrls")(
222 + function* (input) {
223 + const repository = yield* getRepository(
224 + input.cwd,
225 + input.repository,
226 + "getRepositoryCloneUrls",
227 + );
228 + return cloneUrls(repository, input.repository);
229 + },
230 + (effect, input) =>
231 + effect.pipe(
232 + mapError("getRepositoryCloneUrls", input.cwd, { repository: input.repository }),
233 + ),
234 + ),
235 +
236 + createRepository: Effect.fn("OriginSourceControlProvider.createRepository")(
237 + function* (input) {
238 + if (input.visibility === "public")
239 + return yield* new OriginCli.OriginCliError({
240 + operation: "createRepository",
241 + cwd: input.cwd,
242 + reason: "failed",
243 + detail: "Cursor Origin repositories are private. Choose private visibility.",
244 + });
245 + const parts = input.repository.split("/");
246 + if (parts.length > 2 || parts.some((part) => part.trim().length === 0))
247 + return yield* new OriginCli.OriginCliError({
248 + operation: "createRepository",
249 + cwd: input.cwd,
250 + reason: "failed",
251 + detail: "Specify an Origin repository as owner/name or name.",
252 + });
253 + const [owner, name] =
254 + parts.length === 2 ? parts : [yield* cli.personalNamespace(input.cwd), input.repository];
255 + yield* cli.api(
256 + {
257 + cwd: input.cwd,
258 + operation: "createRepository",
259 + method: "POST",
260 + path: `/v1/origin/repos/${encodeURIComponent(owner ?? "")}`,
261 + body: { name },
262 + },
263 + OriginRepositorySchema,
264 + );
265 + // Origin creates repositories internal (visible to the whole team) and only takes a
266 + // visibility on update, so the repository is made private straight after.
267 + const madePrivate = yield* cli
268 + .api(
269 + {
270 + cwd: input.cwd,
271 + operation: "createRepository",
272 + method: "PATCH",
273 + path: OriginCli.originRepositoryPath(`${owner}/${name}`),
274 + body: { visibility: "private" },
275 + },
276 + OriginRepositorySchema,
277 + )
278 + .pipe(
279 + Effect.retry({
280 + times: 2,
281 + schedule: Schedule.spaced("1 second"),
282 + while: (error) =>
283 + error.reason !== "rate-limited" && error.reason !== "unauthenticated",
284 + }),
285 + Effect.mapError(
286 + (cause) =>
287 + new OriginCli.OriginCliError({
288 + operation: "createRepository",
289 + cwd: input.cwd,
290 + reason: cause.reason,
291 + ...(cause.retryAt === undefined ? {} : { retryAt: cause.retryAt }),
292 + detail: `Created ${owner}/${name}, but could not make it private, so your Cursor team can still see it. Set it to private on cursor.com.`,
293 + cause,
294 + }),
295 + ),
296 + );
297 + return cloneUrls(madePrivate, `${owner}/${name}`);
298 + },
299 + (effect, input) =>
300 + effect.pipe(mapError("createRepository", input.cwd, { repository: input.repository })),
301 + ),
302 +
303 + getDefaultBranch: Effect.fn("OriginSourceControlProvider.getDefaultBranch")(
304 + function* (input) {
305 + const repository = yield* cli.resolveRepository(input);
306 + return (
307 + (yield* getRepository(input.cwd, repository, "getDefaultBranch")).defaultBranch ?? null
308 + );
309 + },
310 + (effect, input) => effect.pipe(mapError("getDefaultBranch", input.cwd)),
311 + ),
312 +
313 + checkoutChangeRequest: Effect.fn("OriginSourceControlProvider.checkoutChangeRequest")(
314 + function* (input) {
315 + const repository = yield* cli.resolveRepository(input);
316 + const { repository: linked, number } = pullReference(input.reference);
317 + const reference = input.reference.trim();
318 + // The CLI reads a leading dash as a flag and ignores a target after `--`; no branch starts
319 + // with one.
320 + if (number === null && reference.startsWith("-"))
321 + return yield* new OriginCli.OriginCliError({
322 + operation: "checkoutChangeRequest",
323 + cwd: input.cwd,
324 + reason: "not-found",
325 + detail: "Specify a pull request number, branch, or Cursor Origin pull request URL.",
326 + });
327 + if (linked !== null && linked !== repository.toLowerCase())
328 + return yield* new OriginCli.OriginCliError({
329 + operation: "checkoutChangeRequest",
330 + cwd: input.cwd,
331 + reason: "not-found",
332 + detail: `That pull request is in ${linked}, not this checkout's ${repository}.`,
333 + });
334 + yield* cli.execute({
335 + cwd: input.cwd,
336 + operation: "checkoutChangeRequest",
337 + args: [
338 + "pr",
339 + "checkout",
340 + "-R",
341 + repository,
342 + "--remote",
343 + input.context?.remoteName ?? (yield* git.resolvePrimaryRemoteName(input.cwd)),
344 + ...(input.force ? ["--force"] : []),
345 + number === null ? reference : String(number),
346 + ],
347 + });
348 + },
349 + (effect, input) =>
350 + effect.pipe(mapError("checkoutChangeRequest", input.cwd, { reference: input.reference })),
351 + ),
352 + });
353 +});
packages/source-control-cursor-origin/src/server/driver.ts new
+29
@@ -0,0 +1,29 @@
1 +/**
2 + * The Cursor Origin driver: repository operations, discovery, and pull requests through Origin's
3 + * REST API, signed in with the `origin` CLI's session.
4 + *
5 + * @module source-control-cursor-origin/server/driver
6 + */
7 +import {
8 + defineSourceControlDriver,
9 + withOwnServices,
10 +} from "@t3tools/source-control-core/server/driver";
11 +import * as Effect from "effect/Effect";
12 +
13 +import { definition } from "../shared/definition.ts";
14 +
15 +import * as OriginCli from "./OriginCli.ts";
16 +import * as OriginPullRequestProvider from "./OriginPullRequestProvider.ts";
17 +import * as OriginSourceControlProvider from "./OriginSourceControlProvider.ts";
18 +
19 +const makeInstance = Effect.all({
20 + sourceControl: OriginSourceControlProvider.make,
21 + discovery: OriginSourceControlProvider.makeDiscovery,
22 + pullRequests: OriginPullRequestProvider.make,
23 +});
24 +
25 +export const driver = defineSourceControlDriver({
26 + kind: definition.kind,
27 + definition,
28 + make: withOwnServices(makeInstance, OriginCli.layer),
29 +});
packages/source-control-cursor-origin/src/server/originPullRequests.test.ts new
+64
@@ -0,0 +1,64 @@
1 +import { assert, describe, it } from "@effect/vitest";
2 +
3 +import { checksState, originCheck, originFilesPatch, pullReference } from "./originPullRequests.ts";
4 +
5 +const run = (status: string, conclusion?: string) =>
6 + originCheck({ name: `${status}-${conclusion ?? ""}`, status, conclusion });
7 +
8 +describe("checksState", () => {
9 + it("rolls up Origin check runs", () => {
10 + assert.strictEqual(checksState([]), null);
11 + assert.strictEqual(
12 + checksState([run("completed", "success"), run("completed", "skipped")]),
13 + "passing",
14 + );
15 + assert.strictEqual(checksState([run("completed", "success"), run("in_progress")]), "pending");
16 + assert.strictEqual(
17 + checksState([run("completed", "success"), run("completed", "cancelled")]),
18 + "failing",
19 + );
20 + assert.strictEqual(
21 + checksState([run("in_progress"), run("completed", "action_required")]),
22 + "failing",
23 + );
24 + });
25 +});
26 +
27 +describe("originFilesPatch", () => {
28 + const header = (file: Parameters<typeof originFilesPatch>[0][number]) =>
29 + originFilesPatch([file]).split("\n").slice(0, 4);
30 +
31 + it("keeps rename and copy metadata", () => {
32 + assert.deepStrictEqual(
33 + header({ filename: "b.ts", previousFilename: "a.ts", status: "renamed" }),
34 + ["diff --git a/a.ts b/b.ts", "similarity index 100%", "rename from a.ts", "rename to b.ts"],
35 + );
36 + // Origin leaves out the hunks of large files, which must not read as a pure rename.
37 + assert.strictEqual(
38 + header({ filename: "b.ts", previousFilename: "a.ts", status: "renamed", changes: 4 })[1],
39 + "similarity index 0%",
40 + );
41 + assert.deepStrictEqual(
42 + header({
43 + filename: "b.ts",
44 + previousFilename: "a.ts",
45 + status: "copied",
46 + patch: "@@ -1 +1 @@\n-a\n+b",
47 + }).slice(1),
48 + ["similarity index 0%", "copy from a.ts", "copy to b.ts"],
49 + );
50 + });
51 +});
52 +
53 +describe("pullReference", () => {
54 + it("separates pull request numbers, Origin links, and branches", () => {
55 + assert.deepStrictEqual(pullReference("42"), { repository: null, number: 42 });
56 + assert.deepStrictEqual(pullReference(" #42 "), { repository: null, number: 42 });
57 + assert.deepStrictEqual(pullReference("https://cursor.com/codebase/Acme/Web/pull/7"), {
58 + repository: "acme/web",
59 + number: 7,
60 + });
61 + for (const branch of ["123/fix", "feature/pull/42", "https://github.com/acme/web/pull/7"])
62 + assert.deepStrictEqual(pullReference(branch), { repository: null, number: null });
63 + });
64 +});
packages/source-control-cursor-origin/src/server/originPullRequests.ts new
+411
@@ -0,0 +1,411 @@
1 +/**
2 + * Origin's REST shapes, read leniently: the API is in beta and int64 fields arrive as strings.
3 + *
4 + * @module source-control-cursor-origin/server/originPullRequests
5 + */
6 +import * as DateTime from "effect/DateTime";
7 +import * as Option from "effect/Option";
8 +import * as Schema from "effect/Schema";
9 +import type {
10 + ChangeRequest,
11 + PullRequestActor,
12 + PullRequestCheck,
13 + PullRequestCheckStatus,
14 + PullRequestChecksState,
15 + PullRequestMergeability,
16 + PullRequestState,
17 +} from "@t3tools/contracts";
18 +import { SourceControlProviderKind } from "@t3tools/contracts";
19 +import { quoteGitPatchPath } from "@t3tools/shared/gitPatchPath";
20 +import { parseChangeRequestUrl } from "../shared/definition.ts";
21 +
22 +const Int64 = Schema.Union([Schema.Number, Schema.NumberFromString]);
23 +const OptionalString = Schema.optional(Schema.NullOr(Schema.String));
24 +
25 +const OriginActorSchema = Schema.Struct({
26 + user: Schema.optional(
27 + Schema.NullOr(
28 + Schema.Struct({
29 + id: OptionalString,
30 + email: OptionalString,
31 + displayName: OptionalString,
32 + handle: OptionalString,
33 + }),
34 + ),
35 + ),
36 + app: Schema.optional(
37 + Schema.NullOr(Schema.Struct({ id: OptionalString, displayName: OptionalString })),
38 + ),
39 + serviceAccount: Schema.optional(
40 + Schema.NullOr(Schema.Struct({ id: OptionalString, displayName: OptionalString })),
41 + ),
42 +});
43 +type OriginActor = typeof OriginActorSchema.Type;
44 +
45 +/** Cursor profile pictures by actor id. The REST API omits them; the CLI's JSON carries them. */
46 +export type OriginAvatars = ReadonlyMap<string, string>;
47 +
48 +/** The id an actor's avatar is keyed by, which the REST API and the CLI share. */
49 +export function originActorId(actor: OriginActor | null | undefined): string | null {
50 + return (
51 + actor?.user?.id?.trim() || actor?.app?.id?.trim() || actor?.serviceAccount?.id?.trim() || null
52 + );
53 +}
54 +
55 +/** Every `{ id, avatarUrl }` pair anywhere in `origin pr list/view --json` output. */
56 +export function originAvatars(json: unknown): Map<string, string> {
57 + const avatars = new Map<string, string>();
58 + const visit = (value: unknown): void => {
59 + if (Array.isArray(value)) {
60 + for (const item of value) visit(item);
61 + return;
62 + }
63 + if (value === null || typeof value !== "object") return;
64 + const record = value as Record<string, unknown>;
65 + if (typeof record.id === "string" && typeof record.avatarUrl === "string")
66 + avatars.set(record.id, record.avatarUrl.trim());
67 + for (const child of Object.values(record)) visit(child);
68 + };
69 + visit(json);
70 + return avatars;
71 +}
72 +
73 +const RefSchema = Schema.Struct({ ref: Schema.String, sha: OptionalString });
74 +
75 +export const OriginPullRequestSchema = Schema.Struct({
76 + number: Int64,
77 + state: OptionalString,
78 + draft: Schema.optional(Schema.NullOr(Schema.Boolean)),
79 + merged: Schema.optional(Schema.NullOr(Schema.Boolean)),
80 + title: Schema.String,
81 + body: OptionalString,
82 + head: RefSchema,
83 + base: RefSchema,
84 + author: Schema.optional(Schema.NullOr(OriginActorSchema)),
85 + createdAt: OptionalString,
86 + updatedAt: OptionalString,
87 + closedAt: OptionalString,
88 + mergedAt: OptionalString,
89 + additions: Schema.optional(Schema.NullOr(Int64)),
90 + deletions: Schema.optional(Schema.NullOr(Int64)),
91 + changedFiles: Schema.optional(Schema.NullOr(Int64)),
92 + labels: Schema.optional(
93 + Schema.NullOr(
94 + Schema.Array(
95 + Schema.Struct({ name: Schema.String, color: OptionalString, description: OptionalString }),
96 + ),
97 + ),
98 + ),
99 + webUrl: Schema.String,
100 + stack: Schema.optional(
101 + Schema.NullOr(
102 + Schema.Struct({
103 + parentPullRequest: Schema.optional(Schema.NullOr(Schema.Struct({ number: Int64 }))),
104 + }),
105 + ),
106 + ),
107 + version: Schema.optional(
108 + Schema.NullOr(
109 + Schema.Struct({
110 + headSha: OptionalString,
111 + baseSha: OptionalString,
112 + potentialMergeCommit: Schema.optional(
113 + Schema.NullOr(Schema.Struct({ state: OptionalString, baseSha: OptionalString })),
114 + ),
115 + }),
116 + ),
117 + ),
118 +});
119 +export type OriginPullRequest = typeof OriginPullRequestSchema.Type;
120 +
121 +export const OriginPullRequestListSchema = Schema.Struct({
122 + pullRequests: Schema.optional(Schema.NullOr(Schema.Array(OriginPullRequestSchema))),
123 + nextPageToken: OptionalString,
124 +});
125 +
126 +export const OriginRepositorySchema = Schema.Struct({
127 + name: Schema.String,
128 + fullName: OptionalString,
129 + owner: Schema.optional(Schema.NullOr(Schema.Struct({ slug: Schema.String }))),
130 + defaultBranch: OptionalString,
131 + cloneUrl: OptionalString,
132 + allowMergeCommit: Schema.optional(Schema.NullOr(Schema.Boolean)),
133 + allowSquashMerge: Schema.optional(Schema.NullOr(Schema.Boolean)),
134 +});
135 +export type OriginRepository = typeof OriginRepositorySchema.Type;
136 +
137 +const ThreadSchema = Schema.Struct({
138 + id: Schema.String,
139 + version: Schema.optional(Schema.NullOr(Schema.Struct({ headSha: OptionalString }))),
140 + path: OptionalString,
141 + side: OptionalString,
142 + startLine: Schema.optional(Schema.NullOr(Int64)),
143 + endLine: Schema.optional(Schema.NullOr(Int64)),
144 + resolvedAt: OptionalString,
145 +});
146 +
147 +const OriginCommentSchema = Schema.Struct({
148 + id: Schema.String,
149 + thread: Schema.optional(Schema.NullOr(ThreadSchema)),
150 + body: OptionalString,
151 + author: Schema.optional(Schema.NullOr(OriginActorSchema)),
152 + createdAt: Schema.String,
153 + updatedAt: OptionalString,
154 +});
155 +export type OriginComment = typeof OriginCommentSchema.Type;
156 +
157 +export const OriginCommentListSchema = Schema.Struct({
158 + comments: Schema.optional(Schema.NullOr(Schema.Array(OriginCommentSchema))),
159 + nextPageToken: OptionalString,
160 +});
161 +
162 +export const OriginReviewListSchema = Schema.Struct({
163 + reviews: Schema.optional(
164 + Schema.NullOr(
165 + Schema.Array(
166 + Schema.Struct({
167 + id: Schema.String,
168 + author: Schema.optional(Schema.NullOr(OriginActorSchema)),
169 + verdict: OptionalString,
170 + body: OptionalString,
171 + submittedAt: Schema.String,
172 + dismissal: Schema.optional(Schema.NullOr(Schema.Struct({ dismissedAt: OptionalString }))),
173 + }),
174 + ),
175 + ),
176 + ),
177 + nextPageToken: OptionalString,
178 +});
179 +
180 +const CommitPersonSchema = Schema.Struct({ date: OptionalString });
181 +
182 +export const OriginCommitListSchema = Schema.Struct({
183 + commits: Schema.optional(
184 + Schema.NullOr(
185 + Schema.Array(
186 + Schema.Struct({
187 + sha: Schema.String,
188 + commit: Schema.Struct({
189 + author: Schema.optional(Schema.NullOr(CommitPersonSchema)),
190 + committer: Schema.optional(Schema.NullOr(CommitPersonSchema)),
191 + message: Schema.String,
192 + }),
193 + stats: Schema.optional(
194 + Schema.NullOr(
195 + Schema.Struct({
196 + additions: Schema.optional(Schema.NullOr(Int64)),
197 + deletions: Schema.optional(Schema.NullOr(Int64)),
198 + }),
199 + ),
200 + ),
201 + }),
202 + ),
203 + ),
204 + ),
205 + nextPageToken: OptionalString,
206 +});
207 +
208 +export const OriginFileListSchema = Schema.Struct({
209 + files: Schema.optional(
210 + Schema.NullOr(
211 + Schema.Array(
212 + Schema.Struct({
213 + filename: Schema.String,
214 + status: OptionalString,
215 + patch: OptionalString,
216 + previousFilename: OptionalString,
217 + changes: Schema.optional(Schema.NullOr(Int64)),
218 + }),
219 + ),
220 + ),
221 + ),
222 + nextPageToken: OptionalString,
223 +});
224 +
225 +export const OriginCheckRunListSchema = Schema.Struct({
226 + checkRuns: Schema.optional(
227 + Schema.NullOr(
228 + Schema.Array(
229 + Schema.Struct({
230 + name: Schema.String,
231 + status: OptionalString,
232 + conclusion: OptionalString,
233 + detailsUrl: OptionalString,
234 + output: Schema.optional(Schema.NullOr(Schema.Struct({ title: OptionalString }))),
235 + }),
236 + ),
237 + ),
238 + ),
239 + nextPageToken: OptionalString,
240 +});
241 +
242 +export function originActor(
243 + actor: OriginActor | null | undefined,
244 + avatars?: OriginAvatars,
245 +): PullRequestActor | null {
246 + if (!actor) return null;
247 + const id = originActorId(actor);
248 + const avatarUrl = (id && avatars?.get(id)) || null;
249 + const user = actor.user;
250 + const login = user?.handle?.trim() || user?.email?.trim() || user?.displayName?.trim();
251 + if (login) return { login, name: user?.displayName ?? null, avatarUrl };
252 + const bot = actor.app ?? actor.serviceAccount;
253 + const name = bot?.displayName?.trim() || bot?.id?.trim();
254 + return name ? { login: name, name, avatarUrl, isBot: true } : null;
255 +}
256 +
257 +/**
258 + * Whether the head merges cleanly into the base, from the merge commit Origin prepared for the
259 + * pull request's latest version. That merge was made against the base as it stood then, so it
260 + * only answers for the base's current tip when the version was built on it.
261 + */
262 +export function preparedMergeability(pullRequest: OriginPullRequest): PullRequestMergeability {
263 + // A version still being built for a new head answers for the old one.
264 + if (!pullRequest.head.sha || pullRequest.version?.headSha !== pullRequest.head.sha)
265 + return "unknown";
266 + const state = pullRequest.version?.potentialMergeCommit?.state;
267 + return state === "prepared"
268 + ? "mergeable"
269 + : state === "merge_conflict"
270 + ? "conflicting"
271 + : "unknown";
272 +}
273 +
274 +export const OriginMergeabilitySchema = Schema.Struct({
275 + verdict: OptionalString,
276 + headSha: OptionalString,
277 + blockers: Schema.optional(Schema.NullOr(Schema.Array(Schema.Struct({ kind: OptionalString })))),
278 +});
279 +
280 +export const OriginGitRefSchema = Schema.Struct({
281 + object: Schema.optional(Schema.NullOr(Schema.Struct({ sha: OptionalString }))),
282 +});
283 +
284 +export function originState(pullRequest: OriginPullRequest): PullRequestState {
285 + if (pullRequest.merged || pullRequest.mergedAt || pullRequest.state === "merged") return "merged";
286 + return pullRequest.state === "closed" ? "closed" : "open";
287 +}
288 +
289 +/** Stands in for a time Origin left out, so a row still sorts and renders. */
290 +export const UNKNOWN_TIME = "1970-01-01T00:00:00.000Z";
291 +
292 +const timestamp = (value: string | null | undefined) => value?.trim() || null;
293 +
294 +export function originUpdatedAt(pullRequest: OriginPullRequest): string {
295 + return timestamp(pullRequest.updatedAt) ?? timestamp(pullRequest.createdAt) ?? UNKNOWN_TIME;
296 +}
297 +
298 +export function toOriginChangeRequest(pullRequest: OriginPullRequest): ChangeRequest {
299 + const updatedAt = timestamp(pullRequest.updatedAt);
300 + return {
301 + provider: SourceControlProviderKind.make("cursor-origin"),
302 + number: pullRequest.number,
303 + title: pullRequest.title,
304 + url: pullRequest.webUrl,
305 + baseRefName: pullRequest.base.ref,
306 + headRefName: pullRequest.head.ref,
307 + ...(pullRequest.head.sha ? { headSha: pullRequest.head.sha } : {}),
308 + state: originState(pullRequest),
309 + ...(pullRequest.draft ? { isDraft: true } : {}),
310 + closedAt: timestamp(pullRequest.closedAt),
311 + mergedAt: timestamp(pullRequest.mergedAt),
312 + updatedAt:
313 + updatedAt === null ? Option.none() : Option.map(DateTime.make(updatedAt), DateTime.toUtc),
314 + };
315 +}
316 +
317 +export function originCheck(
318 + run: NonNullable<(typeof OriginCheckRunListSchema.Type)["checkRuns"]>[number],
319 +): PullRequestCheck {
320 + const status: PullRequestCheckStatus =
321 + run.status !== "completed"
322 + ? run.status === "failing"
323 + ? "failure"
324 + : "pending"
325 + : run.conclusion === "success"
326 + ? "success"
327 + : run.conclusion === "skipped"
328 + ? "skipped"
329 + : run.conclusion === "neutral" || run.conclusion === "stale"
330 + ? "neutral"
331 + : run.conclusion === "cancelled"
332 + ? "cancelled"
333 + : run.conclusion === "action_required"
334 + ? "action-required"
335 + : "failure";
336 + return {
337 + name: run.name,
338 + status,
339 + description: run.output?.title ?? null,
340 + url: run.detailsUrl ?? null,
341 + };
342 +}
343 +
344 +export function checksState(
345 + checks: ReadonlyArray<PullRequestCheck>,
346 +): PullRequestChecksState | null {
347 + if (checks.length === 0) return null;
348 + if (
349 + checks.some(
350 + (check) =>
351 + check.status === "failure" ||
352 + check.status === "cancelled" ||
353 + check.status === "action-required",
354 + )
355 + )
356 + return "failing";
357 + if (checks.some((check) => check.status === "pending")) return "pending";
358 + return "passing";
359 +}
360 +
361 +/** A unified patch for the files a pull request or commit touches, from GitHub-style hunks. */
362 +export function originFilesPatch(
363 + files: NonNullable<(typeof OriginFileListSchema.Type)["files"]>,
364 +): string {
365 + return files
366 + .map((file) => {
367 + const oldPath = file.previousFilename || file.filename;
368 + const added = file.status === "added";
369 + const removed = file.status === "removed" || file.status === "deleted";
370 + const action = file.status === "copied" ? "copy" : "rename";
371 + const before = quoteGitPatchPath(`a/${oldPath}`);
372 + const after = quoteGitPatchPath(`b/${file.filename}`);
373 + const header = [
374 + `diff --git ${before} ${after}`,
375 + ...(added ? ["new file mode 100644"] : removed ? ["deleted file mode 100644"] : []),
376 + ...(oldPath !== file.filename
377 + ? [
378 + `similarity index ${file.patch || Number(file.changes ?? 0) > 0 ? 0 : 100}%`,
379 + `${action} from ${quoteGitPatchPath(oldPath)}`,
380 + `${action} to ${quoteGitPatchPath(file.filename)}`,
381 + ]
382 + : []),
383 + ];
384 + if (!file.patch) return `${header.join("\n")}\n`;
385 + return [
386 + ...header,
387 + `--- ${added ? "/dev/null" : before}`,
388 + `+++ ${removed ? "/dev/null" : after}`,
389 + file.patch.endsWith("\n") ? file.patch.slice(0, -1) : file.patch,
390 + ]
391 + .join("\n")
392 + .concat("\n");
393 + })
394 + .join("");
395 +}
396 +
397 +/** `42` or `#42`; anything else, such as `123/fix`, is a branch. */
398 +function originPullNumber(reference: string): number | null {
399 + const match = /^#?(\d+)$/u.exec(reference.trim());
400 + const number = Number(match?.[1]);
401 + return Number.isSafeInteger(number) && number > 0 ? number : null;
402 +}
403 +
404 +/** A cursor.com pull request URL names its own repository, which need not be the checkout's. */
405 +export function pullReference(reference: string) {
406 + const trimmed = reference.trim();
407 + if (!URL.canParse(trimmed)) return { repository: null, number: originPullNumber(trimmed) };
408 + // Another host's pull request URL must not resolve to the same number here.
409 + const link = parseChangeRequestUrl(new URL(trimmed));
410 + return { repository: link?.repository ?? null, number: link?.number ?? null };
411 +}
packages/source-control-cursor-origin/src/shared/definition.ts new
+82
@@ -0,0 +1,82 @@
1 +import { SourceControlProviderKind } from "@t3tools/contracts";
2 +import {
3 + defineSourceControl,
4 + isChangeRequestInProjectRepository,
5 + isChangeRequestOnProjectHost,
6 + type ParsedChangeRequestUrl,
7 + projectChangeRequestHost,
8 +} from "@t3tools/source-control-core/shared/definition";
9 +import { icon } from "./icon.ts";
10 +
11 +/** Origin's git host; its browser pages live under `cursor.com/codebase` instead. */
12 +export const CURSOR_ORIGIN_GIT_HOST = "origin.cursor.com";
13 +export const CURSOR_ORIGIN_WEB_BASE_URL = "https://cursor.com/codebase";
14 +
15 +const CHECKOUT_COMMAND = /^origin\s+pr\s+checkout\s+(.+)$/i;
16 +const CHANGE_REQUEST_PATH = /^\/codebase\/([^/]+\/[^/]+)\/pull\/(\d+)(?:\/|$)/u;
17 +
18 +const KIND = SourceControlProviderKind.make("cursor-origin");
19 +
20 +/** A cursor.com page names a repository on Origin's git host, which is what projects key under. */
21 +export function parseChangeRequestUrl(url: URL): ParsedChangeRequestUrl | null {
22 + const hostname = url.hostname.toLowerCase();
23 + if (url.protocol !== "https:" && url.protocol !== "http:") return null;
24 + if (hostname !== "cursor.com" && hostname !== "www.cursor.com") return null;
25 + const match = CHANGE_REQUEST_PATH.exec(url.pathname);
26 + const repository = match?.[1];
27 + const number = Number(match?.[2]);
28 + return repository && Number.isSafeInteger(number) && number > 0
29 + ? {
30 + host: CURSOR_ORIGIN_GIT_HOST,
31 + repository: repository.toLowerCase(),
32 + number,
33 + repositoryUrl: `${CURSOR_ORIGIN_WEB_BASE_URL}/${repository}`,
34 + }
35 + : null;
36 +}
37 +
38 +export const definition = defineSourceControl({
39 + kind: KIND,
40 + label: "Cursor Origin",
41 + pickerLabel: "Cursor Origin",
42 + icon,
43 + searchKeywords: ["cursor", "origin"],
44 + changeRequest: {
45 + shortLabel: "PR",
46 + shortLabelWithArticle: "a PR",
47 + singular: "pull request",
48 + plural: "pull requests",
49 + },
50 + repositoryPathHint: "owner/repo",
51 + publicHost: CURSOR_ORIGIN_GIT_HOST,
52 + publishDescription: CURSOR_ORIGIN_GIT_HOST,
53 + publishHost: () => CURSOR_ORIGIN_GIT_HOST,
54 + newRepositoryOwner: (account) => ({ owner: account }),
55 + defaultCloneTransport: "https",
56 + changeRequestUrl: ({ repository, number }) =>
57 + `${CURSOR_ORIGIN_WEB_BASE_URL}/${repository}/pull/${number}`,
58 + parseChangeRequestUrl,
59 + changeRequestUrlFromReferenceAutolink: () => null,
60 + changeRequestActions: new Set(["merge", "ready", "draft", "close", "reopen"] as const),
61 + checkoutCommand: ({ number }) => `origin pr checkout ${number}`,
62 + changeRequestCloseCommand: /\borigin\s+pr\s+(?:merge|close)\b/u,
63 + authorProfileUrl: () => null,
64 + reviewSummaryRequired: () => false,
65 + checkoutCommandArgument: (input) => CHECKOUT_COMMAND.exec(input)?.[1]?.trim() ?? null,
66 + isChangeRequestReference: (url) => {
67 + try {
68 + return parseChangeRequestUrl(new URL(url)) !== null;
69 + } catch {
70 + return false;
71 + }
72 + },
73 + checkoutChangeRequestHost: (identity) => projectChangeRequestHost(identity, KIND),
74 + recognizeRemote: ({ hostname }) =>
75 + hostname === CURSOR_ORIGIN_GIT_HOST
76 + ? { kind: KIND, name: "Cursor Origin", baseUrl: CURSOR_ORIGIN_WEB_BASE_URL }
77 + : null,
78 + isChangeRequestInRepository: (identity, link) =>
79 + isChangeRequestInProjectRepository(projectChangeRequestHost(identity, KIND), identity, link),
80 + canReadChangeRequestOnHost: (identity, link) =>
81 + isChangeRequestOnProjectHost(projectChangeRequestHost(identity, KIND), identity, link),
82 +});
packages/source-control-cursor-origin/src/shared/icon.ts new
+12
@@ -0,0 +1,12 @@
1 +import type { SourceControlIcon } from "@t3tools/source-control-core/shared/definition";
2 +
3 +/** The Cursor mark, drawn in the text colour like GitHub's. */
4 +export const icon: SourceControlIcon = {
5 + viewBox: "0 0 466.73 532.09",
6 + paths: [
7 + {
8 + d: "M457.43,125.94L244.42,2.96c-6.84-3.95-15.28-3.95-22.12,0L9.3,125.94c-5.75,3.32-9.3,9.46-9.3,16.11v247.99c0,6.65,3.55,12.79,9.3,16.11l213.01,122.98c6.84,3.95,15.28,3.95,22.12,0l213.01-122.98c5.75-3.32,9.3-9.46,9.3-16.11v-247.99c0-6.65-3.55-12.79-9.3-16.11h-.01ZM444.05,151.99l-205.63,356.16c-1.39,2.4-5.06,1.42-5.06-1.36v-233.21c0-4.66-2.49-8.97-6.53-11.31L24.87,145.67c-2.4-1.39-1.42-5.06,1.36-5.06h411.26c5.84,0,9.49,6.33,6.57,11.39h-.01Z",
9 + fill: "currentColor",
10 + },
11 + ],
12 +};
packages/source-control-cursor-origin/tsconfig.json new
+7
@@ -0,0 +1,7 @@
1 +{
2 + "extends": "../../tsconfig.base.json",
3 + "compilerOptions": {
4 + "types": ["node"]
5 + },
6 + "include": ["src"]
7 +}
packages/source-control-definitions/package.json
+1
@@ -15,6 +15,7 @@
15 "@t3tools/source-control-azure-devops": "workspace:*",
16 "@t3tools/source-control-bitbucket": "workspace:*",
17 "@t3tools/source-control-core": "workspace:*",
18 + "@t3tools/source-control-cursor-origin": "workspace:*",
19 "@t3tools/source-control-forgejo": "workspace:*",
20 "@t3tools/source-control-gitcafe": "workspace:*",
21 "@t3tools/source-control-github": "workspace:*",
packages/source-control-definitions/src/registry.ts
+10 -2
@@ -1,6 +1,7 @@
1 import * as AzureDevOps from "@t3tools/source-control-azure-devops/shared/definition";
2 import * as Bitbucket from "@t3tools/source-control-bitbucket/shared/definition";
3 import { makeSourceControlDefinitionRegistry } from "@t3tools/source-control-core/shared/definition";
4 +import * as CursorOrigin from "@t3tools/source-control-cursor-origin/shared/definition";
5 import * as Forgejo from "@t3tools/source-control-forgejo/shared/definition";
6 import * as GitCafe from "@t3tools/source-control-gitcafe/shared/definition";
7 import * as GitHub from "@t3tools/source-control-github/shared/definition";
@@ -10,12 +11,14 @@ export { canonicalizePullRequestUrl as canonicalizeGitCafePullRequestUrl } from
11
12 /**
13 * GitHub comes first to preserve the client default for repositories with an unknown host.
13 - * GitCafe claims URLs first because GitHub and Forgejo accept the same routes on any hostname.
14 + * GitCafe and Cursor Origin claim URLs first because GitHub and Forgejo accept the same routes on
15 + * any hostname.
16 * Remote recognition needs its own order because host labels can overlap (`gitea.github.example`).
17 */
18 export const builtInSourceControlDefinitions = makeSourceControlDefinitionRegistry(
19 [
20 GitHub.definition,
21 + CursorOrigin.definition,
22 GitLab.definition,
23 GitCafe.definition,
24 Forgejo.definition,
@@ -23,9 +26,14 @@ export const builtInSourceControlDefinitions = makeSourceControlDefinitionRegist
26 AzureDevOps.definition,
27 ],
28 {
26 - claimChangeRequestUrlsFirst: [GitCafe.definition.kind, AzureDevOps.definition.kind],
29 + claimChangeRequestUrlsFirst: [
30 + GitCafe.definition.kind,
31 + CursorOrigin.definition.kind,
32 + AzureDevOps.definition.kind,
33 + ],
34 recognizeRemotesIn: [
35 GitCafe.definition.kind,
36 + CursorOrigin.definition.kind,
37 Forgejo.definition.kind,
38 GitHub.definition.kind,
39 GitLab.definition.kind,
pnpm-lock.yaml
+37
@@ -893,6 +893,9 @@ importers:
893 '@t3tools/source-control-core':
894 specifier: workspace:*
895 version: link:../../packages/source-control-core
896 + '@t3tools/source-control-cursor-origin':
897 + specifier: workspace:*
898 + version: link:../../packages/source-control-cursor-origin
899 '@t3tools/source-control-definitions':
900 specifier: workspace:*
901 version: link:../../packages/source-control-definitions
@@ -2211,6 +2214,37 @@ importers:
2214 specifier: 1.4.0
2215 version: 1.4.0(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0)
2216
2217 + packages/source-control-cursor-origin:
2218 + dependencies:
2219 + '@effect/platform-node':
2220 + specifier: 4.1.2
2221 + version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6)
2222 + '@t3tools/contracts':
2223 + specifier: workspace:*
2224 + version: link:../contracts
2225 + '@t3tools/provider-core':
2226 + specifier: workspace:*
2227 + version: link:../provider-core
2228 + '@t3tools/shared':
2229 + specifier: workspace:*
2230 + version: link:../shared
2231 + '@t3tools/source-control-core':
2232 + specifier: workspace:*
2233 + version: link:../source-control-core
2234 + effect:
2235 + specifier: 4.1.2
2236 + version: 4.1.2
2237 + devDependencies:
2238 + '@effect/vitest':
2239 + specifier: 4.1.2
2240 + version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0)
2241 + '@types/node':
2242 + specifier: 24.12.4
2243 + version: 24.12.4
2244 + vite-plus:
2245 + specifier: 1.4.0
2246 + version: 1.4.0(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0)
2247 +
2248 packages/source-control-definitions:
2249 dependencies:
2250 '@t3tools/source-control-azure-devops':
@@ -2222,6 +2256,9 @@ importers:
2256 '@t3tools/source-control-core':
2257 specifier: workspace:*
2258 version: link:../source-control-core
2259 + '@t3tools/source-control-cursor-origin':
2260 + specifier: workspace:*
2261 + version: link:../source-control-cursor-origin
2262 '@t3tools/source-control-forgejo':
2263 specifier: workspace:*
2264 version: link:../source-control-forgejo
scripts/release-smoke.ts
+1
@@ -46,6 +46,7 @@ const workspaceFiles = [
46 "packages/source-control-azure-devops/package.json",
47 "packages/source-control-bitbucket/package.json",
48 "packages/source-control-core/package.json",
49 + "packages/source-control-cursor-origin/package.json",
50 "packages/source-control-definitions/package.json",
51 "packages/source-control-forgejo/package.json",
52 "packages/source-control-gitcafe/package.json",