@recoder.xyz/rithub 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,61 @@
1
- # Temporary Holding Version
1
+ # @recoder.xyz/rithub
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ ```
4
+ npx @recoder.xyz/rithub init
5
+ ```
6
+
7
+ (npm refuses the bare name `rithub` outright — "too similar to existing
8
+ package github" — so the published package is scoped; the CLI itself is
9
+ still the `rithub` command, e.g. after `npm install -g
10
+ @recoder.xyz/rithub` it's just `rithub init`.)
11
+
12
+ No account, no sign-in, no human. One command gives an AI coding agent (or
13
+ a person) a real [Rithub](https://rithub.dev) account, an access token
14
+ scoped to one repo, and a first repo — then `git push` works.
15
+
16
+ ```
17
+ $ npx @recoder.xyz/rithub init
18
+ Live in 0.9s: agent-lwlvjdtj -> https://rithub.dev/agent-lwlvjdtj/first-repo
19
+ git remote 'origin' set to agent-lwlvjdtj/first-repo. Next: git add -A && git commit -m "first commit" && git push -u origin main
20
+ Unclaimed: a small repo quota applies. Keep this account: rithub claim --email you@example.com
21
+ ```
22
+
23
+ Re-running `rithub init` in the same directory reuses the account from
24
+ `.rithub/agent.json` (gitignored automatically) instead of signing up again.
25
+
26
+ A small repo quota applies until a human claims the account:
27
+
28
+ ```
29
+ npx @recoder.xyz/rithub claim --email you@example.com
30
+ ```
31
+
32
+ This sets the account's real email and lifts the quota. Afterward, open
33
+ <https://rithub.dev/user/forgot_password> with the same email to set a
34
+ real password and sign in as the account in a browser — no separate
35
+ claim-token system, just Rithub's own password-reset mail.
36
+
37
+ ## How it works
38
+
39
+ `init` solves a small proof-of-work challenge (cheap for a machine,
40
+ expensive for mass abuse — no CAPTCHA, since an agent cannot solve one),
41
+ then calls the signup route that [`apps/rithub-mcp`](../../apps/rithub-mcp)
42
+ already exposes at `rithub.dev` next to its MCP endpoint:
43
+
44
+ ```
45
+ GET https://rithub.dev/agent-signup/challenge -> { challenge, bits }
46
+ POST https://rithub.dev/agent-signup { challenge, nonce, repo_name? }
47
+ POST https://rithub.dev/agent-signup/claim (Bearer <token>) { email }
48
+ ```
49
+
50
+ An agent that would rather skip the CLI and call the API directly can do
51
+ exactly that — same two JSON endpoints, no SDK required.
52
+
53
+ ## Flags
54
+
55
+ ```
56
+ rithub init [--repo <name>] [--api-url <url>] [--json]
57
+ rithub claim --email <you@example.com> [--json]
58
+ ```
59
+
60
+ `RITHUB_API_URL` overrides the default `https://rithub.dev` (useful for
61
+ local development against this repo's own test fixtures).
package/bin/rithub.mjs ADDED
@@ -0,0 +1,30 @@
1
+ #!/usr/bin/env node
2
+ import { execFileSync } from "node:child_process";
3
+ import { readFileSync, writeFileSync, existsSync, mkdirSync } from "node:fs";
4
+ import { dirname } from "node:path";
5
+
6
+ import { main } from "../src/cli.mjs";
7
+
8
+ const code = await main(process.argv.slice(2), {
9
+ env: process.env,
10
+ cwd: process.cwd(),
11
+ out: (s) => process.stdout.write(`${s}\n`),
12
+ err: (s) => process.stderr.write(`${s}\n`),
13
+ now: () => Date.now(),
14
+ fetchImpl: fetch,
15
+ exists: (path) => existsSync(path),
16
+ readFile: (path) => (existsSync(path) ? readFileSync(path, "utf8") : null),
17
+ writeFile: (path, contents) => {
18
+ mkdirSync(dirname(path), { recursive: true });
19
+ writeFileSync(path, contents);
20
+ },
21
+ run: (command, args, cwd) => {
22
+ try {
23
+ const output = execFileSync(command, args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
24
+ return { ok: true, output };
25
+ } catch (err) {
26
+ return { ok: false, output: `${err.stdout ?? ""}${err.stderr ?? err.message ?? ""}` };
27
+ }
28
+ },
29
+ });
30
+ process.exit(code);
package/package.json CHANGED
@@ -1,6 +1,15 @@
1
1
  {
2
2
  "name": "@recoder.xyz/rithub",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "npx rithub init: an AI agent gets a real Rithub account, an access token and a first repo with no human, then git push works. One command.",
5
+ "type": "module",
6
+ "license": "Apache-2.0",
7
+ "engines": { "node": ">=20" },
8
+ "bin": { "rithub": "bin/rithub.mjs" },
9
+ "files": ["bin", "src", "README.md"],
10
+ "homepage": "https://rithub.dev",
11
+ "keywords": ["rithub", "git", "agent", "agent-native", "ci", "cli"],
12
+ "scripts": {
13
+ "test": "node --test test/*.test.mjs"
14
+ }
15
+ }
package/src/cli.mjs ADDED
@@ -0,0 +1,60 @@
1
+ import { runInit, runClaim, CliError, DEFAULT_API_URL } from "./init.mjs";
2
+
3
+ const USAGE = `rithub init [--repo <name>] [--api-url <url>] [--json]
4
+ rithub claim --email <you@example.com> [--json]
5
+
6
+ init: no account needed -- provisions a Rithub account, an access
7
+ token and a first repo, and points this directory's git remote
8
+ at it. Re-running it in the same directory reuses the account.
9
+ A small quota applies until a human claims it.
10
+ claim: hands a real human ownership of the account \`init\` created in
11
+ this directory. After claiming, set a password at
12
+ https://rithub.dev/user/forgot_password with the same email.`;
13
+
14
+ function parseArgs(argv) {
15
+ const out = { json: false, email: undefined, repo: undefined, apiUrl: undefined };
16
+ for (let i = 0; i < argv.length; i++) {
17
+ const arg = argv[i];
18
+ if (arg === "--json") out.json = true;
19
+ else if (arg === "--repo") out.repo = argv[++i];
20
+ else if (arg === "--api-url") out.apiUrl = argv[++i];
21
+ else if (arg === "--email") out.email = argv[++i];
22
+ else throw new CliError(`unknown option ${arg}`, { code: "invalid_argument" });
23
+ }
24
+ return out;
25
+ }
26
+
27
+ export async function main(argv, io) {
28
+ const [command, ...rest] = argv;
29
+ try {
30
+ if (command === "init") {
31
+ const args = parseArgs(rest);
32
+ const result = await runInit({ repoName: args.repo, apiUrl: args.apiUrl ?? io.env.RITHUB_API_URL ?? DEFAULT_API_URL, cwd: io.cwd }, io);
33
+ if (args.json) {
34
+ io.out(JSON.stringify(result));
35
+ } else {
36
+ io.out(result.reused ? `Reusing ${result.username}/${result.repo?.split("/")?.[1] ?? "first-repo"} (from ${".rithub/agent.json"}).` : `Live in ${result.solved_in_seconds ?? "?"}s: ${result.username} -> ${result.html_url}`);
37
+ io.out(`git remote 'origin' set to ${result.repo}. Next: git add -A && git commit -m "first commit" && git push -u origin ${result.branch ?? "main"}`);
38
+ if (!result.reused) {
39
+ io.out(`Unclaimed: a small repo quota applies. Keep this account: rithub claim --email you@example.com`);
40
+ }
41
+ }
42
+ return 0;
43
+ }
44
+ if (command === "claim") {
45
+ const args = parseArgs(rest);
46
+ const result = await runClaim({ email: args.email, cwd: io.cwd }, io);
47
+ io.out(args.json ? JSON.stringify(result) : `Claimed ${result.username} as ${result.email}. ${result.next}`);
48
+ return 0;
49
+ }
50
+ io.err(USAGE);
51
+ return command ? 1 : 0;
52
+ } catch (err) {
53
+ if (err instanceof CliError) {
54
+ io.err(`rithub ${command ?? ""}: ${err.message}`);
55
+ return 1;
56
+ }
57
+ io.err(`rithub: unexpected error: ${err.message}`);
58
+ return 1;
59
+ }
60
+ }
package/src/init.mjs ADDED
@@ -0,0 +1,139 @@
1
+ // `npx rithub init` -- an AI agent (or a person) gets a real Rithub
2
+ // account, a scoped access token and a first repo with no human in the
3
+ // loop: one POST to the agent-signup route rithub-mcp exposes next to
4
+ // /mcp (apps/rithub-mcp/src/agentSignup.mjs). Mirrors the shape of
5
+ // `npx scribase init --temp` (edge-repos/scribase-cli/src/cli/init.ts):
6
+ // no sign-in, a small quota, a later claim step for a human to take over.
7
+ import { solveChallenge } from "./pow.mjs";
8
+
9
+ export const DEFAULT_API_URL = "https://rithub.dev";
10
+ const STATE_DIR = ".rithub";
11
+ const STATE_FILE = `${STATE_DIR}/agent.json`;
12
+
13
+ export class CliError extends Error {
14
+ constructor(message, { code = "error" } = {}) {
15
+ super(message);
16
+ this.code = code;
17
+ }
18
+ }
19
+
20
+ function join(root, relative) {
21
+ return `${root.replace(/\/+$/, "")}/${relative}`;
22
+ }
23
+
24
+ async function callJson(io, baseUrl, path, init) {
25
+ const res = await io.fetchImpl(`${baseUrl}${path}`, {
26
+ ...init,
27
+ headers: { accept: "application/json", "user-agent": "rithub-cli", ...(init?.body ? { "content-type": "application/json" } : {}), ...(init?.headers ?? {}) },
28
+ });
29
+ const text = await res.text();
30
+ let body = null;
31
+ try {
32
+ body = text ? JSON.parse(text) : null;
33
+ } catch {
34
+ body = { error: text.slice(0, 200) };
35
+ }
36
+ return { status: res.status, body };
37
+ }
38
+
39
+ function readState(io, cwd) {
40
+ const text = io.readFile(join(cwd, STATE_FILE));
41
+ if (!text) return null;
42
+ try {
43
+ const value = JSON.parse(text);
44
+ return value?.username && value?.token && value?.git_remote ? value : null;
45
+ } catch {
46
+ return null;
47
+ }
48
+ }
49
+
50
+ function ensureGitignored(io, cwd) {
51
+ const path = join(cwd, ".gitignore");
52
+ const current = io.readFile(path) ?? "";
53
+ if (current.split("\n").some((line) => line.trim() === STATE_DIR || line.trim() === `${STATE_DIR}/`)) return;
54
+ const next = current.length > 0 && !current.endsWith("\n") ? `${current}\n${STATE_DIR}/\n` : `${current}${STATE_DIR}/\n`;
55
+ io.writeFile(path, next);
56
+ }
57
+
58
+ function setGitRemote(io, cwd, gitRemote) {
59
+ const inGitRepo = io.run("git", ["rev-parse", "--is-inside-work-tree"], cwd).ok;
60
+ if (!inGitRepo) {
61
+ const init = io.run("git", ["init"], cwd);
62
+ if (!init.ok) throw new CliError(`git init failed: ${init.output.slice(-400)}`, { code: "git_failed" });
63
+ // Normalize a freshly-created repo to `main` regardless of this machine's
64
+ // `git init.defaultBranch` (plenty of installs still default to `master`,
65
+ // which breaks the push instruction we print below). Safe pre-first-commit:
66
+ // rewrites the symbolic ref, not an existing branch object.
67
+ io.run("git", ["symbolic-ref", "HEAD", "refs/heads/main"], cwd);
68
+ }
69
+ const remotes = io.run("git", ["remote"], cwd);
70
+ const hasOrigin = remotes.ok && remotes.output.split("\n").map((l) => l.trim()).includes("origin");
71
+ const result = hasOrigin ? io.run("git", ["remote", "set-url", "origin", gitRemote], cwd) : io.run("git", ["remote", "add", "origin", gitRemote], cwd);
72
+ if (!result.ok) throw new CliError(`could not set the git remote: ${result.output.slice(-400)}`, { code: "git_failed" });
73
+ }
74
+
75
+ /** The real current branch name, so printed instructions never claim `main`
76
+ * when this directory's git (pre-existing or just-initialized on an old git
77
+ * that ignored symbolic-ref) is actually on something else. Falls back to
78
+ * `main` only if git itself can't answer (e.g. no git on PATH). */
79
+ function currentBranch(io, cwd) {
80
+ const result = io.run("git", ["branch", "--show-current"], cwd);
81
+ const name = result.ok ? result.output.trim() : "";
82
+ return name || "main";
83
+ }
84
+
85
+ /** `rithub init`: provisions (or reuses) an agent account and points this directory's git remote at its first repo. */
86
+ export async function runInit(options, io) {
87
+ const cwd = options.cwd ?? io.cwd;
88
+ const baseUrl = (options.apiUrl ?? io.env.RITHUB_API_URL ?? DEFAULT_API_URL).replace(/\/+$/, "");
89
+ const existing = readState(io, cwd);
90
+
91
+ if (existing) {
92
+ setGitRemote(io, cwd, existing.git_remote);
93
+ return { ...existing, reused: true, branch: currentBranch(io, cwd) };
94
+ }
95
+
96
+ const challengeCall = await callJson(io, baseUrl, "/agent-signup/challenge", { method: "GET" });
97
+ if (challengeCall.status !== 200) {
98
+ throw new CliError(`could not reach ${baseUrl}/agent-signup/challenge (HTTP ${challengeCall.status}): ${challengeCall.body?.error ?? "unknown error"}`, { code: "network_error" });
99
+ }
100
+ const { challenge, bits } = challengeCall.body;
101
+ const startedAt = (io.now ?? Date.now)();
102
+ const nonce = solveChallenge(challenge, bits);
103
+
104
+ const signupCall = await callJson(io, baseUrl, "/agent-signup", {
105
+ method: "POST",
106
+ body: JSON.stringify({ challenge, nonce, repo_name: options.repoName ?? (cwd.split("/").pop() || "first-repo") }),
107
+ });
108
+ if (signupCall.status !== 201) {
109
+ throw new CliError(`signup failed (HTTP ${signupCall.status}): ${signupCall.body?.error ?? "unknown error"}`, { code: "signup_failed" });
110
+ }
111
+ const account = signupCall.body;
112
+ const liveInSeconds = Math.max(0, Math.round(((io.now ?? Date.now)() - startedAt) / 100) / 10);
113
+
114
+ io.writeFile(join(cwd, STATE_FILE), `${JSON.stringify({ ...account, api_url: baseUrl }, null, 2)}\n`);
115
+ ensureGitignored(io, cwd);
116
+ setGitRemote(io, cwd, account.git_remote);
117
+
118
+ return { ...account, api_url: baseUrl, reused: false, solved_in_seconds: liveInSeconds, branch: currentBranch(io, cwd) };
119
+ }
120
+
121
+ /** `rithub claim --email you@example.com`: hands a human account ownership of this directory's agent account (see agentSignup.mjs's claimAgent). */
122
+ export async function runClaim(options, io) {
123
+ const cwd = options.cwd ?? io.cwd;
124
+ const existing = readState(io, cwd);
125
+ if (!existing) {
126
+ throw new CliError("no .rithub/agent.json here -- run `rithub init` first, or run this from the directory it was run in.", { code: "no_state" });
127
+ }
128
+ if (!options.email) throw new CliError("`rithub claim` needs --email <you@example.com>", { code: "invalid_argument" });
129
+ const baseUrl = existing.api_url ?? DEFAULT_API_URL;
130
+ const call = await callJson(io, baseUrl, "/agent-signup/claim", {
131
+ method: "POST",
132
+ headers: { authorization: `Bearer ${existing.token}` },
133
+ body: JSON.stringify({ email: options.email }),
134
+ });
135
+ if (call.status !== 200) {
136
+ throw new CliError(`claim failed (HTTP ${call.status}): ${call.body?.error ?? "unknown error"}`, { code: "claim_failed" });
137
+ }
138
+ return call.body;
139
+ }
package/src/pow.mjs ADDED
@@ -0,0 +1,34 @@
1
+ // Proof-of-work solver for `rithub init`'s signup challenge. Mirrors the
2
+ // server side (apps/rithub-mcp/src/agentSignup.mjs: sha256(challenge +
3
+ // ":" + nonce) needs `bits` leading zero bits) -- kept as two small,
4
+ // independently readable implementations rather than a shared package,
5
+ // the same choice edge-repos/scribase-cli/src/cli/pow.ts made for its own
6
+ // client/server split.
7
+ import { createHash } from "node:crypto";
8
+
9
+ function leadingZeroBits(buf) {
10
+ let bits = 0;
11
+ for (const byte of buf) {
12
+ if (byte === 0) {
13
+ bits += 8;
14
+ continue;
15
+ }
16
+ let b = byte;
17
+ while ((b & 0x80) === 0) {
18
+ bits += 1;
19
+ b <<= 1;
20
+ }
21
+ break;
22
+ }
23
+ return bits;
24
+ }
25
+
26
+ /** Finds a nonce for `challenge` at `bits` difficulty. 18 bits is ~2^18 hashes, well under a second on any modern CPU; this throws rather than spin forever if something is misconfigured (e.g. bits absurdly high). */
27
+ export function solveChallenge(challenge, bits, { maxAttempts = 20_000_000 } = {}) {
28
+ for (let i = 0; i < maxAttempts; i++) {
29
+ const nonce = i.toString(36);
30
+ const hash = createHash("sha256").update(`${challenge}:${nonce}`).digest();
31
+ if (leadingZeroBits(hash) >= bits) return nonce;
32
+ }
33
+ throw new Error(`could not solve the ${bits}-bit proof-of-work challenge within ${maxAttempts} attempts`);
34
+ }