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

main
ts 542 lines 17.5 KB
Raw
1 import { isResolved } from "alchemy/Diff";
2 import * as Provider from "alchemy/Provider";
3 import { Resource } from "alchemy/Resource";
4 import { dedent } from "alchemy/Util/dedent";
5 import { exec } from "alchemy/Util/exec";
6 import * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import * as FileSystem from "effect/FileSystem";
9 import * as Path from "effect/Path";
10 import * as ChildProcess from "effect/process/ChildProcess";
11 import * as Redacted from "effect/Redacted";
12 import * as Schedule from "effect/Schedule";
13 import { effectiveGitHubBaseUrl, gitHubBaseUrlChanged } from "./BaseUrl.ts";
14 import { Credentials } from "./Credentials.ts";
15 import type * as GitHub from "./Providers.ts";
16
17 export interface WikiPageProps {
18 /**
19 * Repository owner (user or organization).
20 */
21 owner: string;
22
23 /**
24 * Repository name.
25 */
26 repository: string;
27
28 /**
29 * Page title (e.g. `Home`, `Getting Started`). Whitespace becomes hyphens
30 * in the page name. Changing that name replaces the page (creates a new
31 * page and deletes the old one if opted in via `allowDelete`).
32 */
33 title: string;
34
35 /**
36 * Page content (supports GitHub Markdown, AsciiDoc, MediaWiki, and more
37 * depending on the file extension derived from `format`).
38 *
39 * The content is automatically dedented, so you can use indented template
40 * literals without worrying about leading whitespace. Accepts
41 * `Output<string>` at the call site via `Output.interpolate` to embed
42 * resource attributes that are not yet resolved.
43 */
44 content: string;
45
46 /**
47 * Commit message for creating or updating the page.
48 * @default "Update {title}"
49 */
50 message?: string;
51
52 /**
53 * Page format/markup language. The format is appended to the page name as
54 * an extension (e.g. `markdown` → `Page.md`, `asciidoc` → `Page.asciidoc`).
55 * @default "markdown"
56 */
57 format?: "markdown" | "asciidoc" | "mediawiki" | "org" | "pod" | "rdoc" | "rest" | "textile";
58
59 /**
60 * Whether to allow deletion of the page when the resource is destroyed.
61 * By default, wiki pages are never deleted to preserve documentation history.
62 * @default false
63 */
64 allowDelete?: boolean;
65
66 /**
67 * Override the GitHub host or API base URL for this resource only (e.g.
68 * `github.example.com` for GitHub Enterprise). Falls back to
69 * `GitHub.providers({ baseUrl })`, then to the host resolved by the auth
70 * provider. Changing it replaces the resource — the same name on a
71 * different GitHub instance is a different physical resource. Authenticated
72 * wiki Git operations require HTTPS.
73 */
74 baseUrl?: string;
75 }
76
77 export interface WikiPage extends Resource<
78 "GitHub.WikiPage",
79 WikiPageProps,
80 {
81 /**
82 * The page title.
83 */
84 title: string;
85
86 /**
87 * The page name in URL form (e.g. `Home`, `Getting-Started`).
88 */
89 pageName: string;
90
91 /**
92 * URL to view the page in a browser.
93 */
94 htmlUrl: string;
95
96 /**
97 * SHA hash of the current page revision.
98 */
99 sha: string;
100 },
101 never,
102 GitHub.Providers
103 > {}
104
105 /**
106 * A GitHub wiki page.
107 *
108 * `WikiPage` manages the lifecycle of a page in a repository's wiki. Wiki
109 * pages are created on first deploy and updated in place on subsequent
110 * deploys when the `content` changes. By default, pages are never deleted to
111 * preserve documentation history — set `allowDelete: true` to opt in.
112 *
113 * The repository's wiki must be enabled (`hasWiki: true` on the Repository
114 * resource) and initialized by creating its first page in the GitHub web UI.
115 * Enabling the wiki or setting `autoInit` on the repository does not initialize
116 * the separate wiki Git repository. An inaccessible or uninitialized wiki
117 * produces `WikiRepositoryUnavailable` with setup instructions.
118 *
119 * Git must be installed on the deployment machine. Pages are managed through
120 * the wiki's Git repository, not the GitHub REST API. Each content or format
121 * change creates a commit; unchanged pages do not. Concurrent pushes are
122 * retried against a fresh checkout without force-pushing. Deletion removes the
123 * current page file, not its Git history. Authentication uses a transient
124 * process-environment header; tokens are not stored in clone URLs or Git config.
125 *
126 * Authentication is resolved via the GitHub `Credentials` service supplied by
127 * `GitHub.providers()` (env, stored PAT, `gh` CLI, or OAuth). The token needs
128 * `repo` scope for private repositories or `public_repo` for public ones.
129 * ### Creating Wiki Pages
130 * **Example:** Basic Wiki Page
131 * ```typescript
132 * const home = yield* GitHub.WikiPage("home", {
133 * owner: "my-org",
134 * repository: "my-repo",
135 * title: "Home",
136 * content: "Welcome to the wiki!",
137 * });
138 * ```
139 *
140 * **Example:** Formatted Wiki Page
141 * ```typescript
142 * yield* GitHub.WikiPage("getting-started", {
143 * owner: "my-org",
144 * repository: "my-repo",
145 * title: "Getting Started",
146 * content: `
147 * # Getting Started
148 *
149 * Install the package:
150 *
151 * \`\`\`bash
152 * npm install my-package
153 * \`\`\`
154 * `,
155 * format: "markdown",
156 * message: "Add getting started guide",
157 * });
158 * ```
159 *
160 * ### Updating Wiki Pages
161 * Deploy with the same logical ID and a different `content` to update the
162 * existing page in place rather than creating a new one.
163 *
164 * **Example:** Update Page Content
165 * ```typescript
166 * yield* GitHub.WikiPage("api-docs", {
167 * owner: "my-org",
168 * repository: "my-repo",
169 * title: "API Documentation",
170 * content: "Updated API documentation content",
171 * });
172 * ```
173 *
174 * ### Alternative Formats
175 * **Example:** AsciiDoc Page
176 * ```typescript
177 * yield* GitHub.WikiPage("architecture", {
178 * owner: "my-org",
179 * repository: "my-repo",
180 * title: "Architecture",
181 * content: `
182 * = System Architecture
183 *
184 * == Overview
185 *
186 * The system is built with...
187 * `,
188 * format: "asciidoc",
189 * });
190 * ```
191 *
192 * ### Deleting Wiki Pages
193 * **Example:** Allow Page Deletion
194 * ```typescript
195 * const temp = yield* GitHub.WikiPage("temp-page", {
196 * owner: "my-org",
197 * repository: "my-repo",
198 * title: "Temporary Page",
199 * content: "This page can be deleted",
200 * allowDelete: true,
201 * });
202 * ```
203 *
204 * ### Wiring with Other Resources
205 * **Example:** Create Wiki Pages for a Repository
206 * Deploy the repository first and create its first wiki page in the GitHub
207 * web UI before adding `WikiPage` to the stack.
208 * ```typescript
209 * import * as Output from "alchemy/Output";
210 *
211 * const repo = yield* GitHub.Repository("docs", {
212 * owner: "my-org",
213 * name: "docs",
214 * hasWiki: true,
215 * autoInit: true,
216 * });
217 *
218 * yield* GitHub.WikiPage("home", {
219 * owner: repo.owner!,
220 * repository: Output.map(repo.fullName, (fullName) => fullName.split("/")[1]!),
221 * title: "Home",
222 * content: "Welcome to the documentation wiki!",
223 * });
224 * ```
225 *
226 * @resource
227 * @product Repository
228 */
229 export const WikiPage = Resource<WikiPage>("GitHub.WikiPage");
230
231 export class WikiRepositoryUnavailable extends Data.TaggedError("WikiRepositoryUnavailable")<{
232 readonly message: string;
233 }> {}
234
235 export class WikiGitError extends Data.TaggedError("WikiGitError")<{
236 readonly operation: string;
237 readonly reason: "missing" | "conflict" | "command";
238 readonly message: string;
239 }> {}
240
241 export class InvalidWikiPage extends Data.TaggedError("InvalidWikiPage")<{
242 readonly message: string;
243 }> {}
244
245 const extensions = {
246 markdown: ["md", "markdown", "mdown", "mkdn", "mkd"],
247 asciidoc: ["asciidoc", "adoc", "asc"],
248 mediawiki: ["mediawiki", "wiki"],
249 org: ["org"],
250 pod: ["pod"],
251 rdoc: ["rdoc"],
252 rest: ["rst", "rest"],
253 textile: ["textile"],
254 } as const;
255
256 export interface WikiRepository {
257 readonly remote: string;
258 readonly htmlUrl: string;
259 readonly token: Redacted.Redacted<string>;
260 }
261
262 const pageNameFor = (title: string) =>
263 Effect.gen(function* () {
264 if (
265 title.trim() !== title ||
266 title.length === 0 ||
267 // oxlint-disable-next-line no-control-regex -- rejects control characters on purpose
268 /[\x00-\x1f\x7f/\\]/.test(title) ||
269 title === "." ||
270 title === ".."
271 ) {
272 return yield* new InvalidWikiPage({
273 message:
274 "Wiki page titles must be nonempty, trimmed names without path separators or control characters.",
275 });
276 }
277 return title.replace(/\s+/g, "-");
278 });
279
280 export const wikiRepository = Effect.fn(function* (props: WikiPageProps) {
281 yield* pageNameFor(props.title);
282 if (
283 ![props.owner, props.repository].every(
284 (part) => /^[A-Za-z0-9_.-]+$/.test(part) && part !== "." && part !== "..",
285 )
286 ) {
287 return yield* new InvalidWikiPage({
288 message: "Wiki owner and repository must be GitHub names, not paths or URLs.",
289 });
290 }
291 const baseUrl = yield* effectiveGitHubBaseUrl(props.baseUrl);
292 const origin = yield* Effect.sync(() => {
293 const url = new URL(baseUrl);
294 // The API host's Git host: api.github.com → github.com, and
295 // api.<tenant>.ghe.com → <tenant>.ghe.com (data residency).
296 if (
297 url.hostname === "api.github.com" ||
298 (url.hostname.startsWith("api.") && url.hostname.endsWith(".ghe.com"))
299 ) {
300 url.hostname = url.hostname.slice(4);
301 }
302 return url.origin;
303 });
304 if (!origin.startsWith("https://")) {
305 return yield* new InvalidWikiPage({
306 message: "Wiki Git authentication requires an HTTPS GitHub host.",
307 });
308 }
309 const credentials = yield* yield* Credentials;
310 const repositoryUrl = `${origin}/${props.owner}/${props.repository}`;
311 return {
312 remote: `${repositoryUrl}.wiki.git`,
313 htmlUrl: `${repositoryUrl}/wiki`,
314 token: credentials.token,
315 } satisfies WikiRepository;
316 });
317
318 // Only the transient process environment contains the authorization header.
319 const gitEnvironment = Effect.fn(function* (repository: WikiRepository, directory: string) {
320 const path = yield* Path.Path;
321 const fs = yield* FileSystem.FileSystem;
322 const config = path.join(directory, "gitconfig");
323 yield* fs.writeFileString(config, "");
324 return yield* Effect.sync(() => ({
325 PATH: process.env.PATH,
326 SystemRoot: process.env.SystemRoot,
327 HOME: directory,
328 LC_ALL: "C",
329 GIT_TERMINAL_PROMPT: "0",
330 GIT_CONFIG_NOSYSTEM: "1",
331 GIT_CONFIG_GLOBAL: config,
332 GIT_CONFIG_COUNT: "1",
333 GIT_CONFIG_KEY_0: `http.${repository.remote}.extraHeader`,
334 GIT_CONFIG_VALUE_0: `Authorization: Basic ${Buffer.from(`x-access-token:${Redacted.value(repository.token)}`).toString("base64")}`,
335 GIT_AUTHOR_NAME: "Alchemy",
336 GIT_AUTHOR_EMAIL: "alchemy@users.noreply.github.com",
337 GIT_COMMITTER_NAME: "Alchemy",
338 GIT_COMMITTER_EMAIL: "alchemy@users.noreply.github.com",
339 }));
340 });
341
342 const git = Effect.fn(
343 function* (directory: string, env: Record<string, string | undefined>, ...args: string[]) {
344 const operation = args[0]!;
345 const result = yield* exec(
346 ChildProcess.make(
347 "git",
348 [
349 "--literal-pathspecs",
350 "-c",
351 "credential.helper=",
352 "-c",
353 "commit.gpgSign=false",
354 "-c",
355 "http.followRedirects=false",
356 ...args,
357 ],
358 { cwd: directory, env, extendEnv: false },
359 ),
360 ).pipe(
361 Effect.mapError(
362 () =>
363 new WikiGitError({
364 operation,
365 reason: "command",
366 message: `Unable to run git ${operation}. Ensure Git is installed and executable.`,
367 }),
368 ),
369 );
370 if (result.exitCode !== 0) {
371 const reason =
372 /Repository not found|repository '.+' (?:not found|does not exist)|does not appear to be a git repository/i.test(
373 result.stderr,
374 )
375 ? "missing"
376 : operation === "push" &&
377 /\[rejected\]|cannot lock ref|failed to update ref/i.test(result.stderr)
378 ? "conflict"
379 : "command";
380 // Git diagnostics can include server-controlled text or credentials.
381 return yield* new WikiGitError({
382 operation,
383 reason,
384 message: `git ${operation} failed (exit ${result.exitCode}). Check repository access and GitHub token permissions.`,
385 });
386 }
387 return result.stdout;
388 },
389 Effect.scoped,
390 Effect.timeout("20 seconds"),
391 );
392
393 const checkout = Effect.fn(function* (repository: WikiRepository) {
394 const fs = yield* FileSystem.FileSystem;
395 const path = yield* Path.Path;
396 const directory = yield* fs.makeTempDirectoryScoped({
397 prefix: "alchemy-wiki-",
398 });
399 const env = yield* gitEnvironment(repository, directory);
400 yield* git(directory, env, "clone", "--quiet", "--", repository.remote, "wiki").pipe(
401 Effect.catchTag("WikiGitError", (error) =>
402 Effect.fail(
403 error.reason === "missing"
404 ? new WikiRepositoryUnavailable({
405 message: `Cannot access ${repository.htmlUrl}. Enable the repository wiki and create its first page in the GitHub web UI before deploying WikiPage. Git cannot initialize a GitHub wiki that has never had a page. If it is already initialized, verify the repository name and token's repository access.`,
406 })
407 : error,
408 ),
409 ),
410 );
411 const cwd = path.join(directory, "wiki");
412 const run = (...args: string[]) => git(cwd, env, ...args);
413 const files = (yield* run("ls-files", "-z")).split("\0").filter(Boolean);
414 return { cwd, run, files };
415 });
416
417 type Checkout = Effect.Success<ReturnType<typeof checkout>>;
418
419 const pageFiles = (files: string[], pageName: string) =>
420 Object.values(extensions)
421 .flatMap((formats) => formats.map((extension) => `${pageName}.${extension}`))
422 .filter((file) => files.includes(file));
423
424 const attributes = Effect.fn(function* (
425 repository: WikiRepository,
426 props: WikiPageProps,
427 wiki: Checkout,
428 file: string,
429 ) {
430 return {
431 title: props.title,
432 pageName: props.title.replace(/\s+/g, "-"),
433 htmlUrl: `${repository.htmlUrl}/${encodeURIComponent(props.title.replace(/\s+/g, "-"))}`,
434 sha: (yield* wiki.run("log", "-1", "--format=%H", "--", file)).trim(),
435 } satisfies WikiPage["Attributes"];
436 });
437
438 export const readWikiPage = Effect.fn(
439 function* (repository: WikiRepository, props: WikiPageProps) {
440 const pageName = yield* pageNameFor(props.title);
441 const wiki = yield* checkout(repository);
442 const files = pageFiles(wiki.files, pageName);
443 const desired = `${pageName}.${extensions[props.format ?? "markdown"][0]}`;
444 const file = files.includes(desired) ? desired : files[0];
445 return file === undefined ? undefined : yield* attributes(repository, props, wiki, file);
446 },
447 Effect.scoped,
448 (effect) => effect.pipe(Effect.catchTag("WikiRepositoryUnavailable", () => Effect.undefined)),
449 );
450
451 const retryConcurrentPush = <A, E, R>(effect: Effect.Effect<A, E | WikiGitError, R>) =>
452 effect.pipe(
453 Effect.retry({
454 while: (error) => error instanceof WikiGitError && error.reason === "conflict",
455 schedule: Schedule.spaced("200 millis"),
456 times: 3,
457 }),
458 Effect.timeout("60 seconds"),
459 );
460
461 export const syncWikiPage = Effect.fn(
462 function* (repository: WikiRepository, props: WikiPageProps) {
463 const pageName = yield* pageNameFor(props.title);
464 const wiki = yield* checkout(repository);
465 const fs = yield* FileSystem.FileSystem;
466 const path = yield* Path.Path;
467 const files = pageFiles(wiki.files, pageName);
468 const file = `${pageName}.${extensions[props.format ?? "markdown"][0]}`;
469 const content = dedent(props.content);
470 const observed = wiki.files.includes(file)
471 ? yield* wiki.run("show", `HEAD:${file}`)
472 : undefined;
473 const mode = wiki.files.includes(file)
474 ? yield* wiki.run("ls-files", "--stage", "--", file)
475 : "";
476 if (
477 observed !== content ||
478 files.some((existing) => existing !== file) ||
479 mode.startsWith("120000")
480 ) {
481 if (files.length > 0) yield* wiki.run("rm", "--", ...files);
482 yield* fs.writeFileString(path.join(wiki.cwd, file), content);
483 yield* wiki.run("add", "--", file);
484 yield* wiki.run("commit", "--quiet", "-m", props.message ?? `Update ${props.title}`);
485 yield* wiki.run("push", "--quiet", "origin", "HEAD");
486 }
487 return yield* attributes(repository, props, wiki, file);
488 },
489 Effect.scoped,
490 retryConcurrentPush,
491 );
492
493 export const deleteWikiPage = Effect.fn(
494 function* (repository: WikiRepository, props: WikiPageProps) {
495 if (!props.allowDelete) return;
496 const pageName = yield* pageNameFor(props.title);
497 const wiki = yield* checkout(repository);
498 const files = pageFiles(wiki.files, pageName);
499 if (files.length === 0) return;
500 yield* wiki.run("rm", "--", ...files);
501 yield* wiki.run("commit", "--quiet", "-m", `Delete ${props.title}`);
502 yield* wiki.run("push", "--quiet", "origin", "HEAD");
503 },
504 Effect.scoped,
505 retryConcurrentPush,
506 (effect) => effect.pipe(Effect.catchTag("WikiRepositoryUnavailable", () => Effect.void)),
507 );
508
509 export const WikiPageProvider = () =>
510 Provider.succeed(WikiPage, {
511 stables: ["pageName"],
512
513 // Wiki pages have no account-wide enumeration API.
514 list: () => Effect.succeed([]),
515
516 // Replacement must not delete the successor when titles normalize identically.
517 diff: Effect.fn(function* ({ news, olds }) {
518 if (!isResolved(news)) return;
519 if (olds === undefined) return;
520 if (
521 news.owner !== olds.owner ||
522 news.repository !== olds.repository ||
523 news.title.replace(/\s+/g, "-") !== olds.title.replace(/\s+/g, "-") ||
524 (yield* gitHubBaseUrlChanged(olds, news))
525 ) {
526 return { action: "replace" };
527 }
528 }),
529
530 read: Effect.fn(function* ({ olds }) {
531 return yield* readWikiPage(yield* wikiRepository(olds), olds);
532 }),
533
534 reconcile: Effect.fn(function* ({ news }) {
535 return yield* syncWikiPage(yield* wikiRepository(news), news);
536 }),
537
538 delete: Effect.fn(function* ({ olds }) {
539 if (!olds.allowDelete) return;
540 yield* deleteWikiPage(yield* wikiRepository(olds), olds);
541 }),
542 });