@phren/cli 0.3.36 → 0.3.39

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.
Files changed (103) hide show
  1. package/dist/bridge/account-choice.d.ts +82 -0
  2. package/dist/bridge/account-choice.js +173 -0
  3. package/dist/bridge/account-failover.d.ts +61 -0
  4. package/dist/bridge/account-failover.js +189 -0
  5. package/dist/bridge/account-usage.d.ts +7 -2
  6. package/dist/bridge/account-usage.js +53 -8
  7. package/dist/bridge/agent-hooks.js +2 -0
  8. package/dist/bridge/changes.d.ts +5 -0
  9. package/dist/bridge/changes.js +4 -0
  10. package/dist/bridge/claude-accounts.d.ts +15 -4
  11. package/dist/bridge/claude-accounts.js +31 -16
  12. package/dist/bridge/claude-credits.d.ts +43 -0
  13. package/dist/bridge/claude-credits.js +236 -0
  14. package/dist/bridge/claude-question-dialog.js +6 -2
  15. package/dist/bridge/command.js +64 -3
  16. package/dist/bridge/device-enroll.d.ts +34 -0
  17. package/dist/bridge/device-enroll.js +57 -0
  18. package/dist/bridge/dispatch-command.d.ts +2 -0
  19. package/dist/bridge/dispatch-command.js +25 -1
  20. package/dist/bridge/dispatch-returns.d.ts +19 -0
  21. package/dist/bridge/dispatch-returns.js +93 -12
  22. package/dist/bridge/dispatch.d.ts +83 -3
  23. package/dist/bridge/dispatch.js +82 -10
  24. package/dist/bridge/file-range.d.ts +3 -0
  25. package/dist/bridge/file-range.js +5 -4
  26. package/dist/bridge/file-search.d.ts +37 -0
  27. package/dist/bridge/file-search.js +87 -0
  28. package/dist/bridge/file-write.d.ts +6 -0
  29. package/dist/bridge/file-write.js +120 -0
  30. package/dist/bridge/git-host-auth.d.ts +31 -0
  31. package/dist/bridge/git-host-auth.js +110 -0
  32. package/dist/bridge/git-host-gitboy.d.ts +46 -0
  33. package/dist/bridge/git-host-gitboy.js +296 -0
  34. package/dist/bridge/git-host-gitlab.d.ts +25 -0
  35. package/dist/bridge/git-host-gitlab.js +229 -0
  36. package/dist/bridge/git-host-http.d.ts +33 -0
  37. package/dist/bridge/git-host-http.js +70 -0
  38. package/dist/bridge/git-hosts.d.ts +92 -0
  39. package/dist/bridge/git-hosts.js +244 -0
  40. package/dist/bridge/git-publish.d.ts +15 -5
  41. package/dist/bridge/git-publish.js +69 -21
  42. package/dist/bridge/git-review.d.ts +23 -0
  43. package/dist/bridge/git-review.js +170 -0
  44. package/dist/bridge/git-sync.d.ts +14 -0
  45. package/dist/bridge/git-sync.js +143 -0
  46. package/dist/bridge/git.d.ts +20 -7
  47. package/dist/bridge/git.js +87 -68
  48. package/dist/bridge/gitboy-contract.d.ts +32 -0
  49. package/dist/bridge/gitboy-contract.js +46 -0
  50. package/dist/bridge/hand-off.d.ts +75 -3
  51. package/dist/bridge/hand-off.js +113 -27
  52. package/dist/bridge/health.d.ts +1 -1
  53. package/dist/bridge/health.js +5 -3
  54. package/dist/bridge/install.d.ts +14 -0
  55. package/dist/bridge/install.js +40 -1
  56. package/dist/bridge/launch-brief.d.ts +3 -0
  57. package/dist/bridge/launch-brief.js +16 -0
  58. package/dist/bridge/memory-store.d.ts +8 -0
  59. package/dist/bridge/memory-store.js +80 -2
  60. package/dist/bridge/pair.d.ts +6 -1
  61. package/dist/bridge/pair.js +74 -2
  62. package/dist/bridge/peers.js +4 -2
  63. package/dist/bridge/project-memory.d.ts +94 -0
  64. package/dist/bridge/project-memory.js +235 -0
  65. package/dist/bridge/push.d.ts +15 -0
  66. package/dist/bridge/push.js +39 -0
  67. package/dist/bridge/schedule-launch.js +5 -1
  68. package/dist/bridge/schedule-watch.d.ts +3 -0
  69. package/dist/bridge/schedule-watch.js +27 -1
  70. package/dist/bridge/scoped-gateway.d.ts +29 -0
  71. package/dist/bridge/scoped-gateway.js +239 -0
  72. package/dist/bridge/server-launch.d.ts +12 -0
  73. package/dist/bridge/server-launch.js +23 -12
  74. package/dist/bridge/server-pane-routes.js +54 -3
  75. package/dist/bridge/server-routes.d.ts +12 -0
  76. package/dist/bridge/server-routes.js +64 -5
  77. package/dist/bridge/server.js +50 -5
  78. package/dist/bridge/session-move.d.ts +288 -0
  79. package/dist/bridge/session-move.js +600 -0
  80. package/dist/bridge/subscription.d.ts +15 -0
  81. package/dist/bridge/subscription.js +23 -0
  82. package/dist/bridge/transport.js +21 -1
  83. package/dist/bridge/usage.d.ts +23 -4
  84. package/dist/bridge/usage.js +63 -11
  85. package/dist/bridge-hook.mjs +23280 -13252
  86. package/dist/cli/config.js +28 -2
  87. package/dist/cli-registry.js +10 -4
  88. package/dist/computers/command.js +3 -1
  89. package/dist/computers/read.d.ts +3 -0
  90. package/dist/computers/read.js +6 -0
  91. package/dist/content/summarize.d.ts +21 -0
  92. package/dist/content/summarize.js +56 -18
  93. package/dist/init/preferences.d.ts +6 -0
  94. package/dist/modules/registry.js +13 -13
  95. package/dist/project-config.d.ts +12 -0
  96. package/dist/project-config.js +29 -0
  97. package/dist/shared/retrieval.d.ts +1 -0
  98. package/dist/shared/retrieval.js +1 -1
  99. package/dist/sync/conflict-resolve.js +5 -6
  100. package/dist/tools/dispatch.js +20 -3
  101. package/dist/tools/finding.d.ts +25 -0
  102. package/dist/tools/finding.js +2 -1
  103. package/package.json +57 -1
