@phren/cli 0.3.37 → 0.3.40
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/dist/bridge/account-failover.d.ts +4 -0
- package/dist/bridge/account-failover.js +12 -4
- package/dist/bridge/account-usage.d.ts +5 -2
- package/dist/bridge/account-usage.js +36 -6
- package/dist/bridge/agent-hooks.js +2 -0
- package/dist/bridge/changes.d.ts +5 -0
- package/dist/bridge/changes.js +4 -0
- package/dist/bridge/claude-accounts.d.ts +15 -4
- package/dist/bridge/claude-accounts.js +31 -16
- package/dist/bridge/claude-credits.d.ts +43 -0
- package/dist/bridge/claude-credits.js +236 -0
- package/dist/bridge/claude-question-dialog.js +6 -2
- package/dist/bridge/command.js +64 -3
- package/dist/bridge/conductor-sets.d.ts +5 -0
- package/dist/bridge/conductor-sets.js +23 -3
- package/dist/bridge/device-enroll.d.ts +34 -0
- package/dist/bridge/device-enroll.js +57 -0
- package/dist/bridge/dispatch-command.d.ts +2 -0
- package/dist/bridge/dispatch-command.js +25 -1
- package/dist/bridge/dispatch-returns.d.ts +7 -0
- package/dist/bridge/dispatch-returns.js +56 -6
- package/dist/bridge/dispatch.d.ts +52 -0
- package/dist/bridge/dispatch.js +14 -0
- package/dist/bridge/enroll.js +22 -4
- package/dist/bridge/file-range.d.ts +3 -0
- package/dist/bridge/file-range.js +5 -4
- package/dist/bridge/file-search.d.ts +37 -0
- package/dist/bridge/file-search.js +87 -0
- package/dist/bridge/file-write.d.ts +6 -0
- package/dist/bridge/file-write.js +120 -0
- package/dist/bridge/git-host-auth.d.ts +31 -0
- package/dist/bridge/git-host-auth.js +110 -0
- package/dist/bridge/git-host-gitboy.d.ts +46 -0
- package/dist/bridge/git-host-gitboy.js +296 -0
- package/dist/bridge/git-host-gitlab.d.ts +25 -0
- package/dist/bridge/git-host-gitlab.js +229 -0
- package/dist/bridge/git-host-http.d.ts +33 -0
- package/dist/bridge/git-host-http.js +70 -0
- package/dist/bridge/git-hosts.d.ts +92 -0
- package/dist/bridge/git-hosts.js +244 -0
- package/dist/bridge/git-publish.d.ts +15 -5
- package/dist/bridge/git-publish.js +69 -21
- package/dist/bridge/git-review.d.ts +23 -0
- package/dist/bridge/git-review.js +170 -0
- package/dist/bridge/git-sync.d.ts +14 -0
- package/dist/bridge/git-sync.js +143 -0
- package/dist/bridge/git.d.ts +20 -7
- package/dist/bridge/git.js +87 -68
- package/dist/bridge/gitboy-contract.d.ts +32 -0
- package/dist/bridge/gitboy-contract.js +46 -0
- package/dist/bridge/hand-off.d.ts +52 -2
- package/dist/bridge/hand-off.js +77 -24
- package/dist/bridge/health.d.ts +1 -1
- package/dist/bridge/health.js +5 -3
- package/dist/bridge/install.d.ts +14 -0
- package/dist/bridge/install.js +40 -1
- package/dist/bridge/memory-store.d.ts +8 -0
- package/dist/bridge/memory-store.js +80 -2
- package/dist/bridge/pair.d.ts +6 -1
- package/dist/bridge/pair.js +74 -2
- package/dist/bridge/project-memory.d.ts +94 -0
- package/dist/bridge/project-memory.js +235 -0
- package/dist/bridge/push.d.ts +15 -0
- package/dist/bridge/push.js +39 -0
- package/dist/bridge/scoped-gateway.d.ts +29 -0
- package/dist/bridge/scoped-gateway.js +239 -0
- package/dist/bridge/server-launch.d.ts +12 -0
- package/dist/bridge/server-launch.js +17 -10
- package/dist/bridge/server-pane-routes.js +54 -3
- package/dist/bridge/server-routes.d.ts +13 -0
- package/dist/bridge/server-routes.js +63 -5
- package/dist/bridge/server.js +44 -5
- package/dist/bridge/session-move.d.ts +288 -0
- package/dist/bridge/session-move.js +600 -0
- package/dist/bridge/subscription.d.ts +15 -0
- package/dist/bridge/subscription.js +23 -0
- package/dist/bridge/transport.js +21 -1
- package/dist/bridge/usage.d.ts +20 -3
- package/dist/bridge/usage.js +61 -11
- package/dist/bridge-hook.mjs +12822 -3248
- package/dist/cli-registry.js +10 -4
- package/dist/computers/command.js +3 -1
- package/dist/computers/read.d.ts +3 -0
- package/dist/computers/read.js +6 -0
- package/dist/content/summarize.d.ts +21 -0
- package/dist/content/summarize.js +56 -18
- package/dist/modules/registry.js +14 -14
- package/dist/project-config.d.ts +12 -0
- package/dist/project-config.js +29 -0
- package/dist/shared/retrieval.d.ts +1 -0
- package/dist/shared/retrieval.js +1 -1
- package/dist/sync/conflict-resolve.js +5 -6
- package/dist/tools/dispatch.js +18 -1
- package/dist/tools/finding.d.ts +25 -0
- package/dist/tools/finding.js +2 -1
- package/package.json +57 -1
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { git } from "./projects.js";
|
|
2
|
+
export class HostApiError extends Error {
|
|
3
|
+
reason;
|
|
4
|
+
status;
|
|
5
|
+
body;
|
|
6
|
+
/** `body` is the host's own JSON for a refusal (gitboy's `details`, say). */
|
|
7
|
+
constructor(reason, message, status = 0, body = null) {
|
|
8
|
+
super(message);
|
|
9
|
+
this.reason = reason;
|
|
10
|
+
this.status = status;
|
|
11
|
+
this.body = body;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
/** The API root for a domain: `git config --global phren.<domain>.api` when
|
|
15
|
+
* set (a self-hosted server on another port or path), else the host's
|
|
16
|
+
* default. Only the user's global config counts: a repository's own config is
|
|
17
|
+
* writable by whatever runs in the checkout, and must never be able to send
|
|
18
|
+
* a stored token to another server. */
|
|
19
|
+
export async function apiRoot(root, domain, fallback) {
|
|
20
|
+
const configured = (await git(root, "config", "--global", "--get", `phren.${domain}.api`).catch(() => "")).trim();
|
|
21
|
+
return (configured || fallback).replace(/\/+$/, "");
|
|
22
|
+
}
|
|
23
|
+
export async function hostJson(url, request) {
|
|
24
|
+
const headers = { accept: "application/json", "user-agent": "phren-hook" };
|
|
25
|
+
if (request.token) {
|
|
26
|
+
if (request.scheme === "private-token")
|
|
27
|
+
headers["PRIVATE-TOKEN"] = request.token;
|
|
28
|
+
else
|
|
29
|
+
headers.authorization = `Bearer ${request.token}`;
|
|
30
|
+
}
|
|
31
|
+
if (request.body !== undefined)
|
|
32
|
+
headers["content-type"] = "application/json";
|
|
33
|
+
let response;
|
|
34
|
+
try {
|
|
35
|
+
response = await fetch(url, {
|
|
36
|
+
method: request.method ?? "GET", headers, redirect: "manual",
|
|
37
|
+
body: request.body === undefined ? undefined : JSON.stringify(request.body),
|
|
38
|
+
signal: AbortSignal.timeout(request.timeoutMs ?? 15_000),
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
catch (error) {
|
|
42
|
+
const timedOut = error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError");
|
|
43
|
+
throw new HostApiError("unreachable", timedOut ? `${new URL(url).host} did not answer within ${Math.round((request.timeoutMs ?? 15_000) / 1000)} seconds.` : `Could not reach ${new URL(url).host}.`);
|
|
44
|
+
}
|
|
45
|
+
if (response.status >= 300 && response.status < 400)
|
|
46
|
+
throw new HostApiError("failed", `${new URL(url).host} redirected the API call; set its API address with git config phren.<domain>.api <url>.`, response.status);
|
|
47
|
+
const text = await response.text();
|
|
48
|
+
let json = null;
|
|
49
|
+
try {
|
|
50
|
+
json = text ? JSON.parse(text) : null;
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
json = null;
|
|
54
|
+
}
|
|
55
|
+
if (response.status === 401)
|
|
56
|
+
throw new HostApiError("auth", "The host refused the token: it is missing, expired or revoked.", 401);
|
|
57
|
+
if (response.status === 403)
|
|
58
|
+
throw new HostApiError("auth", "The token cannot read this repository; it needs read access to its code, requests and pipelines.", 403);
|
|
59
|
+
if (response.status === 404)
|
|
60
|
+
throw new HostApiError("not-found", "The host has no such repository, or the token cannot see it.", 404);
|
|
61
|
+
if (response.status >= 400) {
|
|
62
|
+
const message = json && typeof json === "object" ? json.message ?? json.error : undefined;
|
|
63
|
+
throw new HostApiError("failed", `${new URL(url).host} answered ${response.status}${message ? `: ${typeof message === "string" ? message : JSON.stringify(message)}` : ""}`.slice(0, 500), response.status, json);
|
|
64
|
+
}
|
|
65
|
+
return { status: response.status, json: json, headers: response.headers };
|
|
66
|
+
}
|
|
67
|
+
/** An https link, or nothing: hosts' links are shown and opened as-is. */
|
|
68
|
+
export function safeLink(value) {
|
|
69
|
+
return typeof value === "string" && /^https?:\/\//.test(value) ? value.slice(0, 2048) : undefined;
|
|
70
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import type { Json } from "./protocol.js";
|
|
2
|
+
/** Where a repository's pull or merge requests live. Phren supports three git
|
|
3
|
+
* hosts: GitHub, GitLab and gitboy (self-hosted, any domain). The host is read
|
|
4
|
+
* from the remote's URL; a self-hosted GitLab or gitboy is named by an
|
|
5
|
+
* override, per remote or per domain, in git config:
|
|
6
|
+
*
|
|
7
|
+
* git config remote.origin.phrenHost gitlab # this repository's origin
|
|
8
|
+
* git config --global phren.git.example.com.host gitboy # every repo on that domain
|
|
9
|
+
*
|
|
10
|
+
* Each host is a provider with one small interface: list the requests and
|
|
11
|
+
* the checked-out branch's own with its checks, and open one. */
|
|
12
|
+
export type HostKind = "github" | "gitlab" | "gitboy";
|
|
13
|
+
export declare const HOST_KINDS: readonly HostKind[];
|
|
14
|
+
export interface HostTerms {
|
|
15
|
+
short: string;
|
|
16
|
+
long: string;
|
|
17
|
+
ref: string;
|
|
18
|
+
}
|
|
19
|
+
export interface GitHost {
|
|
20
|
+
kind: HostKind | null;
|
|
21
|
+
/** The product name a link reads ("View on GitLab"), or "the git host". */
|
|
22
|
+
name: string;
|
|
23
|
+
/** The remote's domain and the repository's web address, when known. */
|
|
24
|
+
domain: string | null;
|
|
25
|
+
webUrl: string | null;
|
|
26
|
+
remote: string | null;
|
|
27
|
+
/** How the kind was found: from the URL, from an override, or not at all. */
|
|
28
|
+
source: "url" | "remote-override" | "domain-override" | "none";
|
|
29
|
+
terms: HostTerms;
|
|
30
|
+
/** False for a provider that is not built yet (GitLab, gitboy). */
|
|
31
|
+
supported: boolean;
|
|
32
|
+
}
|
|
33
|
+
export interface RequestList {
|
|
34
|
+
available: boolean;
|
|
35
|
+
reason?: string;
|
|
36
|
+
message?: string;
|
|
37
|
+
pulls: Json[];
|
|
38
|
+
current: Json | null;
|
|
39
|
+
/** Where the token came from and who it signs in as, when the host says. */
|
|
40
|
+
account?: {
|
|
41
|
+
source: string;
|
|
42
|
+
user?: string;
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
export interface GitHostProvider {
|
|
46
|
+
readonly kind: HostKind;
|
|
47
|
+
readonly name: string;
|
|
48
|
+
readonly terms: HostTerms;
|
|
49
|
+
readonly supported: boolean;
|
|
50
|
+
/** Open requests and the checked-out branch's own (any state) with its checks. */
|
|
51
|
+
list(root: string, branch: string, host: GitHost): Promise<RequestList>;
|
|
52
|
+
/** Open a request from `branch` into the default branch, titled from its commits. */
|
|
53
|
+
open(root: string, branch: string, draft: boolean, host: GitHost): Promise<Json>;
|
|
54
|
+
/** Merge request `number`, only while its head is still `expectedHeadSha`
|
|
55
|
+
* when one is given. The host's own refusal (checks, approvals, conflicts)
|
|
56
|
+
* comes back as `{ ok: false, reason: "blocked", message }`. */
|
|
57
|
+
merge(root: string, request: MergeRequest, host: GitHost): Promise<Json>;
|
|
58
|
+
/** Who a token signs in as, for Connect; HTTP hosts only. */
|
|
59
|
+
whoami?(root: string, host: GitHost, token: string): Promise<{
|
|
60
|
+
user: string;
|
|
61
|
+
}>;
|
|
62
|
+
}
|
|
63
|
+
export type MergeMethod = "merge" | "squash" | "rebase";
|
|
64
|
+
export interface MergeRequest {
|
|
65
|
+
number: number;
|
|
66
|
+
method: MergeMethod;
|
|
67
|
+
expectedHeadSha?: string;
|
|
68
|
+
deleteBranch?: boolean;
|
|
69
|
+
}
|
|
70
|
+
/** `git@host:owner/repo.git`, `ssh://git@host:2222/owner/repo.git`,
|
|
71
|
+
* `https://user@host/owner/repo` → the domain and the repository path. */
|
|
72
|
+
export declare function parseRemoteUrl(url: string): {
|
|
73
|
+
domain: string;
|
|
74
|
+
path: string;
|
|
75
|
+
} | null;
|
|
76
|
+
/** The kind a domain implies on its own: the public hosts by name, a
|
|
77
|
+
* self-hosted one when its first label says so (`gitlab.example.com`). */
|
|
78
|
+
export declare function kindFromDomain(domain: string): HostKind | null;
|
|
79
|
+
/** Which host a repository's remote is on, overrides first. */
|
|
80
|
+
export declare function detectHost(root: string, branch: string): Promise<GitHost>;
|
|
81
|
+
export declare function hostInfo(kind: HostKind | null, where: Pick<GitHost, "domain" | "webUrl" | "remote" | "source">): GitHost;
|
|
82
|
+
export declare function providerFor(host: GitHost): GitHostProvider | null;
|
|
83
|
+
/** Why there is no list: an unknown host says how to name it. */
|
|
84
|
+
export declare function unknownHost(host: GitHost): RequestList;
|
|
85
|
+
/** A check rollup as one word: any failure fails, anything unfinished is
|
|
86
|
+
* pending, and only finished successes (or skips) pass. No checks is null. */
|
|
87
|
+
export declare function checkRollup(items: unknown): "passing" | "failing" | "pending" | null;
|
|
88
|
+
/** Each check as clients list it: a name, the workflow that ran it, one state
|
|
89
|
+
* word and its page. Check runs and commit statuses read alike; failing
|
|
90
|
+
* first, then pending, then the rest, at most 100. */
|
|
91
|
+
export declare function checkRuns(items: unknown): Json[];
|
|
92
|
+
export declare const PROVIDERS: Record<HostKind, GitHostProvider>;
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { promisify } from "node:util";
|
|
3
|
+
import { git } from "./projects.js";
|
|
4
|
+
import { runCombined } from "./git-publish.js";
|
|
5
|
+
import { gitboy } from "./git-host-gitboy.js";
|
|
6
|
+
import { gitlab } from "./git-host-gitlab.js";
|
|
7
|
+
const exec = promisify(execFile);
|
|
8
|
+
export const HOST_KINDS = ["github", "gitlab", "gitboy"];
|
|
9
|
+
const PULL_TERMS = { short: "PR", long: "pull request", ref: "#" };
|
|
10
|
+
/** `git@host:owner/repo.git`, `ssh://git@host:2222/owner/repo.git`,
|
|
11
|
+
* `https://user@host/owner/repo` → the domain and the repository path. */
|
|
12
|
+
export function parseRemoteUrl(url) {
|
|
13
|
+
const text = url.trim();
|
|
14
|
+
const scp = /^(?:[^@/\s]+@)?([^:/\s]+):(?!\/)(.+)$/.exec(text);
|
|
15
|
+
if (scp && !/^[a-z][a-z0-9+.-]*:\/\//i.test(text))
|
|
16
|
+
return { domain: scp[1].toLowerCase(), path: clean(scp[2]) };
|
|
17
|
+
try {
|
|
18
|
+
const parsed = new URL(text);
|
|
19
|
+
if (!["http:", "https:", "ssh:", "git:", "git+ssh:", "ssh+git:"].includes(parsed.protocol) || !parsed.hostname)
|
|
20
|
+
return null;
|
|
21
|
+
return { domain: parsed.hostname.toLowerCase(), path: clean(parsed.pathname) };
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
return null;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
function clean(path) {
|
|
28
|
+
return path.replace(/^\/+/, "").replace(/\/+$/, "").replace(/\.git$/i, "");
|
|
29
|
+
}
|
|
30
|
+
/** The kind a domain implies on its own: the public hosts by name, a
|
|
31
|
+
* self-hosted one when its first label says so (`gitlab.example.com`). */
|
|
32
|
+
export function kindFromDomain(domain) {
|
|
33
|
+
if (domain === "github.com" || domain.endsWith(".github.com") || domain.endsWith(".ghe.com"))
|
|
34
|
+
return "github";
|
|
35
|
+
if (domain === "gitlab.com")
|
|
36
|
+
return "gitlab";
|
|
37
|
+
const first = domain.split(".")[0];
|
|
38
|
+
if (first === "gitlab")
|
|
39
|
+
return "gitlab";
|
|
40
|
+
if (first === "gitboy")
|
|
41
|
+
return "gitboy";
|
|
42
|
+
if (first === "github")
|
|
43
|
+
return "github";
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
function asKind(value) {
|
|
47
|
+
const v = value.trim().toLowerCase();
|
|
48
|
+
return HOST_KINDS.includes(v) ? v : null;
|
|
49
|
+
}
|
|
50
|
+
async function config(root, key) {
|
|
51
|
+
return (await git(root, "config", "--get", key).catch(() => "")).trim();
|
|
52
|
+
}
|
|
53
|
+
/** The remote a branch's requests belong to: its upstream's, else origin,
|
|
54
|
+
* else the only remote. */
|
|
55
|
+
async function remoteFor(root, branch) {
|
|
56
|
+
const remotes = (await git(root, "remote").catch(() => "")).split("\n").map(line => line.trim()).filter(Boolean);
|
|
57
|
+
const upstream = branch ? await config(root, `branch.${branch}.remote`) : "";
|
|
58
|
+
if (upstream && remotes.includes(upstream))
|
|
59
|
+
return upstream;
|
|
60
|
+
if (remotes.includes("origin"))
|
|
61
|
+
return "origin";
|
|
62
|
+
return remotes[0] ?? null;
|
|
63
|
+
}
|
|
64
|
+
/** Which host a repository's remote is on, overrides first. */
|
|
65
|
+
export async function detectHost(root, branch) {
|
|
66
|
+
const remote = await remoteFor(root, branch);
|
|
67
|
+
const url = remote ? await config(root, `remote.${remote}.url`) : "";
|
|
68
|
+
const parsed = url ? parseRemoteUrl(url) : null;
|
|
69
|
+
let kind = null;
|
|
70
|
+
let source = "none";
|
|
71
|
+
const remoteOverride = remote ? asKind(await config(root, `remote.${remote}.phrenHost`)) : null;
|
|
72
|
+
const domainOverride = parsed ? asKind(await config(root, `phren.${parsed.domain}.host`)) : null;
|
|
73
|
+
if (remoteOverride) {
|
|
74
|
+
kind = remoteOverride;
|
|
75
|
+
source = "remote-override";
|
|
76
|
+
}
|
|
77
|
+
else if (domainOverride) {
|
|
78
|
+
kind = domainOverride;
|
|
79
|
+
source = "domain-override";
|
|
80
|
+
}
|
|
81
|
+
else if (parsed && (kind = kindFromDomain(parsed.domain)))
|
|
82
|
+
source = "url";
|
|
83
|
+
return hostInfo(kind, { domain: parsed?.domain ?? null, webUrl: parsed ? `https://${parsed.domain}/${parsed.path}` : null, remote, source });
|
|
84
|
+
}
|
|
85
|
+
export function hostInfo(kind, where) {
|
|
86
|
+
const provider = kind ? PROVIDERS[kind] : null;
|
|
87
|
+
return { kind, name: provider?.name ?? "the git host", ...where, terms: provider?.terms ?? PULL_TERMS, supported: provider?.supported ?? false };
|
|
88
|
+
}
|
|
89
|
+
export function providerFor(host) {
|
|
90
|
+
return host.kind ? PROVIDERS[host.kind] : null;
|
|
91
|
+
}
|
|
92
|
+
/** Why there is no list: an unknown host says how to name it. */
|
|
93
|
+
export function unknownHost(host) {
|
|
94
|
+
const domain = host.domain ? ` ${host.domain}` : "";
|
|
95
|
+
return { available: false, reason: "unknown-host", pulls: [], current: null,
|
|
96
|
+
message: host.remote
|
|
97
|
+
? `Phren cannot tell which git host${domain} is. Name it with: git config remote.${host.remote}.phrenHost github|gitlab|gitboy`
|
|
98
|
+
: "This repository has no remote, so it has no pull or merge requests." };
|
|
99
|
+
}
|
|
100
|
+
// ---------------------------------------------------------------- GitHub
|
|
101
|
+
/** A check rollup as one word: any failure fails, anything unfinished is
|
|
102
|
+
* pending, and only finished successes (or skips) pass. No checks is null. */
|
|
103
|
+
export function checkRollup(items) {
|
|
104
|
+
if (!Array.isArray(items) || !items.length)
|
|
105
|
+
return null;
|
|
106
|
+
let pending = false;
|
|
107
|
+
for (const raw of items) {
|
|
108
|
+
const item = raw && typeof raw === "object" ? raw : {};
|
|
109
|
+
const conclusion = String(item.conclusion ?? "").toUpperCase(), state = String(item.state ?? "").toUpperCase();
|
|
110
|
+
const status = String(item.status ?? "").toUpperCase();
|
|
111
|
+
if (["FAILURE", "TIMED_OUT", "CANCELLED", "ACTION_REQUIRED", "STARTUP_FAILURE"].includes(conclusion) || ["FAILURE", "ERROR"].includes(state))
|
|
112
|
+
return "failing";
|
|
113
|
+
// A commit status has a state; a check run has a status and, once
|
|
114
|
+
// completed, a conclusion.
|
|
115
|
+
if (state && !status) {
|
|
116
|
+
if (state !== "SUCCESS")
|
|
117
|
+
pending = true;
|
|
118
|
+
}
|
|
119
|
+
else if (status !== "COMPLETED")
|
|
120
|
+
pending = true;
|
|
121
|
+
}
|
|
122
|
+
return pending ? "pending" : "passing";
|
|
123
|
+
}
|
|
124
|
+
/** Each check as clients list it: a name, the workflow that ran it, one state
|
|
125
|
+
* word and its page. Check runs and commit statuses read alike; failing
|
|
126
|
+
* first, then pending, then the rest, at most 100. */
|
|
127
|
+
export function checkRuns(items) {
|
|
128
|
+
if (!Array.isArray(items))
|
|
129
|
+
return [];
|
|
130
|
+
const order = { failing: 0, pending: 1, passing: 2, skipped: 3, neutral: 4 };
|
|
131
|
+
const runs = items.map(raw => {
|
|
132
|
+
const item = raw && typeof raw === "object" ? raw : {};
|
|
133
|
+
const conclusion = String(item.conclusion ?? "").toUpperCase(), state = String(item.state ?? "").toUpperCase();
|
|
134
|
+
const status = String(item.status ?? "").toUpperCase();
|
|
135
|
+
let word;
|
|
136
|
+
if (["FAILURE", "TIMED_OUT", "CANCELLED", "ACTION_REQUIRED", "STARTUP_FAILURE"].includes(conclusion) || ["FAILURE", "ERROR"].includes(state))
|
|
137
|
+
word = "failing";
|
|
138
|
+
else if (state && !status)
|
|
139
|
+
word = state === "SUCCESS" ? "passing" : "pending";
|
|
140
|
+
else if (status !== "COMPLETED")
|
|
141
|
+
word = "pending";
|
|
142
|
+
else if (conclusion === "SKIPPED")
|
|
143
|
+
word = "skipped";
|
|
144
|
+
else if (conclusion === "NEUTRAL" || conclusion === "STALE")
|
|
145
|
+
word = "neutral";
|
|
146
|
+
else
|
|
147
|
+
word = "passing";
|
|
148
|
+
const name = String(item.name ?? item.context ?? "").slice(0, 200) || "Check";
|
|
149
|
+
const workflow = typeof item.workflowName === "string" && item.workflowName ? item.workflowName.slice(0, 200) : undefined;
|
|
150
|
+
const url = String(item.detailsUrl ?? item.targetUrl ?? "");
|
|
151
|
+
return { name, state: word, ...(workflow ? { workflow } : {}), ...(/^https:\/\//.test(url) ? { url: url.slice(0, 2048) } : {}) };
|
|
152
|
+
});
|
|
153
|
+
return runs.sort((a, b) => order[a.state] - order[b.state]).slice(0, 100);
|
|
154
|
+
}
|
|
155
|
+
/** gh never prompts, never nags about updates, and talks to the remote's own
|
|
156
|
+
* domain (a GitHub Enterprise server as much as the public one). */
|
|
157
|
+
function ghEnv(host) {
|
|
158
|
+
return { ...process.env, GIT_CONFIG_NOSYSTEM: "1", GH_PROMPT_DISABLED: "1", GH_NO_UPDATE_NOTIFIER: "1", NO_COLOR: "1", ...(host.domain ? { GH_HOST: host.domain } : {}) };
|
|
159
|
+
}
|
|
160
|
+
const PULL_URL = /https:\/\/[^\s"'<>]+\/pull\/\d+/;
|
|
161
|
+
const github = {
|
|
162
|
+
kind: "github",
|
|
163
|
+
name: "GitHub",
|
|
164
|
+
terms: PULL_TERMS,
|
|
165
|
+
supported: true,
|
|
166
|
+
async list(root, branch, host) {
|
|
167
|
+
const run = (args) => exec("gh", args, { cwd: root, timeout: 15_000, maxBuffer: 4_194_304, env: ghEnv(host) });
|
|
168
|
+
const current = async () => {
|
|
169
|
+
if (!branch)
|
|
170
|
+
return null;
|
|
171
|
+
try {
|
|
172
|
+
const { stdout } = await run(["pr", "view", "--json", "number,title,url,state,isDraft,headRefName,headRefOid,baseRefName,statusCheckRollup,reviewDecision,mergeStateStatus,author,updatedAt"]);
|
|
173
|
+
const pull = JSON.parse(stdout || "null");
|
|
174
|
+
// gh falls back to another head's pull request; only this branch's counts.
|
|
175
|
+
if (!pull || typeof pull !== "object" || typeof pull.number !== "number" || pull.headRefName !== branch)
|
|
176
|
+
return null;
|
|
177
|
+
return { number: pull.number, title: String(pull.title ?? ""), url: String(pull.url ?? ""), head: branch,
|
|
178
|
+
base: String(pull.baseRefName ?? ""), draft: pull.isDraft === true, state: String(pull.state ?? ""), checks: checkRollup(pull.statusCheckRollup),
|
|
179
|
+
checkRuns: checkRuns(pull.statusCheckRollup),
|
|
180
|
+
...(typeof pull.reviewDecision === "string" && pull.reviewDecision ? { reviewDecision: pull.reviewDecision } : {}),
|
|
181
|
+
...(typeof pull.mergeStateStatus === "string" && pull.mergeStateStatus ? { mergeState: pull.mergeStateStatus } : {}),
|
|
182
|
+
...(typeof pull.headRefOid === "string" && pull.headRefOid ? { headSha: pull.headRefOid } : {}),
|
|
183
|
+
...(pull.author && typeof pull.author === "object" && typeof pull.author.login === "string" ? { author: pull.author.login } : {}),
|
|
184
|
+
...(typeof pull.updatedAt === "string" ? { updated: pull.updatedAt } : {}) };
|
|
185
|
+
}
|
|
186
|
+
catch {
|
|
187
|
+
return null;
|
|
188
|
+
}
|
|
189
|
+
};
|
|
190
|
+
try {
|
|
191
|
+
const [{ stdout }, mine] = await Promise.all([
|
|
192
|
+
run(["pr", "list", "--json", "number,title,headRefName,baseRefName,author,url,isDraft,state,updatedAt", "--limit", "50"]),
|
|
193
|
+
current(),
|
|
194
|
+
]);
|
|
195
|
+
const parsed = JSON.parse(stdout || "[]");
|
|
196
|
+
const pulls = (Array.isArray(parsed) ? parsed : []).map((pull) => {
|
|
197
|
+
const author = pull.author && typeof pull.author === "object" ? pull.author : {};
|
|
198
|
+
return { number: pull.number, title: pull.title, head: pull.headRefName, base: pull.baseRefName,
|
|
199
|
+
author: String(author.login ?? author.name ?? ""), url: pull.url, draft: pull.isDraft === true, state: pull.state, updated: pull.updatedAt };
|
|
200
|
+
});
|
|
201
|
+
return { available: true, pulls, current: mine };
|
|
202
|
+
}
|
|
203
|
+
catch {
|
|
204
|
+
return { available: false, reason: "auth", message: "The GitHub CLI (gh) is missing or not signed in on this computer. Install it, then run gh auth login there.", pulls: [], current: null };
|
|
205
|
+
}
|
|
206
|
+
},
|
|
207
|
+
async open(root, branch, draft, host) {
|
|
208
|
+
const env = ghEnv(host);
|
|
209
|
+
const run = (args, timeout) => runCombined("gh", args, root, timeout, env);
|
|
210
|
+
const version = await run(["--version"], 10_000);
|
|
211
|
+
if (version.missing || version.code !== 0) {
|
|
212
|
+
return { ok: false, reason: "missing", message: "The GitHub CLI (gh) is not installed on this computer. Install it, then run gh auth login there." };
|
|
213
|
+
}
|
|
214
|
+
const auth = await run(["auth", "status", ...(host.domain ? ["--hostname", host.domain] : [])], 15_000);
|
|
215
|
+
if (auth.code !== 0) {
|
|
216
|
+
return { ok: false, reason: "auth", message: "The GitHub CLI is not signed in on this computer. Run gh auth login there.", output: auth.output };
|
|
217
|
+
}
|
|
218
|
+
const result = await run(["pr", "create", "--fill", "--head", branch, ...(draft ? ["--draft"] : [])], 60_000);
|
|
219
|
+
const url = PULL_URL.exec(result.output)?.[0];
|
|
220
|
+
if (result.code === 0 && url)
|
|
221
|
+
return { ok: true, url, branch, draft };
|
|
222
|
+
if (url && /already exists/i.test(result.output))
|
|
223
|
+
return { ok: true, url, branch, existing: true };
|
|
224
|
+
return { ok: false, reason: "failed", output: result.timedOut ? `${result.output}\n[gh did not finish within 60 seconds]`.trim() : result.output || "gh pr create failed." };
|
|
225
|
+
},
|
|
226
|
+
async merge(root, request, host) {
|
|
227
|
+
// No --delete-branch: gh would also delete and leave the local branch,
|
|
228
|
+
// which may be an agent's checkout.
|
|
229
|
+
const args = ["pr", "merge", String(request.number), `--${request.method}`,
|
|
230
|
+
...(request.expectedHeadSha ? ["--match-head-commit", request.expectedHeadSha] : [])];
|
|
231
|
+
const result = await runCombined("gh", args, root, 60_000, ghEnv(host));
|
|
232
|
+
if (result.missing)
|
|
233
|
+
return { ok: false, reason: "missing", message: "The GitHub CLI (gh) is not installed on this computer." };
|
|
234
|
+
if (result.code === 0)
|
|
235
|
+
return { ok: true, number: request.number, method: request.method };
|
|
236
|
+
const output = result.output.trim();
|
|
237
|
+
if (/not mergeable|required status|review|protected|blocked|head branch was modified|match-head-commit|conflict/i.test(output))
|
|
238
|
+
return { ok: false, reason: "blocked", message: output.slice(0, 1000) };
|
|
239
|
+
if (/auth|login|401|403/i.test(output))
|
|
240
|
+
return { ok: false, reason: "auth", message: "The GitHub CLI is not signed in on this computer, or the account can't merge here. Run gh auth login there." };
|
|
241
|
+
return { ok: false, reason: "failed", message: output.slice(0, 1000) || "gh pr merge failed." };
|
|
242
|
+
},
|
|
243
|
+
};
|
|
244
|
+
export const PROVIDERS = { github, gitlab, gitboy };
|
|
@@ -7,7 +7,7 @@ interface Run {
|
|
|
7
7
|
}
|
|
8
8
|
/** One process with stdout and stderr interleaved in arrival order, bounded,
|
|
9
9
|
* never attached to a terminal and never prompting. */
|
|
10
|
-
export declare function runCombined(command: string, args: string[], cwd: string, timeout: number): Promise<Run>;
|
|
10
|
+
export declare function runCombined(command: string, args: string[], cwd: string, timeout: number, extraEnv?: NodeJS.ProcessEnv): Promise<Run>;
|
|
11
11
|
/** `git commit` of the index only: no `-a`, no `--no-verify`, no amend. A
|
|
12
12
|
* hook's refusal comes back as `{ ok: false, output }`, exactly as printed. */
|
|
13
13
|
export declare function gitCommit(cwd: string, message: unknown): Promise<Json>;
|
|
@@ -15,9 +15,19 @@ export declare function gitCommit(cwd: string, message: unknown): Promise<Json>;
|
|
|
15
15
|
* Never forced: no `--force`, no `+` refspec, no `--no-verify`. The default
|
|
16
16
|
* branch needs the phone's explicit `confirmDefault`. */
|
|
17
17
|
export declare function gitPush(cwd: string, confirmDefault: unknown): Promise<Json>;
|
|
18
|
-
/**
|
|
19
|
-
*
|
|
20
|
-
* `reason: "
|
|
21
|
-
*
|
|
18
|
+
/** Open a pull or merge request for the current branch on the remote's host
|
|
19
|
+
* (git-hosts.ts). GitHub's: `gh pr create --fill`; a missing or signed-out
|
|
20
|
+
* CLI is `{ ok: false, reason: "missing" | "auth" }`, the host's own refusal
|
|
21
|
+
* `reason: "failed"` with its output, and a request that already exists for
|
|
22
|
+
* the branch is success with `existing: true`. A stubbed host is
|
|
23
|
+
* `reason: "unsupported"`, an unrecognised one `reason: "unknown-host"`. */
|
|
22
24
|
export declare function gitPullRequest(cwd: string, draft: unknown): Promise<Json>;
|
|
25
|
+
/** Merge one pull or merge request on the remote's host. The host decides:
|
|
26
|
+
* its refusal (checks, approvals, conflicts, a head that moved past
|
|
27
|
+
* `expectedHeadSha`) is `{ ok: false, reason: "blocked", message }`. */
|
|
28
|
+
export declare function gitMergeRequest(cwd: string, data: unknown): Promise<Json>;
|
|
29
|
+
/** Connect (or, with an empty token, disconnect) this repository's GitLab or
|
|
30
|
+
* gitboy host: the token is checked against the host first and stored in the
|
|
31
|
+
* Hook's git-hosts.json with the account it signs in as. GitHub keeps gh's. */
|
|
32
|
+
export declare function gitHostToken(cwd: string, data: unknown): Promise<Json>;
|
|
23
33
|
export {};
|
|
@@ -4,6 +4,10 @@ import { BridgeError } from "./protocol.js";
|
|
|
4
4
|
import { git, gitRoot } from "./projects.js";
|
|
5
5
|
import { countGit } from "./metrics.js";
|
|
6
6
|
import { defaultBranch, invalidateTree } from "./git.js";
|
|
7
|
+
import { z } from "zod";
|
|
8
|
+
import { detectHost, providerFor, unknownHost } from "./git-hosts.js";
|
|
9
|
+
import { writeHostToken } from "./git-host-auth.js";
|
|
10
|
+
import { HostApiError } from "./git-host-http.js";
|
|
7
11
|
/** Finishing a session from the phone: commit what is staged, push the
|
|
8
12
|
* current branch, open a pull request. Each acts on the repository the
|
|
9
13
|
* existing /v1/git/* routes resolve (the pane's, a child's worktree, or a
|
|
@@ -13,11 +17,10 @@ import { defaultBranch, invalidateTree } from "./git.js";
|
|
|
13
17
|
const MAX_OUTPUT = 65_536;
|
|
14
18
|
const COMMIT_TIMEOUT_MS = 110_000;
|
|
15
19
|
const PUSH_TIMEOUT_MS = 110_000;
|
|
16
|
-
const PR_TIMEOUT_MS = 60_000;
|
|
17
20
|
const MAX_MESSAGE = 20_000;
|
|
18
21
|
/** One process with stdout and stderr interleaved in arrival order, bounded,
|
|
19
22
|
* never attached to a terminal and never prompting. */
|
|
20
|
-
export function runCombined(command, args, cwd, timeout) {
|
|
23
|
+
export function runCombined(command, args, cwd, timeout, extraEnv = {}) {
|
|
21
24
|
return new Promise(resolve => {
|
|
22
25
|
let output = "", truncated = false, timedOut = false, settled = false;
|
|
23
26
|
const finish = (run) => { if (!settled) {
|
|
@@ -26,7 +29,7 @@ export function runCombined(command, args, cwd, timeout) {
|
|
|
26
29
|
} };
|
|
27
30
|
const child = spawn(command, args, {
|
|
28
31
|
cwd, stdio: ["ignore", "pipe", "pipe"],
|
|
29
|
-
env: nonInteractiveGitEnv({ ...process.env, GIT_CONFIG_NOSYSTEM: "1", GIT_EDITOR: "true", GH_PROMPT_DISABLED: "1", GH_NO_UPDATE_NOTIFIER: "1", NO_COLOR: "1" }),
|
|
32
|
+
env: nonInteractiveGitEnv({ ...process.env, ...extraEnv, GIT_CONFIG_NOSYSTEM: "1", GIT_EDITOR: "true", GH_PROMPT_DISABLED: "1", GH_NO_UPDATE_NOTIFIER: "1", NO_COLOR: "1" }),
|
|
30
33
|
});
|
|
31
34
|
const append = (chunk) => {
|
|
32
35
|
if (truncated)
|
|
@@ -119,27 +122,72 @@ export async function gitPush(cwd, confirmDefault) {
|
|
|
119
122
|
}
|
|
120
123
|
return { ok: true, branch, remote, upstream: `${remote}/${destination}`, setUpstream: !tracked, output: run.output };
|
|
121
124
|
}
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
* is `{ ok: false, reason: "missing" | "auth" }
|
|
125
|
-
* `reason: "failed"` with its output
|
|
126
|
-
* the branch
|
|
125
|
+
/** Open a pull or merge request for the current branch on the remote's host
|
|
126
|
+
* (git-hosts.ts). GitHub's: `gh pr create --fill`; a missing or signed-out
|
|
127
|
+
* CLI is `{ ok: false, reason: "missing" | "auth" }`, the host's own refusal
|
|
128
|
+
* `reason: "failed"` with its output, and a request that already exists for
|
|
129
|
+
* the branch is success with `existing: true`. A stubbed host is
|
|
130
|
+
* `reason: "unsupported"`, an unrecognised one `reason: "unknown-host"`. */
|
|
127
131
|
export async function gitPullRequest(cwd, draft) {
|
|
128
132
|
const root = await repository(cwd);
|
|
129
133
|
const branch = await currentBranch(root);
|
|
130
|
-
const
|
|
131
|
-
|
|
132
|
-
|
|
134
|
+
const host = await detectHost(root, branch);
|
|
135
|
+
const provider = providerFor(host);
|
|
136
|
+
if (!provider) {
|
|
137
|
+
const { reason, message } = unknownHost(host);
|
|
138
|
+
return { ok: false, reason, message, host };
|
|
133
139
|
}
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
140
|
+
return { ...await provider.open(root, branch, draft === true, host), host };
|
|
141
|
+
}
|
|
142
|
+
const MergeBody = z.object({
|
|
143
|
+
number: z.number().int().positive(),
|
|
144
|
+
method: z.enum(["merge", "squash", "rebase"]).default("merge"),
|
|
145
|
+
expectedHeadSha: z.string().regex(/^[0-9a-f]{7,64}$/i).optional(),
|
|
146
|
+
deleteBranch: z.boolean().optional(),
|
|
147
|
+
});
|
|
148
|
+
/** Merge one pull or merge request on the remote's host. The host decides:
|
|
149
|
+
* its refusal (checks, approvals, conflicts, a head that moved past
|
|
150
|
+
* `expectedHeadSha`) is `{ ok: false, reason: "blocked", message }`. */
|
|
151
|
+
export async function gitMergeRequest(cwd, data) {
|
|
152
|
+
const request = MergeBody.parse(data);
|
|
153
|
+
const root = await repository(cwd);
|
|
154
|
+
const branch = (await git(root, "branch", "--show-current").catch(() => "")).trim();
|
|
155
|
+
const host = await detectHost(root, branch);
|
|
156
|
+
const provider = providerFor(host);
|
|
157
|
+
if (!provider) {
|
|
158
|
+
const { reason, message } = unknownHost(host);
|
|
159
|
+
return { ok: false, reason, message, host };
|
|
160
|
+
}
|
|
161
|
+
return { ...await provider.merge(root, request, host), host };
|
|
162
|
+
}
|
|
163
|
+
/** Connect (or, with an empty token, disconnect) this repository's GitLab or
|
|
164
|
+
* gitboy host: the token is checked against the host first and stored in the
|
|
165
|
+
* Hook's git-hosts.json with the account it signs in as. GitHub keeps gh's. */
|
|
166
|
+
export async function gitHostToken(cwd, data) {
|
|
167
|
+
const { token } = z.object({ token: z.string().max(4096) }).parse(data);
|
|
168
|
+
const root = await repository(cwd);
|
|
169
|
+
const branch = (await git(root, "branch", "--show-current").catch(() => "")).trim();
|
|
170
|
+
const host = await detectHost(root, branch);
|
|
171
|
+
const provider = providerFor(host);
|
|
172
|
+
if (!provider || !host.domain || !host.kind) {
|
|
173
|
+
const { reason, message } = unknownHost(host);
|
|
174
|
+
return { ok: false, reason, message, host };
|
|
175
|
+
}
|
|
176
|
+
if (host.kind === "github" || !provider.whoami)
|
|
177
|
+
return { ok: false, reason: "unsupported", message: "GitHub uses the GitHub CLI's sign-in: run gh auth login on this computer.", host };
|
|
178
|
+
const kind = host.kind;
|
|
179
|
+
if (!token.trim()) {
|
|
180
|
+
await writeHostToken(host.domain, kind, "");
|
|
181
|
+
return { ok: true, disconnected: true, domain: host.domain, host };
|
|
182
|
+
}
|
|
183
|
+
try {
|
|
184
|
+
const { user } = await provider.whoami(root, host, token.trim());
|
|
185
|
+
await writeHostToken(host.domain, kind, token.trim(), user || undefined);
|
|
186
|
+
return { ok: true, domain: host.domain, kind, ...(user ? { user } : {}), host };
|
|
187
|
+
}
|
|
188
|
+
catch (error) {
|
|
189
|
+
if (error instanceof HostApiError)
|
|
190
|
+
return { ok: false, reason: error.reason, message: error.reason === "auth" ? `${host.name} refused that token.` : error.message, host };
|
|
191
|
+
throw error;
|
|
137
192
|
}
|
|
138
|
-
const run = await runCombined("gh", ["pr", "create", "--fill", "--head", branch, ...(draft === true ? ["--draft"] : [])], root, PR_TIMEOUT_MS);
|
|
139
|
-
const url = PULL_URL.exec(run.output)?.[0];
|
|
140
|
-
if (run.code === 0 && url)
|
|
141
|
-
return { ok: true, url, branch, draft: draft === true };
|
|
142
|
-
if (url && /already exists/i.test(run.output))
|
|
143
|
-
return { ok: true, url, branch, existing: true };
|
|
144
|
-
return { ok: false, reason: "failed", output: run.timedOut ? `${run.output}\n[gh did not finish within ${PR_TIMEOUT_MS / 1000} seconds]`.trim() : run.output || "gh pr create failed." };
|
|
145
193
|
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { type Json } from "./protocol.js";
|
|
2
|
+
import type { ChangedFile } from "./changes.js";
|
|
3
|
+
/** One file's text at HEAD, in the index or at a commit. A path the tree does
|
|
4
|
+
* not hold answers `missing: true` (an added or deleted side), a file larger
|
|
5
|
+
* than 2 MB `tooLarge: true`, and bytes with a NUL `binary: true`, each with
|
|
6
|
+
* no text. */
|
|
7
|
+
export declare function gitFile(cwd: string, ref: unknown, rawPath: unknown): Promise<Json>;
|
|
8
|
+
/** The files a patch touches, from its `---`/`+++` lines. Rename, mode and
|
|
9
|
+
* binary patches are refused: only text hunks are staged one at a time. */
|
|
10
|
+
export declare function patchFiles(patch: string): string[];
|
|
11
|
+
/** Apply a patch of one file's hunks to the index only: staging them, or with
|
|
12
|
+
* `reverse` unstaging them. The working tree is never touched. Git checks the
|
|
13
|
+
* patch first; a hunk that no longer applies (the file moved on) is Git's
|
|
14
|
+
* refusal as `{ ok: false, output }`. */
|
|
15
|
+
export declare function gitApply(cwd: string, rawPatch: unknown, reverse: unknown): Promise<Json>;
|
|
16
|
+
/** One session's recorded edits, oldest first, folded by file: how often each
|
|
17
|
+
* file changed, the lines added and removed across those edits, and each
|
|
18
|
+
* edit's patch. Only edits inside `root` (the session's repository) count;
|
|
19
|
+
* `others` says how many touched other repositories. */
|
|
20
|
+
export declare function sessionChanges(root: string, history: {
|
|
21
|
+
toolUseId: string;
|
|
22
|
+
files: ChangedFile[];
|
|
23
|
+
}[]): Json;
|