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

main
ts 354 lines 13.7 KB
Raw
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 createsDraftChangeRequests: true,
197 createChangeRequest: Effect.fn("OriginSourceControlProvider.createChangeRequest")(
198 function* (input) {
199 const repository = input.target?.repository ?? (yield* cli.resolveRepository(input));
200 // Origin creates drafts unless told otherwise, so `draft` is always sent.
201 yield* cli.api(
202 {
203 cwd: input.cwd,
204 operation: "createChangeRequest",
205 method: "POST",
206 path: `${OriginCli.originRepositoryPath(repository)}/pulls`,
207 body: {
208 title: input.title,
209 body: yield* fs.readFileString(input.bodyFile),
210 head: SourceControlProvider.sourceBranch(input),
211 base: input.target?.refName ?? input.baseRefName,
212 draft: input.draft === true,
213 },
214 },
215 Schema.Unknown,
216 );
217 },
218 (effect, input) =>
219 effect.pipe(mapError("createChangeRequest", input.cwd, { reference: input.headSelector })),
220 ),
221
222 getRepositoryCloneUrls: Effect.fn("OriginSourceControlProvider.getRepositoryCloneUrls")(
223 function* (input) {
224 const repository = yield* getRepository(
225 input.cwd,
226 input.repository,
227 "getRepositoryCloneUrls",
228 );
229 return cloneUrls(repository, input.repository);
230 },
231 (effect, input) =>
232 effect.pipe(
233 mapError("getRepositoryCloneUrls", input.cwd, { repository: input.repository }),
234 ),
235 ),
236
237 createRepository: Effect.fn("OriginSourceControlProvider.createRepository")(
238 function* (input) {
239 if (input.visibility === "public")
240 return yield* new OriginCli.OriginCliError({
241 operation: "createRepository",
242 cwd: input.cwd,
243 reason: "failed",
244 detail: "Cursor Origin repositories are private. Choose private visibility.",
245 });
246 const parts = input.repository.split("/");
247 if (parts.length > 2 || parts.some((part) => part.trim().length === 0))
248 return yield* new OriginCli.OriginCliError({
249 operation: "createRepository",
250 cwd: input.cwd,
251 reason: "failed",
252 detail: "Specify an Origin repository as owner/name or name.",
253 });
254 const [owner, name] =
255 parts.length === 2 ? parts : [yield* cli.personalNamespace(input.cwd), input.repository];
256 yield* cli.api(
257 {
258 cwd: input.cwd,
259 operation: "createRepository",
260 method: "POST",
261 path: `/v1/origin/repos/${encodeURIComponent(owner ?? "")}`,
262 body: { name },
263 },
264 OriginRepositorySchema,
265 );
266 // Origin creates repositories internal (visible to the whole team) and only takes a
267 // visibility on update, so the repository is made private straight after.
268 const madePrivate = yield* cli
269 .api(
270 {
271 cwd: input.cwd,
272 operation: "createRepository",
273 method: "PATCH",
274 path: OriginCli.originRepositoryPath(`${owner}/${name}`),
275 body: { visibility: "private" },
276 },
277 OriginRepositorySchema,
278 )
279 .pipe(
280 Effect.retry({
281 times: 2,
282 schedule: Schedule.spaced("1 second"),
283 while: (error) =>
284 error.reason !== "rate-limited" && error.reason !== "unauthenticated",
285 }),
286 Effect.mapError(
287 (cause) =>
288 new OriginCli.OriginCliError({
289 operation: "createRepository",
290 cwd: input.cwd,
291 reason: cause.reason,
292 ...(cause.retryAt === undefined ? {} : { retryAt: cause.retryAt }),
293 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.`,
294 cause,
295 }),
296 ),
297 );
298 return cloneUrls(madePrivate, `${owner}/${name}`);
299 },
300 (effect, input) =>
301 effect.pipe(mapError("createRepository", input.cwd, { repository: input.repository })),
302 ),
303
304 getDefaultBranch: Effect.fn("OriginSourceControlProvider.getDefaultBranch")(
305 function* (input) {
306 const repository = yield* cli.resolveRepository(input);
307 return (
308 (yield* getRepository(input.cwd, repository, "getDefaultBranch")).defaultBranch ?? null
309 );
310 },
311 (effect, input) => effect.pipe(mapError("getDefaultBranch", input.cwd)),
312 ),
313
314 checkoutChangeRequest: Effect.fn("OriginSourceControlProvider.checkoutChangeRequest")(
315 function* (input) {
316 const repository = yield* cli.resolveRepository(input);
317 const { repository: linked, number } = pullReference(input.reference);
318 const reference = input.reference.trim();
319 // The CLI reads a leading dash as a flag and ignores a target after `--`; no branch starts
320 // with one.
321 if (number === null && reference.startsWith("-"))
322 return yield* new OriginCli.OriginCliError({
323 operation: "checkoutChangeRequest",
324 cwd: input.cwd,
325 reason: "not-found",
326 detail: "Specify a pull request number, branch, or Cursor Origin pull request URL.",
327 });
328 if (linked !== null && linked !== repository.toLowerCase())
329 return yield* new OriginCli.OriginCliError({
330 operation: "checkoutChangeRequest",
331 cwd: input.cwd,
332 reason: "not-found",
333 detail: `That pull request is in ${linked}, not this checkout's ${repository}.`,
334 });
335 yield* cli.execute({
336 cwd: input.cwd,
337 operation: "checkoutChangeRequest",
338 args: [
339 "pr",
340 "checkout",
341 "-R",
342 repository,
343 "--remote",
344 input.context?.remoteName ?? (yield* git.resolvePrimaryRemoteName(input.cwd)),
345 ...(input.force ? ["--force"] : []),
346 number === null ? reference : String(number),
347 ],
348 });
349 },
350 (effect, input) =>
351 effect.pipe(mapError("checkoutChangeRequest", input.cwd, { reference: input.reference })),
352 ),
353 });
354 });