@@ -0,0 +1,110 @@
1
+ import { execFile } from "node:child_process";
2
+ import { mkdir, readFile, stat } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { promisify } from "node:util";
5
+ import { atomic, bridgeRoot } from "./protocol.js";
6
+ const exec = promisify(execFile);
7
+ export function gitHostsFile() {
8
+ return path.join(bridgeRoot(), "git-hosts.json");
9
+ }
10
+ function clean(value) {
11
+ return typeof value === "string" && value.trim() ? value.trim() : undefined;
12
+ }
13
+ function normalDomain(domain) {
14
+ return domain.trim().toLowerCase().replace(/\.$/, "");
15
+ }
16
+ /** The stored tokens. A file other users can read is ignored, as apns.json is. */
17
+ async function readStore(file = gitHostsFile()) {
18
+ let info;
19
+ try {
20
+ info = await stat(file);
21
+ }
22
+ catch {
23
+ return null;
24
+ }
25
+ if (!info.isFile())
26
+ return null;
27
+ if (process.platform !== "win32" && ((info.mode & 0o077) !== 0 || (process.getuid && info.uid !== process.getuid())))
28
+ return "unsafe";
29
+ try {
30
+ const parsed = JSON.parse(await readFile(file, "utf8"));
31
+ const hosts = {};
32
+ if (parsed.hosts && typeof parsed.hosts === "object") {
33
+ for (const [domain, raw] of Object.entries(parsed.hosts)) {
34
+ const entry = raw && typeof raw === "object" ? raw : {};
35
+ const token = clean(entry.token);
36
+ const kind = entry.kind === "gitlab" || entry.kind === "gitboy" ? entry.kind : null;
37
+ if (token && kind)
38
+ hosts[normalDomain(domain)] = { kind, token, ...(clean(entry.user) ? { user: clean(entry.user) } : {}), ...(clean(entry.savedAt) ? { savedAt: clean(entry.savedAt) } : {}) };
39
+ }
40
+ }
41
+ return { hosts };
42
+ }
43
+ catch {
44
+ return null;
45
+ }
46
+ }
47
+ /** Store (or, with an empty token, forget) one domain's token. */
48
+ export async function writeHostToken(domain, kind, token, user, file = gitHostsFile()) {
49
+ const key = normalDomain(domain);
50
+ if (!key || /[\s/]/.test(key))
51
+ throw new Error("That is not a host name.");
52
+ const current = await readStore(file);
53
+ const hosts = current && current !== "unsafe" ? { ...current.hosts } : {};
54
+ const value = clean(token);
55
+ if (value)
56
+ hosts[key] = { kind, token: value, ...(user ? { user } : {}), savedAt: new Date().toISOString() };
57
+ else
58
+ delete hosts[key];
59
+ await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
60
+ await atomic(file, JSON.stringify({ hosts }, null, 2) + "\n", 0o600);
61
+ }
62
+ /** The environment variables each host's own tools read. GITLAB_TOKEN is
63
+ * glab's; it applies to gitlab.com, or to the domain GITLAB_HOST names.
64
+ * GITBOY_TOKEN applies only to the domain GITBOY_HOST names. */
65
+ function fromEnv(kind, domain, env) {
66
+ if (kind === "gitlab") {
67
+ const named = clean(env.GITLAB_HOST)?.replace(/^https?:\/\//, "").replace(/\/.*$/, "").toLowerCase();
68
+ if (domain === "gitlab.com" ? !named || named === "gitlab.com" : named === domain)
69
+ return clean(env.GITLAB_TOKEN) ?? clean(env.GL_TOKEN);
70
+ return undefined;
71
+ }
72
+ // gitboy runs on any domain, so its token goes only to the one GITBOY_HOST names.
73
+ const named = clean(env.GITBOY_HOST)?.replace(/^https?:\/\//, "").replace(/\/.*$/, "").toLowerCase();
74
+ return named && named === domain ? clean(env.GITBOY_TOKEN) : undefined;
75
+ }
76
+ /** glab's stored token for a domain, when glab is installed and signed in. */
77
+ async function fromCli(kind, domain) {
78
+ if (kind !== "gitlab")
79
+ return undefined;
80
+ try {
81
+ const { stdout } = await exec("glab", ["config", "get", "token", "--host", domain], { timeout: 5_000, env: { ...process.env, NO_COLOR: "1", GLAB_NO_PROMPT: "1" } });
82
+ return clean(stdout);
83
+ }
84
+ catch {
85
+ return undefined;
86
+ }
87
+ }
88
+ export async function resolveHostToken(kind, domain, options = {}) {
89
+ const key = normalDomain(domain);
90
+ const env = fromEnv(kind, key, options.env ?? process.env);
91
+ if (env)
92
+ return { token: env, source: "environment" };
93
+ const store = await readStore(options.file);
94
+ const stored = store && store !== "unsafe" ? store.hosts[key] : undefined;
95
+ if (stored && stored.kind === kind)
96
+ return { token: stored.token, source: "file", ...(stored.user ? { user: stored.user } : {}) };
97
+ if (options.cli !== false) {
98
+ const cli = await fromCli(kind, key);
99
+ if (cli)
100
+ return { token: cli, source: "cli" };
101
+ }
102
+ return undefined;
103
+ }
104
+ /** Each stored domain with its kind and who it signs in as. Never a token. */
105
+ export async function listHostTokens(file = gitHostsFile()) {
106
+ const store = await readStore(file);
107
+ if (store === "unsafe")
108
+ return "unsafe";
109
+ return Object.entries(store?.hosts ?? {}).map(([domain, { kind, user, savedAt }]) => ({ domain, kind, ...(user ? { user } : {}), ...(savedAt ? { savedAt } : {}) }));
110
+ }
@@ -0,0 +1,46 @@
1
+ import type { GitHostProvider, HostTerms } from "./git-hosts.js";
2
+ import { HostApiError } from "./git-host-http.js";
3
+ import type { Json } from "./protocol.js";
4
+ /** gitboy, the self-hosted forge, over its REST API (/api/v1). gitboy names a
5
+ * pull request by `index`, and an older gitboy has no draft state, no aggregate review decision
6
+ * and no web links in its answers, so this provider derives them: web pages
7
+ * are `<origin>/<owner>/<repo>/pulls/<n>` and `/pipelines/<iid>?job=<id>`, a
8
+ * review decision counts approvals on the head commit, and a newer gitboy
9
+ * that sends `html_url`, `draft` or `review_decision` is taken at its word.
10
+ * The token is GITBOY_TOKEN (for the domain GITBOY_HOST names) or the Hook's stored one, a gbp_ personal access
11
+ * token with read:user and read:repo (write:repo to open or merge); gitboy's
12
+ * "Phren Hook" token preset grants exactly those. A gitboy with head_branch and
13
+ * sha filters gets them; an older one ignores them and the client filters below
14
+ * still pick the right rows. */
15
+ export declare const PULL_TERMS: HostTerms;
16
+ type Order = "failing" | "pending" | "passing" | "skipped" | "neutral";
17
+ /** A gitboy job or pipeline status as one state word. */
18
+ export declare function gitboyState(status: unknown, allowFailure?: boolean): Order;
19
+ interface Ctx {
20
+ api: string;
21
+ web: string;
22
+ repo: string;
23
+ token: string;
24
+ domain: string;
25
+ account: {
26
+ source: string;
27
+ user?: string;
28
+ };
29
+ }
30
+ /** Whether a pull request's head lives in this repository rather than a fork
31
+ * with a branch of the same name. gitboy names it in `head_repository`
32
+ * (owner_username, name); a row without one is taken as this repository's. */
33
+ export declare function sameRepository(ctx: Pick<Ctx, "repo">, pull: Json): boolean;
34
+ /** gitboy's reasons it will not merge: a 409's `details`, else the message. */
35
+ export declare function refusalReasons(error: HostApiError): string;
36
+ /** GitHub's reviewDecision from gitboy's reviews: each reviewer's latest
37
+ * verdict on the head commit, the author's own left out. */
38
+ export declare function gitboyReviewDecision(pull: Json): string | undefined;
39
+ /** gitboy's mergeability and blockers in GitHub's mergeStateStatus words. */
40
+ export declare function gitboyMergeState(pull: Json): {
41
+ mergeState?: string;
42
+ mergeDetail?: string;
43
+ blockers?: string[];
44
+ };
45
+ export declare const gitboy: GitHostProvider;
46
+ export {};
@@ -0,0 +1,296 @@
1
+ import { resolveHostToken } from "./git-host-auth.js";
2
+ import { fillFromCommits } from "./git-host-gitlab.js";
3
+ import { apiRoot, HostApiError, hostJson, safeLink } from "./git-host-http.js";
4
+ import { git } from "./projects.js";
5
+ /** gitboy, the self-hosted forge, over its REST API (/api/v1). gitboy names a
6
+ * pull request by `index`, and an older gitboy has no draft state, no aggregate review decision
7
+ * and no web links in its answers, so this provider derives them: web pages
8
+ * are `<origin>/<owner>/<repo>/pulls/<n>` and `/pipelines/<iid>?job=<id>`, a
9
+ * review decision counts approvals on the head commit, and a newer gitboy
10
+ * that sends `html_url`, `draft` or `review_decision` is taken at its word.
11
+ * The token is GITBOY_TOKEN (for the domain GITBOY_HOST names) or the Hook's stored one, a gbp_ personal access
12
+ * token with read:user and read:repo (write:repo to open or merge); gitboy's
13
+ * "Phren Hook" token preset grants exactly those. A gitboy with head_branch and
14
+ * sha filters gets them; an older one ignores them and the client filters below
15
+ * still pick the right rows. */
16
+ export const PULL_TERMS = { short: "PR", long: "pull request", ref: "#" };
17
+ const ORDER = { failing: 0, pending: 1, passing: 2, skipped: 3, neutral: 4 };
18
+ /** A gitboy job or pipeline status as one state word. */
19
+ export function gitboyState(status, allowFailure = false) {
20
+ switch (String(status ?? "").toLowerCase()) {
21
+ case "success": return "passing";
22
+ case "failed":
23
+ case "failure":
24
+ case "error": return allowFailure ? "neutral" : "failing";
25
+ case "canceled":
26
+ case "cancelled": return allowFailure ? "neutral" : "failing";
27
+ case "skipped": return "skipped";
28
+ default: return "pending"; // created, blocked, queued, claimed, running, pending
29
+ }
30
+ }
31
+ function obj(value) {
32
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
33
+ }
34
+ function rows(value) {
35
+ const list = Array.isArray(value) ? value : Array.isArray(obj(value).items) ? obj(value).items : [];
36
+ return list.map(obj);
37
+ }
38
+ function stateOf(pull) {
39
+ if (pull.merged_at)
40
+ return "MERGED";
41
+ return String(pull.state ?? "").toLowerCase() === "open" ? "OPEN" : "CLOSED";
42
+ }
43
+ const SIGN_IN = (domain) => `Phren has no gitboy token for ${domain}. Connect it from the desktop's Changes pane, or run phren bridge git-host set ${domain} gitboy on this computer with a personal access token that has read:user and read:repo (write:repo to open and merge); gitboy's Settings → Access tokens has a "Phren Hook" preset.`;
44
+ async function context(root, host) {
45
+ const repo = host.webUrl?.replace(/^https?:\/\/[^/]+\//, "") ?? "";
46
+ if (!host.domain || repo.split("/").length !== 2)
47
+ return { available: false, reason: "unknown-host", message: "This repository has no gitboy remote of the form owner/repo.", pulls: [], current: null };
48
+ const token = await resolveHostToken("gitboy", host.domain);
49
+ if (!token)
50
+ return { available: false, reason: "auth", message: SIGN_IN(host.domain), pulls: [], current: null };
51
+ const api = await apiRoot(root, host.domain, `https://${host.domain}/api/v1`);
52
+ return { api, web: api.replace(/\/api\/v1$/, ""), repo, token: token.token, domain: host.domain, account: { source: token.source, ...(token.user ? { user: token.user } : {}) } };
53
+ }
54
+ function call(ctx, path, init = {}) {
55
+ return hostJson(`${ctx.api}/repos/${ctx.repo}${path}`, { token: ctx.token, scheme: "bearer", ...init });
56
+ }
57
+ /** Whether a pull request's head lives in this repository rather than a fork
58
+ * with a branch of the same name. gitboy names it in `head_repository`
59
+ * (owner_username, name); a row without one is taken as this repository's. */
60
+ export function sameRepository(ctx, pull) {
61
+ const head = obj(pull.head_repository);
62
+ if (typeof head.owner_username !== "string" || typeof head.name !== "string")
63
+ return true;
64
+ return `${head.owner_username}/${head.name}`.toLowerCase() === ctx.repo.toLowerCase();
65
+ }
66
+ /** Whether the branch was pushed: its remote-tracking ref, read locally so an
67
+ * error path never waits on the network or a credential prompt. */
68
+ async function remoteHasBranch(root, remote, branch) {
69
+ return git(root, "show-ref", "--verify", "--quiet", `refs/remotes/${remote}/${branch}`).then(() => true, () => false);
70
+ }
71
+ /** gitboy's reasons it will not merge: a 409's `details`, else the message. */
72
+ export function refusalReasons(error) {
73
+ const body = obj(error.body);
74
+ const details = Array.isArray(body.details) ? body.details.map(item => String(item).slice(0, 300)).filter(Boolean).slice(0, 10) : [];
75
+ const message = error.message.replace(/^.*? answered \d+:? ?/, "");
76
+ if (details.length)
77
+ return `${message && message !== "Pull request cannot be merged" ? `${message}: ` : ""}${details.join("; ")}`;
78
+ return message || "gitboy says it can't be merged yet.";
79
+ }
80
+ function pullUrl(ctx, pull) {
81
+ return safeLink(pull.html_url) ?? `${ctx.web}/${ctx.repo}/pulls/${pull.index ?? pull.number}`;
82
+ }
83
+ function listed(ctx, pull) {
84
+ const number = typeof pull.index === "number" ? pull.index : pull.number;
85
+ return { number, title: String(pull.title ?? ""), head: String(pull.head_branch ?? ""), base: String(pull.base_branch ?? ""),
86
+ author: String(pull.author_username ?? ""), url: pullUrl(ctx, pull), draft: pull.draft === true, state: stateOf(pull),
87
+ updated: String(pull.updated_at ?? "") };
88
+ }
89
+ /** GitHub's reviewDecision from gitboy's reviews: each reviewer's latest
90
+ * verdict on the head commit, the author's own left out. */
91
+ export function gitboyReviewDecision(pull) {
92
+ if (typeof pull.review_decision === "string" && pull.review_decision)
93
+ return pull.review_decision.toUpperCase();
94
+ const head = String(pull.head_sha ?? "");
95
+ const latest = new Map();
96
+ for (const review of rows(pull.reviews).sort((a, b) => String(a.created_at ?? "").localeCompare(String(b.created_at ?? "")))) {
97
+ const who = String(review.reviewer_username ?? review.reviewer_id ?? "");
98
+ if (!who || who === pull.author_username)
99
+ continue;
100
+ const state = String(review.state ?? "");
101
+ if (state === "changes_requested")
102
+ latest.set(who, state);
103
+ else if (state === "approved" && (!head || review.commit_sha === head))
104
+ latest.set(who, state);
105
+ }
106
+ const verdicts = [...latest.values()];
107
+ if (verdicts.includes("changes_requested"))
108
+ return "CHANGES_REQUESTED";
109
+ const blockers = Array.isArray(pull.merge_blockers) ? pull.merge_blockers.map(String) : [];
110
+ if (blockers.some(text => /approval/i.test(text)))
111
+ return "REVIEW_REQUIRED";
112
+ return verdicts.includes("approved") ? "APPROVED" : undefined;
113
+ }
114
+ /** gitboy's mergeability and blockers in GitHub's mergeStateStatus words. */
115
+ export function gitboyMergeState(pull) {
116
+ const blockers = (Array.isArray(pull.merge_blockers) ? pull.merge_blockers : []).map(text => String(text).slice(0, 300)).slice(0, 20);
117
+ const status = String(pull.status ?? "");
118
+ if (stateOf(pull) !== "OPEN")
119
+ return {};
120
+ if (status === "conflict")
121
+ return { mergeState: "DIRTY", mergeDetail: "Has merge conflicts", ...(blockers.length ? { blockers } : {}) };
122
+ if (status === "checking" || status === "")
123
+ return { mergeState: "UNKNOWN", mergeDetail: "Checking mergeability", ...(blockers.length ? { blockers } : {}) };
124
+ if (status === "empty" || status === "ancestor")
125
+ return { mergeState: "UNKNOWN", mergeDetail: "No changes to merge" };
126
+ if (status === "error")
127
+ return { mergeState: "UNKNOWN", mergeDetail: "gitboy could not check mergeability" };
128
+ if (blockers.length)
129
+ return { mergeState: "BLOCKED", mergeDetail: blockers[0], blockers };
130
+ return { mergeState: "CLEAN", mergeDetail: "Ready to merge" };
131
+ }
132
+ /** The head commit's pipeline jobs, newest attempt of each; failing first. */
133
+ async function jobsFor(ctx, pull) {
134
+ const sha = String(pull.head_sha ?? "");
135
+ const branch = String(pull.head_branch ?? "");
136
+ if (!sha || !branch)
137
+ return { runs: [] };
138
+ const { json } = await call(ctx, `/pipelines?branch=${encodeURIComponent(branch)}&sha=${encodeURIComponent(sha)}&limit=20`).catch(() => ({ json: [] }));
139
+ const pipeline = rows(json).filter(p => p.sha === sha).sort((a, b) => Number(b.iid ?? 0) - Number(a.iid ?? 0))[0];
140
+ if (!pipeline || pipeline.iid === undefined)
141
+ return { runs: [] };
142
+ const { json: detail } = await call(ctx, `/pipelines/${pipeline.iid}`).catch(() => ({ json: {} }));
143
+ const newest = new Map();
144
+ for (const job of rows(obj(detail).jobs)) {
145
+ const name = String(job.name ?? "Job");
146
+ const seen = newest.get(name);
147
+ if (!seen || Number(job.attempt ?? 0) >= Number(seen.attempt ?? 0))
148
+ newest.set(name, job);
149
+ }
150
+ const pipelineUrl = `${ctx.web}/${ctx.repo}/pipelines/${pipeline.iid}`;
151
+ const runs = [...newest.values()].map(job => {
152
+ const state = gitboyState(job.status, job.allow_failure === true);
153
+ const seconds = job.started_at && job.finished_at ? Math.max(0, Math.round((Date.parse(String(job.finished_at)) - Date.parse(String(job.started_at))) / 1000)) : undefined;
154
+ return { name: String(job.name ?? "Job").slice(0, 200), state, ...(job.stage ? { workflow: String(job.stage).slice(0, 200) } : {}),
155
+ url: job.id ? `${pipelineUrl}?job=${encodeURIComponent(String(job.id))}` : pipelineUrl,
156
+ ...(seconds !== undefined && Number.isFinite(seconds) ? { seconds } : {}),
157
+ ...(typeof job.failure_reason === "string" && job.failure_reason ? { detail: job.failure_reason.slice(0, 300) } : {}) };
158
+ }).sort((a, b) => ORDER[a.state] - ORDER[b.state]).slice(0, 100);
159
+ return { runs, pipeline: { id: pipeline.iid, state: gitboyState(obj(detail).status ?? pipeline.status), url: pipelineUrl } };
160
+ }
161
+ /** Commit statuses, when there is no pipeline to read jobs from. */
162
+ function statusRuns(pull) {
163
+ return rows(pull.checks).filter(check => check.context !== "gitboy/pipeline").map(check => {
164
+ const url = safeLink(check.target_url);
165
+ return { name: String(check.context ?? "Check").replace(/^gitboy\//, "").slice(0, 200), state: gitboyState(check.state), ...(url ? { url } : {}) };
166
+ }).sort((a, b) => ORDER[a.state] - ORDER[b.state]).slice(0, 100);
167
+ }
168
+ function rollup(runs) {
169
+ if (!runs.length)
170
+ return null;
171
+ const states = runs.map(run => run.state);
172
+ if (states.includes("failing"))
173
+ return "failing";
174
+ return states.includes("pending") ? "pending" : "passing";
175
+ }
176
+ async function currentRequest(ctx, branch) {
177
+ if (!branch)
178
+ return null;
179
+ // gitboy can't filter by head branch: read the newest and pick this branch's.
180
+ const { json } = await call(ctx, `/pulls?state=all&limit=100&head_branch=${encodeURIComponent(branch)}`);
181
+ const mine = rows(json).filter(pull => pull.head_branch === branch && sameRepository(ctx, pull))
182
+ .sort((a, b) => Number(stateOf(b) === "OPEN") - Number(stateOf(a) === "OPEN") || String(b.updated_at ?? "").localeCompare(String(a.updated_at ?? "")))[0];
183
+ const index = mine?.index ?? mine?.number;
184
+ if (index === undefined)
185
+ return null;
186
+ const { json: detail } = await call(ctx, `/pulls/${index}`);
187
+ const pull = obj(detail);
188
+ const { runs: jobs, pipeline } = await jobsFor(ctx, pull);
189
+ const checkRuns = jobs.length ? jobs : statusRuns(pull);
190
+ const reviewDecision = gitboyReviewDecision(pull);
191
+ const approvals = new Set(rows(pull.reviews).filter(review => review.state === "approved" && review.reviewer_username !== pull.author_username
192
+ && (!pull.head_sha || review.commit_sha === pull.head_sha)).map(review => String(review.reviewer_username ?? review.reviewer_id))).size;
193
+ const conflicted = Array.isArray(pull.conflicted_files) ? pull.conflicted_files.length : 0;
194
+ return { ...listed(ctx, pull), checks: rollup(checkRuns), checkRuns,
195
+ ...(reviewDecision ? { reviewDecision } : {}),
196
+ ...gitboyMergeState(pull),
197
+ ...(pipeline ? { pipeline } : {}),
198
+ ...(approvals ? { approvals: { given: approvals } } : {}),
199
+ ...(typeof pull.comment_count === "number" ? { comments: pull.comment_count } : Array.isArray(pull.comments) ? { comments: pull.comments.length } : {}),
200
+ ...(typeof pull.commits_behind === "number" ? { behind: pull.commits_behind } : {}),
201
+ ...(typeof pull.commits_ahead === "number" ? { ahead: pull.commits_ahead } : {}),
202
+ ...(conflicted ? { conflicts: true } : {}),
203
+ ...(typeof pull.head_sha === "string" ? { headSha: pull.head_sha } : {}) };
204
+ }
205
+ function failed(error, domain) {
206
+ if (error instanceof HostApiError)
207
+ return { available: false, reason: error.reason, message: error.reason === "auth" ? `${error.message} ${SIGN_IN(domain)}` : error.message, pulls: [], current: null };
208
+ return { available: false, reason: "failed", message: error instanceof Error ? error.message : String(error), pulls: [], current: null };
209
+ }
210
+ /** Whether this gitboy has draft pull requests: any pull request it lists
211
+ * carries a `draft` key. */
212
+ async function hasDraftState(ctx, listed) {
213
+ const sample = rows(listed).length ? rows(listed) : rows((await call(ctx, "/pulls?state=all&limit=1").catch(() => ({ json: [] }))).json);
214
+ return sample.some(pull => typeof pull.draft === "boolean");
215
+ }
216
+ export const gitboy = {
217
+ kind: "gitboy",
218
+ name: "gitboy",
219
+ terms: PULL_TERMS,
220
+ supported: true,
221
+ async list(root, branch, host) {
222
+ const ctx = await context(root, host);
223
+ if (!("api" in ctx))
224
+ return ctx;
225
+ try {
226
+ const [{ json }, current] = await Promise.all([call(ctx, "/pulls?state=open&limit=50"), currentRequest(ctx, branch)]);
227
+ return { available: true, pulls: rows(json).map(pull => listed(ctx, pull)), current, account: ctx.account };
228
+ }
229
+ catch (error) {
230
+ return failed(error, ctx.domain);
231
+ }
232
+ },
233
+ async open(root, branch, draft, host) {
234
+ const ctx = await context(root, host);
235
+ if (!("api" in ctx))
236
+ return { ok: false, reason: ctx.reason, message: ctx.message };
237
+ try {
238
+ const { json: open } = await call(ctx, `/pulls?state=open&limit=100&head_branch=${encodeURIComponent(branch)}`);
239
+ const existing = rows(open).find(pull => pull.head_branch === branch);
240
+ if (existing)
241
+ return { ok: true, url: pullUrl(ctx, existing), number: existing.index, branch, existing: true };
242
+ const { json: repo } = await call(ctx, "");
243
+ const target = String(obj(repo).default_branch ?? "main");
244
+ const fill = await fillFromCommits(root, `${host.remote ?? "origin"}/${target}`, branch);
245
+ // A gitboy with draft pull requests sends `draft` on every one; an older
246
+ // one has none, and the title says it, as GitLab's convention does.
247
+ const native = draft && await hasDraftState(ctx, open);
248
+ const title = draft && !native && !/^draft:/i.test(fill.title) ? `Draft: ${fill.title}` : fill.title;
249
+ const { json } = await call(ctx, "/pulls", { method: "POST", body: { head_branch: branch, base_branch: target, title, body: fill.body, ...(native ? { draft: true } : {}) } });
250
+ const pull = obj(json);
251
+ return { ok: true, url: pullUrl(ctx, pull), number: (pull.index ?? pull.number), branch, draft };
252
+ }
253
+ catch (error) {
254
+ if (error instanceof HostApiError && error.status === 400 && /no changes|nothing to compare|no mergeable changes|choose different source and target/i.test(error.message))
255
+ return { ok: false, reason: "failed", message: `${branch} has no changes against the default branch.` };
256
+ // gitboy answers 500 (not 404) for a branch it doesn't have yet; ask git.
257
+ if (error instanceof HostApiError && (error.status === 404 || error.status === 500) && !await remoteHasBranch(root, host.remote ?? "origin", branch)) {
258
+ return { ok: false, reason: "not-found", message: `Push ${branch} to gitboy first, then open the pull request.` };
259
+ }
260
+ const result = failed(error, ctx.domain);
261
+ return { ok: false, reason: result.reason ?? "failed", message: result.message ?? "gitboy refused the pull request." };
262
+ }
263
+ },
264
+ async merge(root, request, host) {
265
+ const ctx = await context(root, host);
266
+ if (!("api" in ctx))
267
+ return { ok: false, reason: ctx.reason, message: ctx.message };
268
+ try {
269
+ // gitboy needs both heads for a rebase; the base guard is harmless for the others.
270
+ const { json: detail } = await call(ctx, `/pulls/${request.number}`).catch(() => ({ json: {} }));
271
+ const baseSha = typeof obj(detail).base_sha === "string" ? obj(detail).base_sha : undefined;
272
+ const { json } = await call(ctx, `/pulls/${request.number}/merge`, { method: "POST", body: {
273
+ method: request.method, ...(request.expectedHeadSha ? { expected_head_sha: request.expectedHeadSha } : {}),
274
+ ...(baseSha ? { expected_base_sha: baseSha } : {})
275
+ } });
276
+ const result = obj(json);
277
+ return { ok: true, number: request.number, method: request.method, ...(typeof result.merge_commit_sha === "string" ? { mergeCommit: result.merge_commit_sha } : {}) };
278
+ }
279
+ catch (error) {
280
+ if (error instanceof HostApiError && (error.status === 409 || error.status === 422 || error.status === 400)) {
281
+ return { ok: false, reason: "blocked", message: refusalReasons(error) };
282
+ }
283
+ if (error instanceof HostApiError && error.status === 403)
284
+ return { ok: false, reason: "auth", message: "The gitboy token can read but not merge here; it needs write:repo, and your account needs merge rights on the branch." };
285
+ const result = failed(error, ctx.domain);
286
+ return { ok: false, reason: result.reason ?? "failed", message: result.message ?? "gitboy refused the merge." };
287
+ }
288
+ },
289
+ async whoami(root, host, token) {
290
+ if (!host.domain)
291
+ throw new HostApiError("failed", "This repository has no gitboy remote.");
292
+ const api = await apiRoot(root, host.domain, `https://${host.domain}/api/v1`);
293
+ const { json } = await hostJson(`${api}/user`, { token, scheme: "bearer" });
294
+ return { user: String(obj(json).username ?? "") };
295
+ },
296
+ };
@@ -0,0 +1,25 @@
1
+ import type { GitHostProvider, HostTerms } from "./git-hosts.js";
2
+ /** GitLab, gitlab.com or self-hosted, over its REST API (v4). The token is
3
+ * GITLAB_TOKEN, the Hook's stored one, or glab's own sign-in, so glab itself
4
+ * is optional. Merge requests come back in the same shape as GitHub's pull
5
+ * requests; pipeline jobs are the checks, and the stage reads as the workflow. */
6
+ export declare const MERGE_TERMS: HostTerms;
7
+ type Order = "failing" | "pending" | "passing" | "skipped" | "neutral";
8
+ /** A pipeline or job status as one state word. An allowed failure is neutral:
9
+ * it doesn't block the merge request. */
10
+ export declare function gitlabState(status: unknown, allowFailure?: boolean): Order;
11
+ export declare function gitlabRollup(states: Order[]): "passing" | "failing" | "pending" | null;
12
+ /** What `detailed_merge_status` means, in GitHub's mergeStateStatus words
13
+ * (which the clients already colour) plus GitLab's own sentence. */
14
+ export declare function gitlabMergeState(detail: unknown): {
15
+ mergeState?: string;
16
+ mergeDetail?: string;
17
+ };
18
+ /** gh's --fill: one commit gives the title and body; several give a title from
19
+ * the branch and a body listing them. */
20
+ export declare function fillFromCommits(root: string, baseRef: string, branch: string): Promise<{
21
+ title: string;
22
+ body: string;
23
+ }>;
24
+ export declare const gitlab: GitHostProvider;
25
+ export {};