@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,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
- /** `gh pr create --fill` for the current branch. A missing or signed-out gh
19
- * is `{ ok: false, reason: "missing" | "auth" }`; gh's own refusal is
20
- * `reason: "failed"` with its output. A pull request that already exists for
21
- * the branch comes back as success with `existing: true`. */
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
- const PULL_URL = /https:\/\/[^\s"'<>]+\/pull\/\d+/;
123
- /** `gh pr create --fill` for the current branch. A missing or signed-out gh
124
- * is `{ ok: false, reason: "missing" | "auth" }`; gh's own refusal is
125
- * `reason: "failed"` with its output. A pull request that already exists for
126
- * the branch comes back as success with `existing: true`. */
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 version = await runCombined("gh", ["--version"], root, 10_000);
131
- if (version.missing || version.code !== 0) {
132
- return { ok: false, reason: "missing", message: "The GitHub CLI (gh) is not installed on this computer. Install it, then run gh auth login there." };
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
- const auth = await runCombined("gh", ["auth", "status"], root, 15_000);
135
- if (auth.code !== 0) {
136
- return { ok: false, reason: "auth", message: "The GitHub CLI is not signed in on this computer. Run gh auth login there.", output: auth.output };
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;
@@ -0,0 +1,170 @@
1
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
2
+ import { tmpdir } from "node:os";
3
+ import path from "node:path";
4
+ import { BridgeError } from "./protocol.js";
5
+ import { git, gitRoot, withGitReadDeadline } from "./projects.js";
6
+ import { invalidateTree, repositoryPath } from "./git.js";
7
+ /** What a review screen needs beyond status and patches: a file's text at
8
+ * HEAD, in the index or at a commit (so a real diff editor can compare whole
9
+ * files), staging or unstaging single hunks, and the edits one agent session
10
+ * made. */
11
+ const MAX_FILE = 2_000_000;
12
+ const MAX_PATCH = 2_000_000;
13
+ async function repository(cwd) {
14
+ const root = await gitRoot(cwd);
15
+ if (!root)
16
+ throw new BridgeError(409, "This pane is not in a Git repository.", { code: "git-not-repository" });
17
+ return root;
18
+ }
19
+ /** `HEAD`, `INDEX` (stage 0) or a commit hash. */
20
+ function revision(raw) {
21
+ if (raw === "HEAD" || raw === "INDEX")
22
+ return raw;
23
+ if (typeof raw === "string" && /^[0-9a-fA-F]{4,64}$/.test(raw))
24
+ return raw;
25
+ throw new BridgeError(400, "Name HEAD, INDEX or a commit hash.");
26
+ }
27
+ /** One file's text at HEAD, in the index or at a commit. A path the tree does
28
+ * not hold answers `missing: true` (an added or deleted side), a file larger
29
+ * than 2 MB `tooLarge: true`, and bytes with a NUL `binary: true`, each with
30
+ * no text. */
31
+ export function gitFile(cwd, ref, rawPath) {
32
+ return withGitReadDeadline(async () => {
33
+ const root = await repository(cwd);
34
+ const rev = revision(ref);
35
+ const file = await repositoryPath(root, rawPath);
36
+ let spec;
37
+ if (rev === "INDEX")
38
+ spec = `:0:${file}`;
39
+ else {
40
+ let commit;
41
+ try {
42
+ commit = (await git(root, "rev-parse", "--verify", "--end-of-options", `${rev}^{commit}`)).trim();
43
+ }
44
+ catch {
45
+ throw new BridgeError(404, "This repository has no such commit.", { code: "git-unknown-commit" });
46
+ }
47
+ spec = `${commit}:${file}`;
48
+ }
49
+ const kind = await git(root, "cat-file", "-t", spec).then(out => out.trim(), () => "");
50
+ if (!kind)
51
+ return { path: file, ref: rev, missing: true, text: "" };
52
+ if (kind !== "blob")
53
+ return { path: file, ref: rev, missing: true, text: "", kindOf: kind };
54
+ const size = Number((await git(root, "cat-file", "-s", spec)).trim()) || 0;
55
+ if (size > MAX_FILE)
56
+ return { path: file, ref: rev, size, tooLarge: true, text: "" };
57
+ const text = await git(root, "cat-file", "blob", spec);
58
+ if (text.slice(0, 8000).includes("\0"))
59
+ return { path: file, ref: rev, size, binary: true, text: "" };
60
+ return { path: file, ref: rev, size, text };
61
+ });
62
+ }
63
+ /** A name in a patch header: `a/x` or a C-quoted `"a/x\ty"`. */
64
+ function headerName(raw) {
65
+ let name = raw.trim();
66
+ if (name === "/dev/null")
67
+ return null;
68
+ if (name.startsWith("\"")) {
69
+ try {
70
+ name = JSON.parse(name);
71
+ }
72
+ catch {
73
+ throw new BridgeError(400, "This patch names a file Phren cannot read.");
74
+ }
75
+ }
76
+ if (!/^[ab]\//.test(name))
77
+ throw new BridgeError(400, "This patch is not a Git patch.");
78
+ return name.slice(2);
79
+ }
80
+ /** The files a patch touches, from its `---`/`+++` lines. Rename, mode and
81
+ * binary patches are refused: only text hunks are staged one at a time. */
82
+ export function patchFiles(patch) {
83
+ const files = new Set();
84
+ let hunks = 0;
85
+ for (const line of patch.split("\n")) {
86
+ if (/^(?:rename|copy) (?:from|to) |^(?:old|new|deleted file|new file) mode |^GIT binary patch|^Binary files /.test(line)) {
87
+ throw new BridgeError(400, "Only text hunks can be staged one at a time. Stage the whole file instead.");
88
+ }
89
+ if (line.startsWith("--- ") || line.startsWith("+++ ")) {
90
+ const name = headerName(line.slice(4).replace(/\t.*$/, ""));
91
+ if (name)
92
+ files.add(name);
93
+ }
94
+ if (line.startsWith("@@ "))
95
+ hunks++;
96
+ }
97
+ if (!files.size || !hunks)
98
+ throw new BridgeError(400, "This patch has no hunks.");
99
+ if (files.size > 1)
100
+ throw new BridgeError(400, "Stage hunks of one file at a time.");
101
+ return [...files];
102
+ }
103
+ /** Apply a patch of one file's hunks to the index only: staging them, or with
104
+ * `reverse` unstaging them. The working tree is never touched. Git checks the
105
+ * patch first; a hunk that no longer applies (the file moved on) is Git's
106
+ * refusal as `{ ok: false, output }`. */
107
+ export async function gitApply(cwd, rawPatch, reverse) {
108
+ if (typeof rawPatch !== "string" || !rawPatch.trim())
109
+ throw new BridgeError(400, "Choose a hunk to stage.");
110
+ if (rawPatch.length > MAX_PATCH || rawPatch.includes("\0"))
111
+ throw new BridgeError(400, "This patch is too large.");
112
+ const root = await repository(cwd);
113
+ const [file] = patchFiles(rawPatch);
114
+ await repositoryPath(root, file);
115
+ const scratch = await mkdtemp(path.join(tmpdir(), "phren-apply-"));
116
+ const patchFile = path.join(scratch, "hunk.patch");
117
+ try {
118
+ await writeFile(patchFile, rawPatch.endsWith("\n") ? rawPatch : rawPatch + "\n", { mode: 0o600 });
119
+ const args = ["apply", "--cached", "--whitespace=nowarn", ...(reverse === true ? ["-R"] : []), "--", patchFile];
120
+ invalidateTree(root);
121
+ try {
122
+ await git(root, "apply", "--check", ...args.slice(1));
123
+ }
124
+ catch (error) {
125
+ return { ok: false, output: error instanceof BridgeError ? error.message.replace(/^Git apply failed: /, "") : "git apply refused this hunk." };
126
+ }
127
+ await git(root, ...args);
128
+ return { ok: true, path: file, staged: reverse !== true };
129
+ }
130
+ finally {
131
+ invalidateTree(root);
132
+ await rm(scratch, { recursive: true, force: true });
133
+ }
134
+ }
135
+ /** One session's recorded edits, oldest first, folded by file: how often each
136
+ * file changed, the lines added and removed across those edits, and each
137
+ * edit's patch. Only edits inside `root` (the session's repository) count;
138
+ * `others` says how many touched other repositories. */
139
+ export function sessionChanges(root, history) {
140
+ const files = new Map();
141
+ let others = 0, calls = 0;
142
+ for (const row of history) {
143
+ let counted = false;
144
+ for (const change of row.files) {
145
+ if (change.root !== root) {
146
+ others++;
147
+ continue;
148
+ }
149
+ counted = true;
150
+ const entry = files.get(change.path) ?? { path: change.path, status: change.status, added: 0, removed: 0, edits: [], redacted: false, binary: false };
151
+ entry.added += change.added;
152
+ entry.removed += change.removed;
153
+ entry.redacted ||= change.redacted === true;
154
+ entry.binary ||= change.binary === true;
155
+ // The first edit's status says whether the session added the file.
156
+ if (entry.edits.length && change.status === "D")
157
+ entry.status = "D";
158
+ if (entry.edits.length < 50)
159
+ entry.edits.push({ toolUseId: row.toolUseId, status: change.status, added: change.added, removed: change.removed,
160
+ patch: change.patch.slice(0, 200_000), ...(change.patch.length > 200_000 || change.truncated ? { truncated: true } : {}) });
161
+ files.delete(change.path);
162
+ files.set(change.path, entry);
163
+ }
164
+ if (counted)
165
+ calls++;
166
+ }
167
+ const list = [...files.values()].reverse().slice(0, 300);
168
+ return { root, calls, files: list, totalFiles: files.size, others,
169
+ additions: list.reduce((n, f) => n + f.added, 0), deletions: list.reduce((n, f) => n + f.removed, 0) };
170
+ }
@@ -0,0 +1,14 @@
1
+ import { type Json } from "./protocol.js";
2
+ /** Switch to a local branch, or create one (from `startPoint`, a branch or
3
+ * remote-tracking branch, else HEAD) and switch to it. A remote-tracking
4
+ * start point sets it as the upstream. Uncommitted tracked edits travel with
5
+ * a switch in Git; the phone must say it knows (`carryChanges`), and Git
6
+ * still refuses whatever would be overwritten. */
7
+ export declare function gitCheckout(cwd: string, body: Json): Promise<Json>;
8
+ /** Fetch the upstream's remote (else `origin`) and prune what it deleted, so
9
+ * ahead/behind counts and remote branches are current. Tags are not fetched. */
10
+ export declare function gitFetch(cwd: string): Promise<Json>;
11
+ /** Fetch, then fast-forward the current branch to its upstream. Never a merge
12
+ * commit or a rebase: a branch that has diverged is refused by Git and the
13
+ * phone shows why. */
14
+ export declare function gitPull(cwd: string): Promise<Json>;