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

main
ts 344 lines 10.1 KB
Raw
1 import * as Issues from "@distilled.cloud/github/issues";
2 import * as Repos from "@distilled.cloud/github/repos";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { dedent } from "alchemy/Util/dedent";
7 import * as Effect from "effect/Effect";
8 import * as Stream from "effect/Stream";
9 import { withBaseUrl, gitHubBaseUrlChanged } from "./BaseUrl.ts";
10 import type * as GitHub from "./Providers.ts";
11
12 export interface IssueProps {
13 /**
14 * Repository owner (user or organization).
15 */
16 owner: string;
17
18 /**
19 * Repository name.
20 */
21 repository: string;
22
23 /**
24 * Issue title.
25 */
26 title: string;
27
28 /**
29 * Issue body (supports GitHub Markdown).
30 *
31 * The body is automatically dedented, so you can use indented template
32 * literals without worrying about leading whitespace. Accepts
33 * `Output<string>` at the call site via `Output.interpolate` to embed
34 * resource attributes that are not yet resolved.
35 */
36 body?: string;
37
38 /**
39 * State of the issue. Use "open" to reopen a closed issue or "closed" to
40 * close an open issue.
41 * @default "open"
42 */
43 state?: "open" | "closed";
44
45 /**
46 * Labels to attach to the issue. The provided list fully replaces any
47 * existing labels.
48 */
49 labels?: string[];
50
51 /**
52 * Assignees (user logins) to assign to the issue. The provided list fully
53 * replaces existing assignees.
54 */
55 assignees?: string[];
56
57 /**
58 * Milestone number to assign to the issue. Use `null` to remove milestone.
59 */
60 milestone?: number | null;
61
62 /**
63 * Override the GitHub host or API base URL for this resource only (e.g.
64 * `github.example.com` for GitHub Enterprise). Falls back to
65 * `GitHub.providers({ baseUrl })`, then to the host resolved by the auth
66 * provider. Changing it replaces the resource — the same name on a
67 * different GitHub instance is a different physical resource.
68 */
69 baseUrl?: string;
70 }
71
72 export interface Issue extends Resource<
73 "GitHub.Issue",
74 IssueProps,
75 {
76 /**
77 * The numeric ID of the issue in GitHub.
78 */
79 issueNumber: number;
80
81 /**
82 * GraphQL node ID of the issue.
83 */
84 nodeId: string;
85
86 /**
87 * URL to view the issue in a browser.
88 */
89 htmlUrl: string;
90
91 /**
92 * State of the issue (open or closed).
93 */
94 state: "open" | "closed";
95
96 /**
97 * ISO-8601 timestamp of when the issue was created.
98 */
99 createdAt: string;
100
101 /**
102 * ISO-8601 timestamp of the last update.
103 */
104 updatedAt: string;
105 },
106 never,
107 GitHub.Providers
108 > {}
109
110 /**
111 * A GitHub repository issue.
112 *
113 * `Issue` manages the lifecycle of a single issue in a repository. Issues are
114 * created on the first deploy and updated in place on subsequent deploys when
115 * properties change. By default, issues are retained on destruction to preserve
116 * discussion history. Pipe the resource through `destroy()` to close the issue
117 * on destruction instead; its discussion remains on GitHub.
118 *
119 * Authentication is resolved via the GitHub `Credentials` service supplied by
120 * `GitHub.providers()` (env, stored PAT, `gh` CLI, or OAuth). The token needs
121 * `repo` scope for private repositories or `public_repo` for public ones.
122 *
123 * ### Creating Issues
124 * **Example:** Create a Basic Issue
125 * ```typescript
126 * const issue = yield* GitHub.Issue("bug-report", {
127 * owner: "my-org",
128 * repository: "my-repo",
129 * title: "Bug: Application crashes on startup",
130 * body: "## Description\n\nThe application crashes when...",
131 * })
132 * ```
133 *
134 * **Example:** Issue with Labels and Assignees
135 * ```typescript
136 * const issue = yield* GitHub.Issue("feature-request", {
137 * owner: "my-org",
138 * repository: "my-repo",
139 * title: "Feature: Add dark mode",
140 * body: "Users have requested...",
141 * labels: ["enhancement", "ui"],
142 * assignees: ["developer1"],
143 * })
144 * ```
145 *
146 * ### Updating Issues
147 * Deploy with the same logical ID and different properties to update the
148 * existing issue in place rather than creating a new one.
149 *
150 * **Example:** Update Issue State
151 * ```typescript
152 * const issue = yield* GitHub.Issue("resolved-bug", {
153 * owner: "my-org",
154 * repository: "my-repo",
155 * title: "Bug: Application crashes on startup",
156 * body: "This has been resolved.",
157 * state: "closed",
158 * })
159 * ```
160 *
161 * ### Issue with Milestone
162 * **Example:** Assign to Milestone
163 * ```typescript
164 * const issue = yield* GitHub.Issue("v1-task", {
165 * owner: "my-org",
166 * repository: "my-repo",
167 * title: "Implement authentication",
168 * milestone: 1,
169 * })
170 * ```
171 *
172 * ### Tracking Infrastructure Changes
173 * A common pattern is creating issues to track infrastructure changes or
174 * deployment status.
175 *
176 * **Example:** Infrastructure Status Issue
177 * ```typescript
178 * yield* GitHub.Issue("infra-status", {
179 * owner: "my-org",
180 * repository: "my-repo",
181 * title: "Infrastructure Status",
182 * body: Output.interpolate`
183 * ## Current Status
184 *
185 * **Database:** ${database.endpoint}
186 * **Cache:** ${cache.endpoint}
187 * `,
188 * labels: ["infrastructure"],
189 * })
190 * ```
191 *
192 * @resource
193 * @product Issue
194 */
195 export const Issue = Resource<Issue>("GitHub.Issue", {
196 defaultRemovalPolicy: "retain",
197 });
198
199 export const IssueProvider = () =>
200 Provider.succeed(Issue, {
201 stables: ["issueNumber", "nodeId"],
202
203 // An issue belongs to (host, owner, repository) — its server-assigned
204 // number is meaningless elsewhere, so moving it replaces the resource:
205 // a fresh issue is created on the new repository, and the old one is
206 // retained by default (matching the resource's `retain` removal policy).
207 diff: Effect.fn(function* ({ news, olds }) {
208 if (!isResolved(news)) return;
209 if (olds === undefined) return;
210 if (
211 news.owner !== olds.owner ||
212 news.repository !== olds.repository ||
213 (yield* gitHubBaseUrlChanged(olds, news))
214 ) {
215 return { action: "replace" };
216 }
217 }),
218
219 reconcile: Effect.fn(
220 function* ({ news, output }) {
221 const body = news.body ? dedent(news.body) : "";
222 const state = news.state ?? "open";
223 const labels = news.labels ?? [];
224 const assignees = news.assignees ?? [];
225 const milestone = news.milestone ?? null;
226
227 let data =
228 output?.issueNumber !== undefined
229 ? yield* Issues.get({
230 owner: news.owner,
231 repo: news.repository,
232 issue_number: output.issueNumber,
233 }).pipe(Effect.catchTag(["NotFound", "Gone"], () => Effect.undefined))
234 : undefined;
235
236 if (data === undefined) {
237 data = yield* Issues.create({
238 owner: news.owner,
239 repo: news.repository,
240 title: news.title,
241 body,
242 labels,
243 assignees,
244 milestone: milestone ?? undefined,
245 });
246 }
247
248 const sameNames = (observed: string[], desired: string[]) =>
249 JSON.stringify(observed.map((name) => name.toLowerCase()).sort()) ===
250 JSON.stringify(desired.map((name) => name.toLowerCase()).sort());
251
252 // Creation always opens an issue; sync also applies the desired initial state.
253 if (
254 data.title !== news.title ||
255 (data.body ?? "") !== body ||
256 data.state !== state ||
257 !sameNames(
258 data.labels.map((label) => (typeof label === "string" ? label : (label.name ?? ""))),
259 labels,
260 ) ||
261 !sameNames(
262 (data.assignees ?? []).map((assignee) => assignee.login),
263 assignees,
264 ) ||
265 (data.milestone?.number ?? null) !== milestone
266 ) {
267 const issueNumber = data.number;
268 data = yield* Issues.update({
269 owner: news.owner,
270 repo: news.repository,
271 issue_number: issueNumber,
272 title: news.title,
273 body,
274 state,
275 labels,
276 assignees,
277 milestone,
278 });
279 }
280 return {
281 issueNumber: data.number,
282 nodeId: data.node_id,
283 htmlUrl: data.html_url,
284 state: data.state as "open" | "closed",
285 createdAt: data.created_at,
286 updatedAt: data.updated_at,
287 };
288 },
289 (effect, { news }) => effect.pipe(withBaseUrl(news.baseUrl)),
290 ),
291
292 // Enumerate every issue across the repositories the token can see.
293 list: Effect.fn(function* () {
294 const repos = yield* Stream.runCollect(
295 Repos.listForAuthenticatedUser.items({ per_page: 100 }),
296 );
297 const perRepo = yield* Effect.forEach(
298 repos,
299 (repo) =>
300 Stream.runCollect(
301 Issues.listForRepo.items({
302 owner: repo.owner.login,
303 repo: repo.name,
304 state: "all",
305 per_page: 100,
306 }),
307 ).pipe(
308 // Filter out pull requests (they appear in issues API)
309 Effect.map((issues) =>
310 issues
311 .filter((issue) => !issue.pull_request)
312 .map((issue) => ({
313 issueNumber: issue.number,
314 nodeId: issue.node_id,
315 htmlUrl: issue.html_url,
316 state: issue.state as "open" | "closed",
317 createdAt: issue.created_at,
318 updatedAt: issue.updated_at,
319 })),
320 ),
321 // Repositories the token can list but not read, or with issues disabled.
322 Effect.catchTag(["Forbidden", "NotFound", "Gone"], () => Effect.succeed([])),
323 ),
324 { concurrency: 10 },
325 );
326
327 return perRepo.flat();
328 }),
329
330 delete: Effect.fn(
331 function* ({ olds, output }) {
332 // Opted-in destruction closes the issue without deleting its discussion.
333 if (output?.issueNumber !== undefined) {
334 yield* Issues.update({
335 owner: olds.owner,
336 repo: olds.repository,
337 issue_number: output.issueNumber,
338 state: "closed",
339 }).pipe(Effect.catchTag(["NotFound", "Gone"], () => Effect.void));
340 }
341 },
342 (effect, { olds }) => effect.pipe(withBaseUrl(olds.baseUrl)),
343 ),
344 });